Sub topic 10
Windows, watermarks and state
This chapter assumes you can write a basic streaming query, know what an output mode is, and understand that a checkpoint stores query progress. It covers how Structured Streaming keeps state for aggregations and how watermarks limit that state.
Why aggregations need state
A stateless query, such as a filter, looks at each row once. An aggregation such as "orders per customer per five minutes" must remember partial counts between micro-batches. Spark stores these counts in a state store, which is saved in the checkpoint.
Events can arrive late. Without a rule for when to stop waiting, Spark would keep every window open forever, and state would grow without bound.
Event-time windows
A window groups rows by the time an event happened (event time), not the time Spark received it. F.window("event_time", "5 minutes") assigns each row to a five-minute bucket. The result is a struct column with start and end fields.
Watermarks
A watermark is a threshold that says how late data may be. Spark computes it as the maximum event time seen so far minus the delay you set. Once the watermark passes the end of a window, Spark treats that window as final. It then emits the result and drops its state.
from pyspark.sql import functions as F
events = spark.readStream.table("main.demo.orders_bronze")
counts = (
events.withWatermark("event_time", "10 minutes")
.groupBy(F.window("event_time", "5 minutes"), "customer_id")
.agg(F.count("*").alias("orders"))
)
(
counts.writeStream
.outputMode("append")
.option("checkpointLocation", "/Volumes/main/demo/chk/orders_counts")
.toTable("main.demo.orders_5min")
)In append mode, each window is written once, after the watermark passes its end. A window ending at 12:05 is emitted only after Spark has seen an event at 12:15 or later. Rows that arrive after their window is closed are dropped.
Choosing the delay
The delay trades completeness against latency and memory.
| Delay | Effect |
|---|---|
| Short | Results appear sooner and state stays small, but more late rows are dropped. |
| Long | Fewer rows are dropped, but results are delayed and state grows. |
Pick a value from the lateness you observe in your data, such as the 99th percentile of the gap between event time and arrival time.
Common errors
- No watermark in append mode. Spark rejects a streaming aggregation in append mode without a watermark on the event-time column.
- No watermark in update or complete mode. The query runs, but state is never cleaned up and grows until the job fails.
- Watermark column mismatch. The column in
withWatermarkmust be the same one used in the window. Also callwithWatermarkbefore the aggregation. - Expecting output immediately. In append mode the last windows stay unemitted until later events move the watermark forward. If the stream goes quiet, results are held back.
- Changing the query after a restart. Altering the window size, grouping keys or aggregations can make the saved state incompatible with the checkpoint. Use a new checkpoint location and reprocess if you need such a change.
Watching state size
query.lastProgress includes a stateOperators section with fields such as numRowsTotal and memoryUsedBytes. If these numbers keep rising, check that the watermark is set and that the delay is not too long.
Exercise
A query uses withWatermark("event_time", "10 minutes") and five-minute windows in append mode. The latest event time seen is 12:20. Has the window 12:05 to 12:10 been emitted? Explain.
Show answer
Yes. The watermark is 12:20 minus 10 minutes, which is 12:10. That has reached the end of the 12:05 to 12:10 window, so the window is final. Spark emits it and removes its state. A row with event time 12:07 arriving afterward is late and is dropped.