Time: windows and watermarks
Part of the free LogicWiz Data Engineering course, Module 15: Streaming. The SQL and Python run in the app, on real Postgres and real Python in the browser.
It is 10:00 on Wednesday. Tess is back with two numbers from the flash sale that never matched. For the same 15 minutes, 09:15 to 09:30, the live dashboard said 1 cart. The next morning's batch report said 3. No job failed and no row was counted twice. Nora asks one thing: "When did those carts happen, and when did we hear about them?"
You'll learn to
- Tell event time from processing time, and say why they drift apart
- Count events in tumbling, hopping and session windows
- Use a watermark to decide when a window is final
- Pick an output mode and size the memory a windowed count needs
Learn
Two clocks
Every event carries two times.
- Event time: when it happened, stamped by the device. It is the
tsfield in SwiftKart's events. - Processing time: when your pipeline sees it.
Usually they are seconds apart. But phones lose signal, apps send events in batches to save battery, and retries resend old events. So an event can arrive minutes late, or a day late. During the sale one shopper's phone was on a train, and it sent its events when it came out of a tunnel.
Tess's question, "carts between 09:15 and 09:30", means carts added then. That is event time. The live dashboard counted by the other clock.
Four carts: when each arrived, and when it happened
| Arrived (processing time) | Event | Happened (event time) |
|---|---|---|
| 09:29:07 | e0062 addtocart (user 10, web) | 09:29:06 |
| 09:32:47 | e0055 addtocart (a visitor's phone) | 09:32:46 |
| 09:41:02 | e0010 addtocart (user 21's phone, back online) | 09:21:32 |
| 09:41:02 | e0192 addtocart (the same phone) | 09:29:32 |
The rows are in the order the pipeline received them. Read the right-hand column against the left one.
Each cart, from the moment it happened to the moment it arrived
A timeline with one lane per cart: two carts arrive within a second of happening, and the two carts from the phone on the train happen at 09:21 and 09:29 but arrive at 09:41, after the 09:30 end of the window.
The axis is minutes after 09:15. A bar starts when the cart happened and ends when it arrived. Everything that starts left of the dashed line belongs to the 09:15 window, whenever it arrives.
Cut the endless stream into windows
You cannot GROUP BY all of a stream that never ends. So a streaming job groups by windows of event time. There are three kinds.
- Tumbling: fixed size, no overlap: 09:00, 09:15, 09:30. Each event is in exactly one window.
- Hopping (Spark calls it sliding): fixed size, overlapping, such as 30 minutes starting every 15. Each event lands in size / slide = 2 windows, so it is counted, and stored, twice.
- Session: one per user, open while events keep coming, closed after a gap with no activity.
A tumbling window is nothing new. It is a GROUP BY on the time, rounded down to the window size.
Seven clicks, three kinds of window
A timeline of seven events between 09:02 and 09:52, grouped into 15-minute tumbling windows, 30-minute hopping windows that start every 15 minutes, and session windows that close after 10 minutes without an event.
The top lane is the events, at 09:02, 09:04, 09:11, 09:13, 09:31, 09:33 and 09:52 (the axis is minutes after 08:45). Each lane below groups them one way; a label gives the window's start and its count. Tumbling counts each event once (4 + 2 + 1 = 7), hopping twice (4 + 2 + 1 + 4 + 3 = 14), and a session ends 10 minutes after its last event.
Tumbling 15-minute windows in Postgres
SELECT date_bin(INTERVAL '15 minutes', event_ts, TIMESTAMP '2025-06-01 00:00:00') AS window_start,
COUNT(*) AS events,
COUNT(*) FILTER (WHERE event_type = 'add_to_cart') AS carts
FROM events
WHERE event_ts >= TIMESTAMP '2025-06-01 08:00:00'
AND event_ts < TIMESTAMP '2025-06-01 11:00:00'
GROUP BY 1
ORDER BY 1;
date_bin(size, ts, origin) rounds each time down to the start of its window, counted from origin. Find the 09:15 row: 3 carts, the batch report's number. A window with no events, such as 09:00, has no row.
The same windows in DuckDB, and one event in hopping windows
import duckdb
from datetime import datetime, timedelta
rows = duckdb.sql("""
SELECT strftime(time_bucket(INTERVAL '1 hour', ts), '%H:%M') AS hour,
COUNT(*) AS events,
COUNT(*) FILTER (WHERE type = 'add_to_cart') AS carts
FROM read_json_auto('data/events.jsonl')
WHERE ts < TIMESTAMP '2025-06-01 12:00:00'
GROUP BY 1 ORDER BY 1
""").fetchall()
print(rows)
# Hopping: 30-minute windows that start every 15 minutes
ts = datetime(2025, 6, 1, 9, 47)
size, slide = timedelta(minutes=30), timedelta(minutes=15)
start = ts.replace(minute=ts.minute - ts.minute % 15, second=0)
while start + size > ts:
print('in window', start.strftime('%H:%M'), 'to', (start + size).strftime('%H:%M'))
start -= slide
DuckDB reads ts as a timestamp, and time_bucket does what date_bin does. The hour from 09:00 holds 10 add-to-carts: the flash sale. The loop at the end finds the two 30-minute hopping windows that contain an event at 09:47.
How long do you wait for the phone?
A live job must decide when the 09:15 to 09:30 count is final. Wait for ever and nothing is ever final.
Think of a bus that waits a few minutes past its time for late passengers, then leaves. The job keeps a moving line: "I have probably seen everything that happened before time W." That line is the watermark: the latest event time seen so far, minus an allowed lateness that you choose. With 10 minutes of lateness, once an event stamped 09:41 arrives, the watermark is 09:31.
When the watermark passes the end of a window, the window closes: its count is final and its memory is freed. An event that arrives for a closed window is too late, and is dropped.
Wait longer and the counts are more complete, but they come later and cost more memory.
Six events and a watermark
Six events arrive one at a time into 5-minute windows with 10 minutes of allowed lateness: the watermark moves forward, one late event is still counted, the first window closes, and a later event for it is dropped.
a arrives, stamped 10:01. It goes into the 10:00 to 10:05 window. The watermark is 10:01 minus 10 minutes: 09:51.
b arrives, stamped 10:03. Same window. The watermark moves to 09:53.
c arrives, stamped 10:08. It opens the next window, and the watermark moves to 09:58. No window ends before 09:58, so both stay open.
d arrives, stamped 10:02: a late one. It is older than events already seen. But its window ends at 10:05, after the watermark, so the window is still open and d is counted. The watermark never moves back.
e arrives, stamped 10:16. It opens a third window and pulls the watermark to 10:06. That is past 10:05, so the first window closes with a final count of 3.
f arrives, stamped 10:04: too late. Its window has closed. f is dropped and the count stays 3. Both d and f were late; only f was later than the watermark.
Windows are 5 minutes long and the allowed lateness is 10 minutes. Watch the Watermark box first in each step, then see which window it has passed.
Remember: watermark = latest event time seen - allowed lateness. A window closes when the watermark passes its end. Late is fine. Later than the watermark is lost.
Watch a late event make it, or not
import ministream as ms
from datetime import datetime, timedelta
broker = ms.Broker()
ms.load_events(broker, 'clicks', partitions=1, path='landing/events/*.jsonl') # arrival order
DAY = timedelta(days=1)
def run(lateness):
"""Daily event-time windows with a watermark: final, still open, dropped."""
reader = broker.consumer(f'job-{lateness}', 'clicks')
open_windows, final, dropped = {}, {}, []
max_seen = None
for m in reader.poll(max_records=1000):
ts = datetime.fromisoformat(m.value['ts'][:19]) # event time
start = ts.replace(hour=0, minute=0, second=0) # its 1-day window
if max_seen is not None and start + DAY <= max_seen - lateness:
dropped.append(m.value['event_id']) # window already closed
continue
open_windows[start] = open_windows.get(start, 0) + 1
max_seen = ts if max_seen is None else max(max_seen, ts)
for w in sorted(open_windows):
if w + DAY <= max_seen - lateness: # the watermark passed it
final[w.strftime('%m-%d')] = open_windows.pop(w)
still_open = {w.strftime('%m-%d'): n for w, n in sorted(open_windows.items())}
return final, still_open, dropped
print('lateness 2 hours:', run(timedelta(hours=2)))
print('lateness 1 day: ', run(timedelta(days=1)))
Each line shows final windows, windows still open, and dropped events. With 2 hours of lateness, 2 June is already final at 59 and the late event e9001 is dropped. With a day of lateness it is counted (60), but 2 June is not yet final when the data ends. Complete or soon: the lateness is the dial.
Incremental loads on a timeline where the watermark moves forward, a late row arrives behind it, and a lookback window catches it.
You have met this idea before. Module 6's batch watermark and a streaming watermark answer the same question: how far back do we still accept late rows? The lookback there plays the role of the allowed lateness here.
Spark is always one batch behind
In Spark Structured Streaming you write withWatermark("ts", "10 minutes"). There is no default: you choose the delay.
Spark reads the stream in small batches, called micro-batches. It works out the watermark at the end of each one: the latest event time seen, minus the delay. It never moves it back. The next batch uses it to drop rows whose window has ended, and to write out and forget the closed windows. So everything trails by one batch.
The promise is one-sided. A row less late than the delay is never dropped. A later row may or may not be.
With several input streams (a union, a join), the query keeps one watermark, the minimum of them: the slowest stream sets the pace.
Micro-batches of clicks arrive; a 10-minute windowed count keeps one state row per open window, the watermark advances after each batch, closed windows are emitted and evicted, and too-late rows are dropped.
Step through the six batches, then move the delay. At 0 minutes four late clicks are dropped and the job never holds more than 2 windows; at 30 minutes nothing is dropped, but it holds up to 5 windows and the first window is written in batch 5 instead of batch 3.
The whole job in Spark Structured Streaming on Databricks
Runs on Databricks:
from pyspark.sql import functions as F
schema = 'event_id STRING, user_id BIGINT, type STRING, ts TIMESTAMP'
clicks = (spark.readStream
.format('kafka')
.option('kafka.bootstrap.servers', 'broker:9092')
.option('subscribe', 'clicks')
.option('startingOffsets', 'earliest')
.load()
.select(F.from_json(F.col('value').cast('string'), schema).alias('e'))
.select('e.*'))
counts = (clicks
.withWatermark('ts', '10 minutes') # allowed lateness
.dropDuplicates(['event_id', 'ts']) # replays and retries
.groupBy(F.window('ts', '15 minutes'), 'type') # tumbling windows
.count())
query = (counts.writeStream
.format('delta')
.outputMode('append') # final windows only
.option('checkpointLocation', '/Volumes/swiftkart/stream/checkpoints/clicks_15m')
.trigger(availableNow=True) # read what is there, then stop
.toTable('swiftkart.gold.clicks_15m'))
query.awaitTermination()
spark.table('swiftkart.gold.clicks_15m').orderBy('window', 'type').show(4, truncate=False)
+------------------------------------------+------------+-----+
|window |type |count|
+------------------------------------------+------------+-----+
|{2025-06-01 08:00:00, 2025-06-01 08:15:00}|page_view |1 |
|{2025-06-01 08:15:00, 2025-06-01 08:30:00}|add_to_cart |1 |
|{2025-06-01 08:15:00, 2025-06-01 08:30:00}|product_view|1 |
|{2025-06-01 08:30:00, 2025-06-01 08:45:00}|page_view |3 |
+------------------------------------------+------------+-----+
only showing top 4 rows
Read it in three parts: read the clicks from Kafka, count them per window behind a watermark, write the counts to a Delta table. Kafka hands Spark the raw bytes in value; from_json turns them into columns. dropDuplicates with the event-time column remembers ids only as long as the watermark needs.
When does a window reach the table?
The job above writes with outputMode('append'). That choice decides when Tess sees a number.
- append writes each window once, when the watermark passes its end, then forgets it (Spark says the window is evicted). The numbers are final, but they come late: a 15-minute window with a 10-minute delay appears 25 minutes after it starts, at the earliest.
- update writes every window the batch changed, again and again. The numbers come early, and they change, so the table must overwrite the old row.
- complete rewrites the whole result every batch, and never forgets a window.
Final or early: one mode cannot give you both.
Output modes for a windowed count
| outputMode | What each batch writes | What it remembers | Watch out |
|---|---|---|---|
| append (the default) | each window once, when the watermark passes its end | forgets a window after writing it | needs a watermark; a window appears window + delay after it starts, at the earliest |
| update | every window this batch changed, again and again | forgets closed windows, if there is a watermark | the sink must upsert (a MERGE in foreachBatch); not allowed with session windows |
| complete | the whole result table, every batch | never forgets | only for aggregations; memory and output grow without bound |
Append with an aggregation and no watermark fails at start with Append output mode not supported when there are streaming aggregations on streaming DataFrames/DataSets without watermark. The checkpoint, the triggers and the store that holds this memory are Lesson 15.6.
Waiting costs memory
Every open window is a row the job must remember: one per key, per open window. Spark calls this memory state.
How many windows are open at once? With window size S, slide L (L = S for tumbling) and delay D, about ceil((S + D) / L) per key.
SwiftKart counts views per product, for 50,000 products:
- tumbling 15 minutes, delay 10: ceil(25 / 15) = 2 windows, 100,000 rows
- sliding 30 minutes every 5, delay 10: (30 + 10) / 5 = 8 windows, 400,000 rows, and every event updates 6 of them
- tumbling 15 minutes, delay 2 hours: ceil(135 / 15) = 9 windows, 450,000 rows
- tumbling 15 minutes, no watermark: no window ever closes. State grows by 96 windows a day per product, 4.8 million rows a day, until executors run out of memory.
State rows for 50,000 products
Bars compare the state rows of four designs: 0.1 million for tumbling windows with a 10-minute delay, 0.4 million for sliding windows, 0.45 million with a 2-hour delay, and 4.8 million after one day with no watermark.
The first three bars stay where they are however long the job runs. The red one is one day old, and adds its own length again every day.
Two classic mistakes. Windowing by arrival time (the file's date, the Kafka timestamp) puts late events in the wrong window. And an aggregation with no watermark never closes a window, so its state grows until the job runs out of memory weeks later.
Numbers to remember
| What | Value | Note |
|---|---|---|
| Watermark delay | no default | you choose it in withWatermark("ts", "10 minutes") |
| Open windows per key | ceil((size + delay) / slide) | times the number of keys = state rows |
| Tumbling window in Spark | window("ts", "15 minutes") | each event in 1 window |
| Hopping (sliding) window | window("ts", "30 minutes", "15 minutes") | each event in size / slide windows |
| Session window | sessionwindow("ts", "10 minutes") | the gap can be an expression per row |
| spark.sql.streaming.noDataMicroBatches.enabled | true | when data stops, one more batch still runs to close windows |
| spark.sql.streaming.multipleWatermarkPolicy | min | with several streams the slowest sets the watermark; max follows the fastest and drops more from the slow ones |
| Rounding a time down | datebin in Postgres, timebucket in DuckDB | a tumbling window in plain SQL |
What changed at SwiftKart
Tess gets a straight answer: both numbers were right, each for its own clock. By 09:30 one cart had arrived. Three had happened.
The live count now groups by event time, with a 10-minute watermark in append mode. The two carts from the train were between 11 and 20 minutes late, so a 10-minute watermark may still miss them. A 30-minute one would catch them, and make every window 20 minutes later. You keep 10, and add a nightly batch that recomputes yesterday from the raw events, so stragglers still reach the final numbers. (Teams that need sub-second results use Apache Flink.)
So far Kafka has been a box that keeps its promises. Next lesson you open it, starting at 02:14 on a Saturday, when one broker loses power.
In one line
Group by event time, close each window with a watermark (latest event time minus the allowed lateness), and plan for the events that arrive after it.
Interview corner
What is the difference between event time and processing time?
Event time is when something happened, stamped at the source; processing time is when the pipeline handles it. They drift apart because devices go offline, clients batch and retry, and pipelines lag. Business metrics should be computed on event time, which means handling events that arrive late.
What is a watermark, how does Spark compute it, and how do you choose it?
A watermark is the engine's estimate that no more events older than a time will arrive: the latest event time seen minus an allowed delay. Spark computes it at the end of each micro-batch and the next batch uses it, to drop rows whose window has ended and to emit and evict closed windows; it never moves back, and with several streams the global watermark is the minimum. Rows less late than the delay are guaranteed to be kept; later ones may or may not be dropped. I choose the delay from the measured lateness distribution, trading completeness against latency and state, roughly keys x ceil((size + delay) / slide) rows, and correct stragglers with a batch job if they matter.
Which output mode would you use for a windowed count written to Delta, and why?
Append, if consumers want final numbers: each window is written once after the watermark passes its end, and its state is evicted, but results arrive window size plus delay after a window starts. Update, if they want provisional numbers sooner: each batch rewrites the windows it changed, so the sink must MERGE on the window key in foreachBatch. Complete rewrites the whole result every batch and never evicts state, which only suits a small, bounded set of keys. Append with an aggregation needs a watermark, or the query fails at start.
Tumbling, sliding or session windows: when would you use each?
Tumbling windows are fixed and non-overlapping, good for counts per 15 minutes on a dashboard. Sliding (hopping) windows overlap, good for a smooth moving count such as errors in the last 10 minutes updated every minute. Session windows follow a user's activity and close after a gap, good for visit length and conversion per session.