The 40x Solution: Scaling Transactions State
The 40x Solution: Scaling Transactions State
By: Harsh Sharma Special Thanks: Navdeep Agarwal, Mayur Jadhav
Merging
Consider a scenario where you have a cab-hailing service, in which every ride goes through different stages — like being requested, accepted by a driver, in progress, completed, or canceled. Each of these updates comes as a separate event with details like timestamps, driver info, and fare.
These daily logs capture essential details such as ride IDs, driver and passenger IDs, fare details, and crucial incremental updates like changes in ride status. For instance, they track whether a ride is requested, accepted by a driver, on the way for pickup, in progress, completed, or canceled, along with timestamps marking each status change.
The challenge is that these events arrive separately, making it hard to get a clear, complete picture of a ride in one place. Instead of storing multiple entries for the same ride, we need a way to keep just one row per ride that updates with the latest information while keeping important details. This makes it easier to track rides, analyze data, and keep things organized.
In some business domains, transaction logs may be generated in a single day, while in others, such as grocery or logistics, they may arrive over multiple days. We intend to capture the entire order journey in a single row with 60+ attributes for analytics.
> Each order is represented as a single row with up to 60+ attributes.
Can't we solve it using a transactional database like Postgres/Cassandra?
It's a valid question — and the answer lies in the nature of the data we're dealing with.
We're not storing the transactions themselves, but rather the transaction logs: high-volume, incremental updates that trace the lifecycle of a transaction. In some cases, a single transaction might generate 30,000 log entries.
Transactional databases like PostgreSQL (OLTP systems) are optimized for low-latency, high-concurrency workloads involving small, discrete operations — such as updating a bank balance or recording a user action in real time. They excel at per-transaction updates and are highly reliable for that use case.
However, scaling OLTP systems to handle something like 300,000 requests per second — especially for log ingestion — requires significant compute and clustering infrastructure to ensure availability and fault tolerance. This level of horizontal scaling is both resource-intensive and cost-prohibitive.
In short, while OLTP systems are great for operational data, they're overkill for log-heavy workloads at this scale. What we need is a system built for high-throughput ingestion and efficient handling of append-only log data — something more aligned with log-structured or distributed streaming architectures.
What about using an analytics engine like Athena with Parquet?
This is what we tried at first but soon realised its limitations. We can fire SQL queries on tools like AWS Athena with our transaction data sitting on an S3 bucket stored in columnar file format like parquet. By using powerful features like windowing and partitioning, we can extract the key business metrics and insights needed for decision-making. The final result is then saved to a cloud storage bucket like S3, ready for analysis.
However, here's the challenge: for 300 odd days' worth of transaction logs, such a SQL query could require scanning 30 TB of data. This is a huge amount of information to process, and as data volumes grow, the time and cost to scan this data also increases.
The Problem: Scaling Challenges in Processing Transaction Logs
While the above solution works in theory, scalability becomes a huge issue as the data grows.
- Transaction Logs Across Multiple Days: Imagine you have a logistics order, and you need to aggregate data like the earliest delivery date. Transaction logs for that order might span days or even weeks. To get the correct data, you need to read through all the logs, even those generated over long periods. - Rolling Window: If the business needs to process data for the last 90 days (from day T-90 to day T), every day you have to reprocess the logs for a rolling window of 90 days. In our case, for an ETL involving logistics orders, we were reading transaction logs from the beginning every day, transforming them and storing the output in an S3 bucket. We witnessed severe performance deterioration as the number of days increased (think of reading 500 days of data at once, transforming and storing it).
Cost and Time Implications
1. High Data Processing Costs. Processing 90 days of data every day means reading huge chunks of data. One of our Athena queries was scanning 150GB of data just to process a single day's logs. CTEs that break the query into logical chunks further drive up the cost. 2. Limited Support for Incremental Processing. Athena doesn't natively support compaction or incremental updates. Every query reads the entire dataset. 3. Increased Computational Costs. More data means more resources, and the cost keeps spiraling. 4. Slower Processing Times. Constantly scanning and transforming large datasets results in significant delays. 5. Overlapping Output. Rolling 90-day windows mean results overlap each day — lots of repeated work. 6. Increased Storage Costs. You're not just paying for processing, but for storing redundant overlapping output. 7. Lack of Control Over Compute. Athena scales dynamically. You have no control over how much processing power you get or how quickly it scales, leading to unpredictability in both cost and performance.
In short, while the solution might work for smaller datasets, as transactions grow and data needs become more complex, the scalability and cost-effectiveness quickly deteriorate.
Optimizing Data Processing with Incremental Updates
The solution lies in maintaining a state and updating the aggregate fields as new data arrives. This drastically reduces the data you need to process and enables more efficient, real-time updates.
Incremental Data Processing
State Maintenance:
- Instead of reprocessing 90 days of data, we read only the transaction logs of the last day. - We then transform the data and upsert it into a maintained state (e.g., a data lake or warehouse). - The state now contains the current aggregates and can be updated incrementally.
Cost Reduction:
- By processing only new data, you avoid scanning large chunks of historical data (9TB vs. 5GB). - This reduces both compute and storage costs. - Overlapping output from a rolling-window approach is eliminated.
The Solution: Apache Spark & Apache Hudi
To overcome Athena's limitations, we need a tool that is better suited for distributed computing and incremental data processing. This is where Apache Spark and Apache Hudi come into play. Spark's distributed computing capabilities coupled with Hudi's incremental updates solve our scalability problem.
Optimizing Spark for Scalable Queries
A poorly written Spark script can blow up cluster runtimes and erode all the cost efficiencies of migrating away from Athena. To ensure efficiency in Spark:
Avoid/minimize expensive joins — use windowing and partitioning on the same dataframe:
- Joins in Spark can be very expensive on large dataframes. - Instead of complex joins (common when replicating SQL logic with multiple CTEs), use windowing and partitioning to generate aggregate fields such as earliest delivery time or latest order status directly on the base dataframe. - This leverages Spark's in-memory computing and avoids the overhead of multiple joins.
Configurable aggregate columns:
- This approach makes it easy to add new aggregate columns through a configuration, without writing much new code.
Creating and Updating State with Apache Hudi
State Management:
- Hudi stores data on systems like HDFS, S3, or GCS and handles incremental updates efficiently. - Each transaction log can be uniquely identified by a primary key (e.g., tid and oid). This allows Hudi to manage upserts and ensure aggregate fields are updated whenever new logs arrive.
Time Travel and Data Consistency:
- Hudi offers time travel, allowing us to query historical data as it existed at a specific point in time. - Hudi also provides ACID consistency for writes to the data lake.
Near Real-Time Data Availability:
- With Hudi's real-time ingestion, you can process data as it arrives and immediately reflect updates in your aggregates.
How It Works in Practice
- As Spark processes the new day's transaction logs, it creates a processed incremental dataframe holding the latest data for each transaction and its aggregates. - This dataframe is upserted into Apache Hudi, so any changes to aggregate fields are reflected in the final output. - As data flows in, aggregate fields (such as earliest delivery time) update incrementally — no large-scale reprocessing. - The final results are quickly available for querying.
window_spec = Window.partitionBy("t_id", "o_id").orderBy(col("context_ts").desc())
df = df.withColumn(
"latest_ride_status",
first(col("ride_status"), ignorenulls=True).over(window_spec),
)
df = df.withColumn( "earliestrideonway", last( when(col("ridestatus") == "On-way", col("contextts")).otherwise(None), ignorenulls=True, ).over(windowspec), )
Cost and Time Calculations: Athena vs. Spark
The savings from switching are significant on daily runs and become even more substantial on monthly or yearly scale. As transaction data grows, Athena costs keep rising; Spark-based ETL costs remain much more stable.
When you scale this up to multiple ETLs (logistics, ride-hailing, groceries, etc.), the total savings become immense. Each additional ETL run is processed with the same level of efficiency, and the savings multiply.
Advantages of the Optimized Approach (Spark with Hudi)
- Better control over resources. With Spark, you can scale compute up or down based on data volume. If data size grows 2x or 3x, Spark adjusts to maintain efficiency. - Cost efficiency. Our optimized Spark-based ETL was 40x cheaper than Athena for processing the same 90 days of transaction data. - Time efficiency. For one domain, runtime dropped from 90 minutes to 21 minutes. - Scalability. Spark scales effectively as data grows, without the exponential cost curve we saw with Athena.
Conclusion
By using Apache Spark and Apache Hudi, we achieved:
- Incremental updates to aggregate fields. - Significant cost reduction in compute and storage by processing only new data. - Scalable, efficient processing of large datasets without relying on costly joins. - State management that supports fast querying and ACID transactions for consistency.
This approach optimizes the processing pipeline and scales gracefully as data volume grows.
---
At Dataorc we design solutions with scale and cost-effectiveness in mind. With experience building petabyte-scale data platforms and 400k TPS portals from scratch for enterprises and startups, we believe in solutions that grow with your business. Reach out for a free open-consulting session with our tech team — about this, or anything data.