Skip to main content
← PROBLEMS / SYSTEM-DESIGN
An end-to-end domain learning journey

Design a Late-Data Watermarking
& Stateful Aggregation Pipeline.

Mobile devices buffering offline for 30 minutes to 6 hours cause unbounded state growth or dropped sessions in naive streaming aggregators.
Start the journey5 stages
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

When a single bottleneck threatens end-to-end availability, set a 30-minute event-time watermark (`withWatermark('event_time', '30 minutes')`) backed by `RocksDBStateStoreProvider`, and route >30-minute outliers to a dead-letter/backfill side path.

TL;DR30-second simplified summary
▾

Core Mechanics: Mobile apps in subways or airplanes buffer telemetry locally and flush events 30 minutes (or 6 hours) after they occurred.

Visual & Structural Flow: Depicts 30-Min Event-Time Watermark + RocksDB State + Ultra-Late DLQ (Kafka (64 parts) -> Spark (15s batch) -> RocksDB State -> Delta/Iceberg + DLQ); Off-Heap RocksDB State Store with Incremental S3 Checkpoints (15s Micro-Batch -> RocksDB Provider -> Watermark Evictor -> S3 Checkpoint + DLQ).

Trade-Offs & Production: Setting a 6-hour watermark forces the state store to retain 40,000 × 21,600 = 864M events' worth of open window state and delays final window emissions by 6 hours. Bound state, protect SLAs, and preserve auditability: 30-Minute Watermark: withWatermark("event_time", "30 minutes") tracks max(event_time) - 30m, capturing 99%+ of subway.

Failure Modes & Application: Event-time watermarking and off-heap RocksDB state power production streaming: Apache Flink & Spark Structured Streaming: Both use RocksDB state backends to scale terabytes of keyed window state beyond JVM RAM.

Before you begin · Building blocksAlready know these? Jump to Stage 01 ↓
Spark Structured Streaming & Watermarking
Spark Structured Streaming models unbounded streams as continuously appended tables. Event-time watermarks bound how long in-memory or RocksDB state is retained for late-arriving records, enabling fault-tolerant stateful aggregations and Kafka-to-Lakehouse pip...
Apache Spark Data Engineering
Apache Spark processes petabyte-scale batch and streaming data across distributed clusters using lazy DAG execution, the Catalyst query optimizer, Tungsten off-heap memory, and Adaptive Query Execution (AQE) over columnar formats like Parquet, Delta Lake, and...
Full walkthrough · 5 stages
01
STAGE 01 · WHY IT MATTERSL4 · FUNDAMENTALS

Why event-time vs. processing-time breaks mobile analytics.

Why this matters: The mechanism: understand how Why event-time vs. processing-time breaks mobile analytics works from first principles.

Think of Why event-time vs. processing-time breaks mobile analytics as the intuition layer for Design a Late-Data Watermarking & Stateful Aggregation Pipeline: The mechanism: understand how Why event-time vs. processing-time breaks mobile analytics works from first principles.

Mobile apps in subways or airplanes buffer telemetry locally and flush events 30 minutes (or 6 hours) after they occurred. Grouping by processing time misattributes sessions, while keeping every 5-minute window open forever in JVM heap to wait for 6-hour stragglers crashes executors with OOM over months of operation.

02
STAGE 02 · IMPACTL5 · APPLIED DESIGN

Unbounded state OOMs, small-file explosions, and silent data loss.

Why this matters: The problem: see what breaks without Unbounded state OOMs, small-file explosions, and silent data loss under real concurrency or scale.

At 40,000 events/sec across 64 Kafka partitions (600,000 events per 15 s micro-batch):

  1. JVM State Store OOM: Default HDFS-backed in-memory state stores hold all open windows in executor heap, triggering Full GC and OOM kills.
  2. Silent Outlier Loss: Dropping events older than 30 minutes silently loses 6-hour audit records unless routed to a backfill path.
  3. Small-File Explosion: Writing raw 15 s micro-batches to S3 creates thousands of tiny Parquet files/hour.
Watermark & State Eviction

30-Min Event-Time Watermark + RocksDB State + Ultra-Late DLQ

Kafka (64 parts)Spark (15s batch)RocksDB StateDelta/Iceberg + DLQ1. 40k/s -> Watermark =max(event_ts) - 30m2. Update 5m windows >= Watermark(off-heap)3. Close & evict windows <Watermark4. Event > 30m late -> side-outputaudit DLQ

RocksDB keeps 30 minutes of active windows off-heap while ultra-late (>30m) records route to a backfill DLQ.

Engineering Decision Framework
Problem
How to implement Design a Late-Data Watermarking & Stateful Aggregation Pipeline without hitting unbounded tail latency, state divergence, or operational fragility.
Naive Solution
Use a single unpartitioned path with unbounded retries and synchronous global coordination.
Why It Fails
Global coordination serializes throughput under load, while unbounded retries amplify transient stalls into full outages.
Alternatives
Compare synchronous strict-consistency paths against bounded asynchronous replication, local caching, or partitioned ownership.
Engineering Decision
When a single bottleneck threatens end-to-end availability, set a 30-minute event-time watermark (withWatermark('event_time', '30 minutes')) backed by RocksDBStateStoreProvider, and route >30-minute outliers to a dead-letter/backfill side path.
Trade-Offs
Gains predictable p99 latency and fault isolation in exchange for explicit bounding, observability, and slightly higher implementation complexity.
Decision Exercise · Make the Call

When Design a Late-Data Watermarking & Stateful Aggregation Pipeline experiences a sudden 5x traffic spike alongside a slow downstream dependency, which engineering choice best protects system stability?

03
STAGE 03 · NAIVE SOLUTIONL5 · APPLIED DESIGN

Naive `6-hour` watermarks or unwatermarked `groupBy`.

Why this matters: Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.

Think of Naive 6-hour watermarks or unwatermarked groupBy as the intuition layer for Design a Late-Data Watermarking & Stateful Aggregation Pipeline: Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.

Setting a 6-hour watermark forces the state store to retain 40,000 × 21,600 = 864M events' worth of open window state and delays final window emissions by 6 hours. Conversely, omitting a watermark entirely leaks state until the cluster OOMs.

Lifecycle & Failure Recovery

Naive `6-hour` watermarks or unwatermarked `groupBy`

admitsucceedbudget exceededInitializedProcessingInvariant MetDegraded Fallback
04
STAGE 04 · ENTERPRISE SOLUTIONL6 · SCALE & TRADE-OFFS

Enterprise solution: 30-Min Watermark + RocksDB + Side-Output DLQ.

Why this matters: Operational control: configure bounds, failure handling, and safe production defaults.

Bound state, protect SLAs, and preserve auditability:

  • 30-Minute Watermark: withWatermark("event_time", "30 minutes") tracks max(event_time) - 30m, capturing 99%+ of subway buffering while letting RocksDB evict closed 5-minute windows.
  • Off-Heap RocksDBStateStoreProvider: Moves state out of JVM heap onto local NVMe SSDs with incremental checkpointing to S3.
  • Ultra-Late Side Output (mapGroupsWithState): Events arriving > 30m late are tagged and written to a late_events_audit Delta/Parquet table for hourly batch merge/backfill.
State Store Architecture

Off-Heap RocksDB State Store with Incremental S3 Checkpoints

15s Micro-Batch64 partitions, 600k eventsRocksDB ProviderOff-heap MemTable + SSTablesWatermark EvictorPurges window_end < WMS3 Checkpoint + DLQIncremental delta + lat…

RocksDB bounds executor JVM heap flat across months of 40k/sec streaming while incremental checkpoints guard recovery.

spark.conf.set(
    "spark.sql.streaming.stateStore.providerClass",
    "org.apache.spark.sql.execution.streaming.state.RocksDBStateStoreProvider"
)

windowed = (
    events_df
    .withWatermark("event_time", "30 minutes")
    .groupBy(window("event_time", "5 minutes"), "device_id")
    .agg(count("*").alias("events"), sum("bytes").alias("total_bytes"))
)
05
STAGE 05 · SYSTEM DESIGN APPLICATIONSL7 · STAFF / PRINCIPAL

Where watermarking and RocksDB state stores are used.

Why this matters: Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.

Event-time watermarking and off-heap RocksDB state power production streaming:

  • Apache Flink & Spark Structured Streaming: Both use RocksDB state backends to scale terabytes of keyed window state beyond JVM RAM.
  • Lakehouse Medallion Pipelines: Stream late events into Bronze/DLQ and run periodic MERGE INTO Silver tables.
Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

Why does switching to `RocksDBStateStoreProvider` with a 30-minute watermark solve executor OOMs without losing 6-hour late events?

Recommended Learning Flow