Skip to main content
← CONCEPTS / DATA ENGINEERING
An end-to-end domain learning journey

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 pipelines.
Start the journey7 sections· Last modified Nov 16, 2026
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

When durability and read throughput pull in opposite directions, always pair event-time windows or mapGroupsWithState with an explicit watermark and RocksDB state store so late data is handled accurately without unbounded state OOM.

TL;DR30-second simplified summary
▾

Core Mechanics: Spark Structured Streaming models unbounded streams as continuously appended tables.

Visual & Structural Flow: Depicts Micro-Batch Offset WAL & RocksDB State Store (Kafka Offset Log -> Streaming Engine -> RocksDB StateStore -> S3 Checkpoint WAL); Event-Time Watermark Window State Machine (WINDOW OPEN -> LATE ACCEPTED -> DROPPED & EVICTED).

Trade-Offs & Production: Always pair event-time windows or mapGroupsWithState with an explicit watermark and RocksDB state store so late data is handled accurately without unbounded state OOM.

Failure Modes & Application: Always pair event-time windows or mapGroupsWithState with an explicit watermark and RocksDB state store so late data is handled accurately without unbounded state OOM.

Before you begin · Building blocksAlready know these? Jump to Stage 01 ↓
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 · 7 stages
01
STAGE 01 · WHAT IT ISL4 · FUNDAMENTALS

What is Spark Structured Streaming & Watermarking.

Why this matters: The mechanism: understand how Spark Structured Streaming & Watermarking works from first principles.

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 pipelines.

Core Pillars:

  • Micro-Batch vs Continuous: Micro-batch gives exactly-once end-to-end guarantees and full stateful SQL; Continuous mode targets ~1ms latency for stateless map/filter.
  • Watermark Formula: Watermark = max(event_time_seen) - delayThreshold. Windows older than the watermark are finalized and evicted.
  • Stateful Timeout: mapGroupsWithState supports EventTimeTimeout (driven by watermark) and ProcessingTimeTimeout (driven by wall clock).
  • State Store Backends: HDFSBackedStateStoreProvider keeps state on JVM heap (fast, OOM risk); RocksDBStateStoreProvider spills state to local NVMe + changelog.
State & Checkpointing

Micro-Batch Offset WAL & RocksDB State Store

Kafka Offset LogReplayable micro-batchStreaming EngineEvent-time watermark WRocksDB StateStoreWindow aggregates + TTLS3 Checkpoint WALOffsets + state delta

Write-ahead offset logs in the checkpoint directory paired with RocksDB state snapshots guarantee fault-tolerant exactly-once stateful streaming.

02
STAGE 02 · WHY WE NEED ITL4 · FUNDAMENTALS

Why we need Spark Structured Streaming & Watermarking (and what fails without it).

Why this matters: The problem: see what breaks without Spark Structured Streaming & Watermarking under real concurrency or scale.

Mobile clients and IoT devices routinely deliver events minutes or hours late. Without watermarks, stateful streaming jobs accumulate infinite state until executors crash; with overly aggressive watermarks, valid late events are silently dropped.

Common Pitfalls:

  • Using update mode when writing to Parquet/Iceberg append-only sinks without proper merge/upsert.
  • Forgetting checkpointLocation on writeStream, losing Kafka offset tracking across restarts.
Component Topology

Why we need Spark Structured Streaming & Watermarking (and what fails without it)

CalleringressRouter / APIcomputeProcessorstorageState Layercontrolrequestdispatchread/write
Engineering Decision Framework
Problem
How to implement Spark Structured Streaming & Watermarking 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 durability and read throughput pull in opposite directions, always pair event-time windows or mapGroupsWithState with an explicit watermark and RocksDB state store so late data is handled accurately without unbounded state OOM.
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 Spark Structured Streaming & Watermarking experiences a sudden 5x traffic spike alongside a slow downstream dependency, which engineering choice best protects system stability?

Production Failure Mode

Unbounded state OOM when withWatermark is omitted on a streaming aggregation or dropDuplicates.

Production Failure Mode

Watermark stalling when one Kafka partition receives no traffic (max event time advances only as fast as the slowest partition).

03
STAGE 03 · WHERE IT IS USEDL5 · APPLIED DESIGN

Where Spark Structured Streaming & Watermarking is used (and where to avoid it).

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

Think of Where Spark Structured Streaming & Watermarking is used (and where to avoid it) as the intuition layer for Spark Structured Streaming & Watermarking: Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.

Spark Structured Streaming & Watermarking delivers the highest leverage at well-defined architectural boundaries. Use it for real-time sessionization, windowed metrics, and deduplication over Kafka event streams.

ChoiceWhat it buysWhat it costs
Production Fit #1Real-time sessionization, windowed metrics, and deduplication over Kafka event streams.Sub-10ms single-event CEP where micro-batch scheduling overhead (~100ms) is too high (consider Flink or Continuous mode).
Production Fit #2Custom per-key state machines (fraud scoring, SLA timers) via mapGroupsWithState / flatMapGroupsWithState.Avoid when workload is flat, trivial, or outside operational bounds.
PySpark: Event-Time Windowing with Watermark from KafkaRequires strict operational guardrails and observability.
Java: Watermarked Kafka Streaming QueryRequires strict operational guardrails and observability.
04
STAGE 04 · HOW IT IS MANAGEDL5 · APPLIED DESIGN

How Spark Structured Streaming & Watermarking works under the hood & reference implementation.

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

Think of How Spark Structured Streaming & Watermarking works under the hood & reference implementation as the intuition layer for Spark Structured Streaming & Watermarking: Operational control: configure bounds, failure handling, and safe production defaults.

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 pipelines.

Lifecycle & Failure Recovery

How Spark Structured Streaming & Watermarking works under the hood & reference implementation

admitsucceedbudget exceededInitializedProcessingInvariant MetDegraded Fallback

Operational Guidelines

  • Micro-Batch vs Continuous: Micro-batch gives exactly-once end-to-end guarantees and full stateful SQL; Continuous mode targets ~1ms latency for stateless map/filter.
  • Watermark Formula: Watermark = max(event_time_seen) - delayThreshold. Windows older than the watermark are finalized and evicted.
  • Stateful Timeout: mapGroupsWithState supports EventTimeTimeout (driven by watermark) and ProcessingTimeTimeout (driven by wall clock).
05
STAGE 05 · ALTERNATIVESL6 · SCALE & TRADE-OFFS

Alternatives & trade-offs for Spark Structured Streaming & Watermarking.

Why this matters: The trade-off: compare competing approaches across latency, consistency, and operational cost.

Think of Alternatives & trade-offs for Spark Structured Streaming & Watermarking as the intuition layer for Spark Structured Streaming & Watermarking: The trade-off: compare competing approaches across latency, consistency, and operational cost.

Evaluating Spark Structured Streaming & Watermarking against alternatives requires balancing latency, operational overhead, failure blast radius, and cost.

ChoiceWhat it buysWhat it costs
Short Watermark (e.g. 1 min)
Long Watermark (e.g. 2 hours)
06
STAGE 06 · PRODUCTION ARCHITECTUREL7 · STAFF / PRINCIPAL

Production architecture & hardening for Spark Structured Streaming & Watermarking.

Why this matters: Production architecture: see how the components compose end to end under real load.

Think of Production architecture & hardening for Spark Structured Streaming & Watermarking as the intuition layer for Spark Structured Streaming & Watermarking: Production architecture: see how the components compose end to end under real load.

Always pair event-time windows or mapGroupsWithState with an explicit watermark and RocksDB state store so late data is handled accurately without unbounded state OOM.

Late Data Lifecycle

Event-Time Watermark Window State Machine

arrives within delaywatermark advances past…WINDOW OPENevent_time >= WLATE ACCEPTEDW <= t_end <= max - delaDROPPED & EVICTEDt_end < W; state purged

Watermarks bound memory in RocksDB by evicting window state once event time advances past the allowed lateness threshold.

07
STAGE 07 · PROBLEMS SOLVED & FURTHER DEEP DIVEL7 · STAFF / PRINCIPAL

Problems solved by Spark Structured Streaming & Watermarking & Related Concepts.

Why this matters: Applied problems: connect these internals to concrete system design and debugging scenarios.

Think of Problems solved by Spark Structured Streaming & Watermarking & Related Concepts as the intuition layer for Spark Structured Streaming & Watermarking: Applied problems: connect these internals to concrete system design and debugging scenarios.

Apply Spark Structured Streaming & Watermarking to real-world engineering problems and explore adjacent architectural concepts below.

Design Trade-Off

Problems solved by Spark Structured Streaming & Watermarking & Related Concepts

Before · Unbounded Coupling
  • No backpressure on spikes
  • Implicit shared state
  • Cascading tail latency
After · Bounded & Observable
  • Explicit capacity budgets
  • Isolated failure domains
  • Predictable p99 latency
Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

If you configure `.withWatermark('event_time', '10 minutes')` on a stateful `groupBy(window('event_time', '5 minutes'))` in Spark Structured Streaming, what happens to state memory?

Recommended Learning Flow