Watermarks & Late Data: How Streaming Decides What's Too Late

Every streaming query runs on two clocks — event time and processing time — and they never agree. Watermarks are how Spark Structured Streaming decides how long to wait for late events before finalizing a window and dropping its state.

Every streaming query is secretly running on two clocks, and they never agree with each other.

Event time is when the thing happened — the timestamp the sensor stamped on the reading, the moment the user tapped “buy.” Processing time is when your engine got around to looking at it. In a perfect world these would be the same. In the real world, between the device and your Spark cluster, there is a phone in a tunnel, a Kafka partition rebalancing, a retry after a failed batch — and the same three events arrive in a different order than they occurred.

If you aggregate by processing time, the math is easy and often wrong: a 12:04 door event that arrived at 12:07 gets counted in the wrong 10-minute bucket, and nobody downstream can tell. If you aggregate by event time, the math is right but now you have a new problem: how long do you keep each window open waiting for stragglers? Forever is not an answer — your state store would grow without bound and your job would eventually fall over. The answer Spark gives you is the watermark.

The watermark, precisely

From the official Structured Streaming docs, the semantics are:

For a specific window ending at time T, the engine will maintain state and allow late data to update the state until (max event time seen by the engine - late threshold > T).

Put plainly: late data within the threshold still gets aggregated; data beyond it starts getting dropped.

You declare it with one call, before your aggregation:

events = (
    spark.readStream.format("kafka")          # the events arrive here, out of order
    .option("kafka.bootstrap.servers", "broker:9092")
    .option("subscribe", "sensors")
    .load()
    .select(F.from_json(F.col("value").cast("string"), schema).alias("e"))
    .select("e.eventTime", "e.device", "e.reading")
)

counts = (
    events
    .withWatermark("eventTime", "10 minutes")  # ← the policy: how late is too late
    .groupBy(window("eventTime", "10 minutes"))
    .count()
)

Note that the watermark is defined on the event-time column from the payload, not on Kafka’s own record timestamp — the engine trusts the timestamp inside your data. The formula is simple and worth memorizing:

watermark = max event time seen by the engine − delay

It is recomputed at the start of every trigger, and — this matters — it only ever moves forward. Once the watermark has passed a point in event time, it never goes back, no matter what arrives later.

Event time versus processing time: devices stamp when things happened, Kafka delivers the events out of order, and Spark can aggregate by either clock
Two clocks, one stream. The watermark exists to reconcile them.

Walk through the docs’ own example

The official guide works through an example with a 10-minute watermark, and it’s the clearest way to build the mental model. Say the engine has observed events up to 12:14. The watermark for the next trigger is 12:04 — the max event time minus the 10-minute delay.

Now a (12:09, cat) event shows up. It arrived out of order and it’s late — but 12:09 is ahead of the watermark (12:04), so it’s accepted. It belongs to windows 12:00–12:10 and 12:05–12:15 (a sliding window example), and the engine updates those counts from state.

Later, the max event time advances and the watermark is updated to 12:11. Two things happen at once: the state for window 12:00–12:10 is cleared — its end (12:10) is behind the watermark — and any event arriving now with an event time of, say, (12:04, donkey) is considered “too late” and ignored. Not queued, not counted elsewhere. Dropped.

The watermark as a line on the event-time axis: max event time 12:14 minus a 10-minute delay gives a watermark of 12:04; events below it are dropped, the 12:09 event is late but kept
The watermark is a moving threshold on the event-time axis, not the wall-clock. Everything behind it is forgotten.

Notice the subtlety that trips people up: an event can be late but not too late. 12:09 arriving after 12:14 is out of order — it missed its “natural” position in the stream — but it’s within the threshold, so it still counts. “Too late” is a precise technical term: event time behind the watermark. Everything else, however tardy, is still in play.

Try it live

This is exactly what the lab below simulates — step through the stream event by event and watch the watermark line advance:

WATERMARKLAB — LIVE
How late is too late? You decide.
12 sensor events stream in — some out of order, some arriving late. Step through them and watch the watermark advance against the max event time, dropping events that fall behind it.
Watermark delay: 10 minutes
how late an event may be and still count
01530
Window duration
tumbling windows over event time
Output mode
what reaches the sink
Event-time timeline (teal = kept · red = too late · hollow = not yet arrived)
12:00
12:10
12:20
12:30
12:40
watermark = max event time seen − 10 min · it only ever moves forward.
0 / 12 events · 0 kept · 0 dropped
# watermark delay: 10 minutes · window: 10 min · output mode: update events \ .withWatermark("eventTime", "10 minutes") \ .groupBy(window("eventTime", "10 minutes")) \ .count() \ .writeStream.outputMode("update").start()
Note: this simulates engine semantics in your browser — no Spark cluster was harmed. The lab evaluates the watermark once per event; real Spark evaluates it at trigger boundaries, and the watermark only ever moves forward. withWatermark on a batch (non-streaming) query is a no-op.

Two experiments worth running. First, drag the watermark delay to 0 minutes and replay: every event that arrives even slightly out of order is dropped, because the watermark equals the max event time and tolerates zero lateness. Now drag it to 30 minutes: nothing is dropped, but watch the windows stay open — that retained state is the price. Second, switch to append mode and notice the sink stays empty until a window’s end falls behind the watermark. That’s the completeness guarantee in action: append mode refuses to emit a window until the engine is confident no more data can arrive for it.

Output modes: where the watermark really bites

The watermark interacts differently with each output mode, and this is where most production surprises live:

  • Update mode — every trigger emits the updated counts for every window that changed. The engine keeps updating a window’s count until the window is older than the watermark, then finalizes it and clears the state. Late-but-acceptable events show up as corrections to previously emitted counts.
  • Append mode — only final counts are written, and only after the watermark passes the window’s end. The docs’ example: the final count for window 12:00–12:10 is appended only after the watermark reaches 12:11. This is why append mode with event-time aggregations effectively requires a watermark — without one, the engine can never know a window is done, and it would have to hold every window open forever.

That “forever” is the whole point of the mechanism. The watermark is as much a state-cleanup policy as a correctness policy. Without it, a windowed aggregation on an unbounded stream accumulates intermediate state for every window it has ever seen — memory grows until the job dies. The watermark is the engine’s license to forget.

Windowed aggregation gated by the watermark: the 12:00 to 12:10 window is finalized once the watermark passes 12:10, later windows stay open, and a 12:04 event arriving now is dropped
Finalized windows are evicted from state; open windows keep accepting late events. A 30-minute delay would have saved the 12:04 straggler.

Tuning: the completeness-vs-state tradeoff

There is no correct watermark delay in the abstract — only a correct one for your lateness distribution. The rule of thumb:

  • Too small and you silently drop valid data. This is the dangerous direction: dropped late events don’t raise errors, they just never appear in your aggregates. If your Kafka consumers lag during deploys or your mobile clients batch uploads, a 5-minute watermark will quietly eat them.
  • Too large and you hold state for windows that are long settled — more memory, later final results in append mode. A 24-hour watermark on a 10-minute window means every window’s state lives a full day past its usefulness.

So measure. Look at the distribution of (processing time − event time) for your stream over a week, and pick a delay that covers your p99 with margin — the occasional deploy-lag spike, not just the sunny-day median. Then keep watching: compare sink row counts against what the source produced. A sudden rise in missing records is your early warning that the world got slower than your policy assumed.

The gotchas, from the official docs

A few rules worth internalizing before they bite you:

  1. withWatermark on a batch query is a no-op. The docs are explicit: the watermark must not affect any batch query, so it’s ignored outright. If you’re testing watermark logic on a static DataFrame, you’re testing nothing.
  2. The watermark never moves backward. It’s max(eventTime seen) − delay, and the max only grows. A quiet stream doesn’t rewind the watermark — but note the flip side: if no new data arrives, the watermark doesn’t advance either, so windows don’t finalize during idle periods.
  3. It also gates deduplication. dropDuplicates on a stream without a watermark keeps every key forever; with one, the engine can evict old keys once the watermark passes them. Same mechanism, same tradeoff.
  4. Multiple watermarks have a policy. If your query ends up with more than one watermark (joins, mostly), spark.sql.streaming.multipleWatermarkPolicy controls how they’re combined — the default takes the minimum, i.e. the most conservative one wins.

Why this matters beyond the config line

Watermarks are one of those ideas that look like a Spark API detail and turn out to be a general streaming truth. Every stream processor — Flink, Kafka Streams, Beam — has some version of “how long do we wait before we call it done,” because the underlying tension is physical: events happen in one order and arrive in another, and no engine can wait forever. Spark’s answer is unusually legible: one number, one formula, visible on the event-time axis. Once you’ve watched the line advance and seen exactly which events fall behind it, “too late” stops being a vague fear and becomes a policy you chose, measured, and can defend. That’s the whole game — not eliminating late data, which is impossible, but deciding, deliberately, what you’re willing to lose.

Keep reading