# Spark Structured Streaming watermarks, windows and output modes, traced batch by batch

Watermarks decide when a streaming window is final and when late events are thrown away. This guide runs a small PySpark 4.3 stream batch by batch, prints the watermark after each step and shows exactly which rows update, appear or get dropped.

A stream never ends, so a streaming engine has to decide when a result is done. Suppose you count orders per user in ten-minute windows. The window from 10:00 to 10:10 seems finished at 10:10, but an event stamped 10:08 can still arrive at 10:25 from a phone that was offline. If the engine waits forever, it holds every window in memory forever. If it closes windows on the wall clock, it miscounts late events.

The watermark is Spark's answer. It is a moving line in event time that says "I do not expect anything older than this any more". Windows that end before the line are final, their state is deleted, and rows that fall behind the line are dropped. Getting the delay right is a trade between completeness, latency and memory.

This article runs a small stream on [PySpark](/tools/pyspark) 4.3.0, one micro-batch at a time, and prints the watermark, the output and the dropped-row counter after each step. Everything shown was produced by running the code. To experiment interactively with the same ideas, use the [streaming windows and watermarks simulation](/ai-simulations/streaming-windows-watermarks). The [streaming topic page](/topics/big-data/streaming) collects related material.

## What happened

### Apache Spark 4.3.0 is released (30 October 2026)

PySpark 4.3.0 was published to PyPI on 30 October 2026, alongside the Spark 4.3.0 release notes and documentation. Databricks announced that Spark 4.3 is available in Databricks Runtime 19. The core event-time model used in this article, `withWatermark`, `window`, `session_window` and the append and update output modes, works the same way it has in the 4.x line.

### The real-time trigger is part of the PySpark 4.3 API (October 2026)

The `DataStreamWriter.trigger()` method in PySpark 4.3.0 accepts a `realTime` argument alongside `processingTime`, `availableNow` and `continuous`. Its docstring describes it as a trigger "that runs a real time mode query with batch at the specified duration", and marks the API as evolving. Real-time mode targets workloads that need much lower latency than classic micro-batches. The watermark logic explained below still decides when stateful results are final.

### transformWithState is the general stateful API in Spark 4 (2025 onwards)

Spark 4.0 introduced `transformWithState`, documented in the Structured Streaming guide for 4.0 and later, and PySpark 4.3 exposes both `transformWithState` and `transformWithStateInPandas`. It lets you keep typed state with timers and time-to-live, which matters when built-in windows do not fit. Built-in windows remain the simplest choice for counts and sums over time.

## Event time, processing time and the watermark

Two clocks matter in streaming:

- **Event time** is when something happened, carried inside the record (`ts`).
- **Processing time** is when Spark sees the record.

Windows are defined on event time. The watermark is computed from event time too, like this:

```
watermark = max(event time seen so far) - delay threshold
```

Spark computes the new watermark at the end of a micro-batch and uses it in the next one. The PySpark docstring for `withWatermark` adds an important caveat: because coordinating this value across partitions is costly, the watermark is only guaranteed to be at least the delay behind real event time, so Spark may still accept some rows that are later than the delay. The delay is a lower bound on how long Spark waits, not an exact cut-off.

An everyday analogy: a teacher collects homework. The deadline moves with the latest homework handed in. If the newest paper is dated Friday and the teacher allows two days of grace, anything dated before Wednesday is now refused. The teacher never looks at the wall clock, only at the dates on the papers.

### Window types

Spark offers three window shapes. I ran three events for one user (10:07, 10:12 and 10:40) through each to show the difference.

| Window | Code | Windows produced (start to end, count) |
|---|---|---|
| Tumbling, 10 min | `window('ts', '10 minutes')` | 10:00-10:10 (1), 10:10-10:20 (1), 10:40-10:50 (1) |
| Sliding, 10 min every 5 min | `window('ts', '10 minutes', '5 minutes')` | 10:00-10:10 (1), 10:05-10:15 (2), 10:10-10:20 (1), 10:35-10:45 (1), 10:40-10:50 (1) |
| Session, 10 min gap | `session_window('ts', '10 minutes')` | 10:07-10:22 (2), 10:40-10:50 (1) |

Sliding windows place each event in several windows (here, two), which multiplies state. Session windows grow while events keep arriving within the gap: the 10:07 and 10:12 events merge into one session that ends ten minutes after the last event, at 10:22.

## A stream traced batch by batch

The query counts and sums `amount` per user per ten-minute tumbling window, with a ten-minute watermark delay. The source is a folder of JSON files; I drop one file in, run the query with `trigger(availableNow=True)` and the same checkpoint, and repeat. The session time zone is set to UTC so times print as written.

```python
from pyspark.sql import SparkSession, functions as F

spark = (SparkSession.builder.master("local[2]")
         .config("spark.sql.shuffle.partitions", "2")
         .config("spark.sql.session.timeZone", "UTC")
         .getOrCreate())

src = spark.readStream.schema("user STRING, ts TIMESTAMP, amount INT").json("in")

agg = (src.withWatermark("ts", "10 minutes")
          .groupBy(F.window("ts", "10 minutes"), "user")
          .agg(F.sum("amount").alias("total"), F.count("*").alias("n")))

def show(df, batch_id):
    print(batch_id, df.orderBy("window", "user").collect())

q = (agg.writeStream.outputMode("update")      # or "append"
        .foreachBatch(show)
        .option("checkpointLocation", "ck_update")
        .trigger(availableNow=True)
        .start())
q.awaitTermination()
for p in q.recentProgress:
    print(p["batchId"], p["eventTime"].get("watermark"),
          p["stateOperators"][0]["numRowsDroppedByWatermark"])
```

The four input files (all times on 23 November 2026):

| File | Events (user, event time, amount) | Max event time after this file |
|---|---|---|
| 1 | a 10:01 5, a 10:07 3, b 10:09 4 | 10:09 |
| 2 | a 10:14 2, a 10:21 6 | 10:21 |
| 3 | a 10:08 1 (late), b 10:33 7 | 10:33 |
| 4 | a 10:05 9 (late), a 10:45 1 | 10:45 |

### What Spark printed in update mode

Each file produced one data batch and, because `availableNow` processes everything and the watermark moved, one extra batch with no input. Spark runs such no-data batches so that state can be cleaned up and final results emitted even when no new rows arrive (controlled by `spark.sql.streaming.noDataMicroBatches.enabled`).

| Batch | Input rows | Watermark used | Rows emitted (window, user, total, n) | Late events dropped |
|---|---|---|---|---|
| 0 | 3 | none yet (epoch) | 10:00 a 8 2; 10:00 b 4 1 | 0 |
| 1 | 0 | 09:59 | none | 0 |
| 2 | 2 | 09:59 | 10:10 a 2 1; 10:20 a 6 1 | 0 |
| 3 | 0 | 10:11 | none | 0 |
| 4 | 2 | 10:11 | 10:30 b 7 1 | 1 (a 10:08) |
| 5 | 0 | 10:23 | none | 0 |
| 6 | 2 | 10:23 | 10:40 a 1 1 | 1 (a 10:05) |
| 7 | 0 | 10:35 | none | 0 |

Step by step:

1. **File 1.** No watermark yet, so everything is accepted. Update mode emits both windows immediately. The max event time is 10:09, so the next watermark is 10:09 minus 10 minutes, 09:59.
2. **File 2.** Watermark 09:59. Both events are on time. The max event time becomes 10:21, so the watermark moves to 10:11. The 10:00 to 10:10 window now ends before the watermark, so it is final and its state is removed.
3. **File 3.** The 10:08 event belongs to the 10:00 window, which closed when the watermark passed 10:10. Spark drops it, and the `numRowsDroppedByWatermark` metric in that batch's progress report becomes non-zero (it reported 2 here; the counter is measured at the stateful operator, so treat it as a signal rather than an exact count of late input events). The 10:33 event opens a new window. Max event time 10:33, watermark 10:23.
4. **File 4.** The 10:05 event is far behind the watermark and is dropped too. The 10:45 event opens another window.

The final totals never include the two late rows. If those events matter, the delay was too short: a 30-minute delay would have kept both, at the cost of holding more windows open.

### The same stream in append mode

Append mode emits each window exactly once, when it is final. Same input, same watermark:

| Batch | Watermark used | Rows emitted |
|---|---|---|
| 0, 1, 2 | epoch, 09:59, 09:59 | none |
| 3 | 10:11 | 10:00 a 8 2; 10:00 b 4 1 |
| 5 | 10:23 | 10:10 a 2 1 |
| 7 | 10:35 | 10:20 a 6 1 |

The 10:30 and 10:40 windows have not been emitted yet. They will be when later events push the watermark past 10:40 and 10:50. That is the cost of append mode: latency equals window length plus the delay, plus however long it takes for newer events to arrive. A quiet stream holds its last windows until traffic resumes.

## Choosing the output mode and delay

| Output mode | What is written | Latency | Sink requirement | Good for |
|---|---|---|---|---|
| Append | Each final window once | Window + delay + wait for newer events | Any append-only sink (files, Kafka) | Data lakes, Delta or Iceberg tables, downstream joins |
| Update | Windows that changed in this batch | One trigger interval | A sink that can upsert by key | Live dashboards, key-value stores, `MERGE` in `foreachBatch` |
| Complete | The whole result table every batch | One trigger interval | Small results only | Small leaderboards and tests; state is never dropped |

How long should the delay be? Measure the lag between event time and processing time on real traffic, then pick a delay that covers the share of late events you are willing to lose. If 99.5% of events arrive within 4 minutes and 99.95% within 20 minutes, a 5-minute delay drops about 0.5% of events and a 20-minute delay drops about 0.05%, but holds four times as many minutes of open windows.

### What state costs

A rough sizing for a tumbling-window count:

- 1,000,000 active users, 10-minute windows, 10-minute delay.
- Each user has its current window open, plus the previous window until the watermark passes its end. That is up to 2 open windows per user, so up to about 2,000,000 state rows.
- At an assumed 100 bytes per row (key, window and aggregates), that is about 200 MB of state, before store overhead.
- Switch to 10-minute sliding windows every minute and each event lands in 10 windows, so state grows roughly tenfold.

These are estimates to show scale, not measured sizes. For large state, the RocksDB state store provider (`spark.sql.streaming.stateStore.providerClass`) keeps state on local disk instead of the JVM heap. Read real numbers from each query's progress report: `stateOperators[].numRowsTotal` and `memoryUsedBytes`.

### Several streams, several watermarks

If a query reads two watermarked streams, for example in a stream-stream join, Spark tracks a watermark per input and combines them. The setting `spark.sql.streaming.multipleWatermarkPolicy` accepts `min` (the default, safest) or `max` (faster, but drops more data from the slower stream).

## Spark and Flink side by side

The same idea exists in Apache Flink, with different mechanics.

| Aspect | Spark Structured Streaming | Apache Flink |
|---|---|---|
| Declaring the watermark | `df.withWatermark("ts", "10 minutes")` | `WATERMARK FOR ts AS ts - INTERVAL '10' MINUTE` in a table definition, or a `WatermarkStrategy` in the DataStream API |
| When it advances | Between micro-batches, from the max event time | Continuously, as watermark records flow through the job |
| Late rows | Dropped by stateful operators once behind the watermark | Dropped by default; the DataStream API can route them to a side output or allow lateness |
| Execution | Micro-batches; real-time mode in recent releases | Record-at-a-time pipelines |

Both treat the watermark as a heuristic about completeness, not a guarantee. The [Apache Flink tool page](/tools/apache-flink) and the [Spark streaming tool page](/tools/spark-streaming) go further into each engine.

## What it means in practice

Watermarks are a business decision dressed as a config value. The delay sets how many late events you lose, how stale your final numbers are and how much state you pay for. In the trace above, a ten-minute delay was cheap and quick, and it silently threw away two of nine events.

Output mode is the second decision. Update mode gives fresh numbers every batch but needs a sink that can overwrite by key, which usually means `foreachBatch` with a `MERGE` into a Delta or Iceberg table. Append mode writes each window once and suits append-only sinks such as files or [Apache Kafka](/tools/apache-kafka) topics, but its latency includes the delay, and quiet streams hold windows open.

Late data does not have to be lost. A common pattern is to keep the stream's watermark tight for low latency, land every raw event in a bronze table, and run a batch job that recomputes recent windows from the raw data each night. The stream gives speed and the batch job gives completeness. The [medallion architecture article](/articles/medallion-architecture-quality-gates-reprocessing) describes that layering, and [real-time AI from streams to decisions](/articles/real-time-ai-from-streams-to-decisions) shows where such pipelines feed models.

## What to do now

1. **Measure lateness.** Compute processing time minus event time for a week of real events and note the 99th, 99.9th and 99.99th percentiles.
2. **Set the delay from data.** Choose the percentile of events you must keep and set `withWatermark` to cover it, with a margin.
3. **Alert on dropped rows.** Export `numRowsDroppedByWatermark` from `StreamingQueryProgress` and alert when it exceeds an agreed rate.
4. **Pick the output mode by sink.** Use append for append-only sinks and update with `foreachBatch` plus `MERGE` for tables that accept upserts.
5. **Avoid complete mode at scale.** It keeps every group forever and rewrites the whole result each batch.
6. **Size state before launch.** Estimate keys times open windows times bytes per row, and switch to the RocksDB state store for large state.
7. **Set the session time zone.** Fix `spark.sql.session.timeZone` (usually UTC) so window boundaries do not depend on the cluster's local zone.
8. **Keep raw events.** Write every input event to a bronze table so late data can be reprocessed in batch.
9. **Test with replayed files.** Reproduce the trace in this article with your own late-event patterns using `availableNow` and a fixed checkpoint.

## Risks and open questions

**Dropped rows are silent by default.** Nothing fails when the watermark discards an event; only the progress metric shows it.

**A single bad timestamp can jump the watermark.** One event stamped far in the future pushes the max event time forward and makes all real traffic look late. Filter or clamp impossible timestamps before `withWatermark`.

**Checkpoints tie you to a query shape.** Changing the grouping keys, window size or stateful operators can make an existing checkpoint incompatible, forcing a restart from scratch or a migration plan.

**Quiet partitions stall append output.** If one input stops sending data, the max event time stops moving and final windows are not emitted.

**Real-time mode is new.** The PySpark 4.3 docstring marks the trigger API as evolving; check which sources, sinks and operators it supports before you depend on it.

**Watch next:** how real-time mode and `transformWithState` mature across Spark releases, and how managed platforms expose watermark and state metrics for alerting.

## Frequently asked questions

### What exactly is a watermark in Spark?

It is a timestamp equal to the maximum event time Spark has seen minus the delay you set with `withWatermark`. Windows that end before it are final and their state is removed, and rows older than it can be dropped. Spark updates it between micro-batches.

### Why did my late event disappear without an error?

Because it arrived after the watermark had passed the end of its window. Stateful operators drop such rows by design and report them in the `numRowsDroppedByWatermark` metric. Increase the delay or reprocess late data from raw storage in batch.

### Why does append mode show nothing for a long time?

Append mode only writes a window when the watermark passes its end. That requires newer events to arrive, so output lags by at least the window length plus the delay. Use update mode if you need early results.

### Does the watermark use the wall clock?

No. It is computed only from event times in the data. If no new events arrive, the watermark does not move, even as real time passes.

### When should I use session windows?

Use them when activity comes in bursts and you want one group per burst, such as user sessions on a website. A session closes when no event arrives within the gap, so its length depends on the data. In a streaming query, give them a watermark so Spark can decide when a session is over and remove its state.

## Summary

Spark Structured Streaming groups events into tumbling, sliding or session windows by event time and uses the watermark, the max event time seen minus a delay, to decide when a window is final. Running a small stream on PySpark 4.3.0 batch by batch shows the mechanics: the watermark moves between batches, windows close once it passes their end, late rows behind it are dropped and counted, update mode emits changes every batch and append mode emits final windows once. The delay trades completeness against latency and state size, so set it from measured lateness, alert on dropped rows and keep raw events for batch correction.

## Sources

- [Apache Spark: Spark Release 4.3.0](https://spark.apache.org/releases/spark-release-4-3-0.html)
- [Apache Spark: Structured Streaming Programming Guide, Spark 4.3.0](https://spark.apache.org/docs/latest/streaming/apis-on-dataframes-and-datasets.html)
- [Apache Spark: Structured Streaming transformWithState guide, Spark 4.0.0](https://spark.apache.org/docs/4.0.0/streaming/structured-streaming-transform-with-state.html)
- [Apache Spark: Real-time mode documentation source](https://apache.googlesource.com/spark/+/master/docs/streaming/real-time-mode.md)
- [Apache Spark: PySpark 4.3.0 documentation](https://spark.apache.org/docs/latest/api/python/index.html)
- [Databricks: Introducing Apache Spark 4.3, now available in Databricks Runtime 19](https://www.databricks.com/blog/introducing-apache-spark-43-now-available-databricks-runtime-19)
- [Databricks: Introducing transformWithState in Apache Spark Structured Streaming](https://www.databricks.com/en/blog/introducing-transformwithstate-apache-sparktm-structured-streaming)
- [PyPI: pyspark](https://pypi.org/project/pyspark/)
