Watermarks and late data
Events often arrive late: a phone was offline, a network was slow. A stream that counts per minute or per hour has to decide how long to wait for stragglers before it calls a number final. A watermark is that decision. This lesson explains it with a homework deadline, then shows exactly how Spark moves it.
Step 4 · Structured Streaming · Silver · Stateful streams, lesson 1 of 3
On this page
Read first: Structured Streaming basics (skip if you know it)
In plain words first
A teacher collects homework. Each sheet is dated when it was written, but students hand it in at different times. The teacher cannot wait forever to grade Monday's homework, so they set a rule: "I will take Monday's sheets until I have seen sheets dated Wednesday." Once a Wednesday sheet arrives, Monday is closed, graded and filed. A Monday sheet that turns up after that is too late.
In a stream, the date on the sheet is the event time, the moment it is handed in is the processing time, and the teacher's rule is the watermark: how far behind the newest event Spark is still willing to wait.
Event time vs processing time
A phone that was offline sends its 12:05 click at 12:40. Counting clicks per 5 minutes of processing time would put it in the 12:40 bucket, which is wrong. Counting by event time puts it in 12:05-12:10, where it belongs, as long as Spark has not closed that window yet.
counts = (clicks .withWatermark("event_time", "10 minutes") .groupBy(F.window("event_time", "5 minutes"), "page") .count()) counts.writeStream.outputMode("append").format("delta") \ .option("checkpointLocation", "s3://chk/page_clicks/").toTable("gold.page_clicks")
How the watermark moves
After each micro-batchmicro-batch: One small round of a stream: Spark takes the data that arrived since the last round, processes it like a little batch job, and saves its progress. Learn more → Spark calculates watermark = newest event time seen so far - delay. It only ever moves forward. A window is final once the watermark passes its end. Click through four batches:
Batch 1 · events 12:01, 12:07
Batch 2 · events 12:16, 12:03
Batch 3 · the window closes
Batch 4 · event 12:02 arrives
numRowsDroppedByWatermark in the progress report counts such rows.Why it matters: memory
Without a watermark, Spark can never close anything, so it must remember everything:
| Operation | Without a watermark | With a watermark |
|---|---|---|
| Counting per window | Every window ever seen, forever | Windows older than the watermark are forgotten |
| Dropping duplicates | Every id ever seen | Use dropDuplicatesWithinWatermark (Spark 3.5+) to forget old ids |
| Joining two streams | Both sides kept forever | Watermarks on both sides plus a time limit in the join condition let Spark forget old rows |
A stream that runs for months without a watermark keeps growing its state until it runs out of memory or its checkpointcheckpoint: In streaming, the folder where Spark records which input it has processed and its state, so a restarted query continues where it stopped. Learn more → becomes huge. The RocksDB state storestate store: Where a stateful query keeps what it remembers between micro-batches, saved with the checkpoint so it survives a restart. Learn more → holds more, but does not remove the need to limit it.
Choosing the delay
- Measure how late events really are: processing time minus event time. Cover the 99th or 99.9th percentile.
- A longer delay: more complete numbers, but windows are final later (in append mode) and more is kept in memory.
- A shorter delay: fresher output and less memory, more rows dropped.
- If late events must never be lost, also land the raw events in a table and correct the numbers with a periodic batch job.
Watermarks and output modes
In append mode a window is written once, when it is final, so output waits for the window length plus the delay. In update mode a window is written every time its count changes, so results are fresh but the sinksink: Where a stream writes its results: a Delta table, files, Kafka, or your own code with foreachBatch. Learn more → must handle updates (a MERGE). For rules that windows cannot express, Spark 4 adds transformWithState, with timers and TTL (Custom state).
Try it yourself
Each example says what it shows, then the output from a real run and what to notice in it, so you can follow without running anything. To try one yourself, paste it into a local Spark session, with spark already created: each builds its own data.
Goal: Count page views per 10-minute window in a stream that can run forever, writing each window once it is final.
import json, os from pyspark.sql import functions as F os.makedirs("lab/wm/landing", exist_ok=True) events = [("2025-03-01 10:01:00", "/home"), ("2025-03-01 10:07:00", "/cart"), ("2025-03-01 10:52:00", "/home")] with open("lab/wm/landing/events.json", "w") as f: f.write("\n".join(json.dumps({"ts": ts, "page": p}) for ts, p in events)) counts = (spark.readStream.schema("ts TIMESTAMP, page STRING").json("lab/wm/landing") # bounds state; later rows are dropped .withWatermark("ts", "30 minutes") .groupBy(F.window("ts", "10 minutes"), "page").count() .select(F.col("window.start").alias("window_start"), "page", "count")) (counts.writeStream # each window written once, when final .outputMode("append") .format("parquet") .option("path", "lab/wm/page_counts") .option("checkpointLocation", "lab/wm/_checkpoints/page_counts") .trigger(availableNow=True) .start().awaitTermination()) spark.read.parquet("lab/wm/page_counts").orderBy("window_start", "page").show()
Output from a real run
+-------------------+-----+-----+ | window_start| page|count| +-------------------+-----+-----+ |2025-03-01 10:00:00|/cart| 1| |2025-03-01 10:00:00|/home| 1| +-------------------+-----+-----+
What to notice:
- Only the 10:00 windows were written. The latest event is 10:52, so the watermark is 10:22 (30 minutes earlier), past the end of the 10:00 window.
- The 10:50 window is missing: it is not final yet and waits for later data.
- File outputs only accept final results (append mode), which is why an aggregation into files needs a watermark.
Goal: See which late events still count and which are dropped.
import json, os from pyspark.sql import functions as F os.makedirs("lab/watermarks/in", exist_ok=True) def drop_file(name, rows): path = f"lab/watermarks/in/{name}.json" with open(path, "w") as f: f.write("\n".join(json.dumps({"ts": ts}) for ts in rows)) n = len(os.listdir("lab/watermarks/in")) # files are read in modification order os.utime(path, (1_700_000_000 + n, 1_700_000_000 + n)) drop_file("1", ["2025-03-01 10:01:00", "2025-03-01 10:07:00"]) drop_file("2", ["2025-03-01 10:31:00"]) # event time moves on drop_file("3", ["2025-03-01 10:32:00"]) drop_file("4", ["2025-03-01 10:09:00", # 22 min late: counted "2025-03-01 09:55:00"]) # 36 min late: dropped (spark.readStream.schema("ts TIMESTAMP").option("maxFilesPerTrigger", 1) .json("lab/watermarks/in") .withWatermark("ts", "30 minutes") .groupBy(F.window("ts", "10 minutes")).count() # memory sink: keeps the result in a temp table named "windows" .writeStream.outputMode("update").format("memory").queryName("windows") .option("checkpointLocation", "lab/watermarks/_checkpoints/windows") .trigger(availableNow=True).start().awaitTermination()) (spark.table("windows") .groupBy(F.col("window.start").alias("window_start")) .agg(F.max("count").alias("count")) .orderBy("window_start").show())
Output from a real run
+-------------------+-----+ | window_start|count| +-------------------+-----+ |2025-03-01 10:00:00| 3| |2025-03-01 10:30:00| 2| +-------------------+-----+
What to notice:
- The 10:00 window counts 3: the 10:09 event arrived 22 minutes late but was within the 30-minute watermark, so it was added.
- There is no 09:50 window: the 09:55 event was 36 minutes late, behind the watermark, so it was dropped.
- Files are read one per batch, so the watermark moves between them. Spark drops a row only after the previous batch's watermark has passed it.
Common mistakes
- No watermark on a long-running aggregation — Memory grows forever.
- Watermark on a different column than the window — The watermark must be on the event-time column used by the window or the join.
- Expecting append mode to write windows straight away — Append writes only final windows, after the watermark passes them.
- Assuming nothing is lost — Rows later than the delay can be dropped; watch numRowsDroppedByWatermark.
Key takeaways
- Event time is when it happened; processing time is when Spark saw it. Count by event time.
- Watermark = newest event time seen - delay; it only moves forward, and windows behind it are final.
- Events later than the watermark may be dropped; events within the delay never are.
- Pick the delay from measured lateness; back it up with a batch correction if nothing may be lost.
Interview prep
THE QUESTION
"Mobile events can arrive hours late. How do you compute accurate hourly counts in a stream?"
Avoid: "set a watermark of a few hours" without the trade-off: a longer delay means more state and later results; a shorter one drops more late data.
Follow-ups · answer out loud, then open
Follow-up"How is the watermark actually computed?"
Scenario"Hourly counts in append mode only appear after a long delay. Why, and what can you change?"
Trap"Rows older than the watermark are always dropped."
Check yourself
3 questionsThe newest event time seen is 10:40 and the delay is 15 minutes. What is the watermark?
Show the answer
10:25. 10:40 - 15 minutes.
In append mode, when is a window written?
Show the answer
When the watermark passes the window end. Append writes rows that will not change again.
Besides handling late events, what is a watermark for?
Show the answer
Limiting what Spark must keep in memory. Without it, state for windows, dedup and joins grows forever.
Practise this
Problems that use this, graded on hidden tests
- Click Counts in 5-Minute Windows with Late DataStreaming Medium
- Drop Duplicate Events from a Retrying ProducerStreaming Medium
- Trending Searches in Sliding WindowsStreaming Hard
Keep going
Up next · Stateful streams · lesson 2 of 3 · 7 min readEvent-time windows
Tumbling, sliding and session windows, what they cost in state, and when a window is final.
Related lessons
Structured Streaming basicsPySpark functions · 5 min read
dropDuplicatesSpark internals · 7 min read
The memory model
Previous: Consumer groups and offsets
Primary sources: Handling late data and watermarking · Window operations on event time