Windows and Watermarks, Event by Event
Follow twelve clicks through five micro-batches by hand, predict when each 5-minute window is emitted and which late click is dropped, then confirm the trace with Spark Structured Streaming and compare tumbling, sliding and session windows on the same data.
Contentsand lesson path
On this page
- The problem
- Step 1: Write down the clicks
- Step 2: Apply the watermark rules by hand
- Step 3: Check the trace with Spark
- Step 4: Sliding and session windows
- What happens to the dropped clicks
- Check your understanding
- Apply it
- Review prompt
Lessons of Stream Processing
- Streams, Tables and Two Kinds of Time Concept · 20 min
- Windows and Watermarks, Event by Event Worked example · 25 min
- State, Checkpoints and Delivery Guarantees Concept · 25 min
- Lab: Kafka to a Lakehouse Table with Structured Streaming Lab · 30 min
- Lab: Schema Evolution and Replaying a Topic Lab · 25 min
- Check: Streaming Correctness Scenarios Knowledge check · 8 questions
What you will learn
- Distinguish event time from processing time and compute tumbling, sliding and session window aggregates with watermarks that bound lateness.
Prerequisites: Messaging & Event Streaming
01. The problem
A window groups events by event time so that an endless stream can be aggregated. A tumbling window has a fixed size and windows do not overlap: 12:00 to 12:05, 12:05 to 12:10, and so on, so each event belongs to exactly one window. A sliding window also has a fixed size, but a new window starts every slide interval, so windows overlap and one event can count in several of them. A session window has no fixed size: it starts with an event and stays open while further events of the same key arrive within a gap.
A streaming job cannot keep every window open for ever, because each open window is state held in memory or on disk. In Spark Structured Streaming that rule is the watermark: withWatermark("ts", "10 minutes") tells Spark that events may arrive up to about 10 minutes late, measured in event time. Spark computes the watermark as the largest event time it has seen, minus 10 minutes. In append output mode, a window is written to the sink only once, when the watermark has reached its end, and later events for that window are dropped.
Here is the problem. Twelve clicks reach a job in five micro-batches, some out of order. The job counts clicks in 5-minute tumbling windows with a 10-minute watermark. When does each window appear in the output, and which clicks are lost? Work it out by hand first, then check the answer with Spark.
Work in the stream-lab/ folder from lesson 1. You need Python 3.12, and Java 17 or 21 for Spark; check Java with java -version. Spark is pinned to 4.2.0 in this skill because the newest Delta Lake release, 4.4.1, is built for Spark 4.2 and its Python package requires pyspark<=4.2.0; Spark 4.3 is newer than any Delta Lake release today. Install everything the skill needs once, in a virtual environment.
"""Print the versions this lab was tested with."""
from importlib.metadata import version
import platform
for package in ("pyspark", "delta-spark", "confluent-kafka", "fastavro"):
print(f"{package} {version(package)}")
print("python", ".".join(platform.python_version_tuple()[:2]))python3.12 -m venv .venv
source .venv/bin/activate
pip install "pyspark==4.2.0" "delta-spark==4.4.1" \
"confluent-kafka[avro,schemaregistry]==2.16.1"
python versions.pypyspark 4.2.0
delta-spark 4.4.1
confluent-kafka 2.16.1
fastavro 1.13.1
python 3.1202. Step 1: Write down the clicks
Each tuple is an event id, a user and the event time. The list order is the order in which the clicks reach the job, grouped into micro-batches. e05, e07 and e09 arrive after clicks with later times.
"""Twelve clicks in five micro-batches, in the order they reach the job."""
BATCHES = [
[("e01", "u1", "12:01"), ("e02", "u2", "12:03"), ("e03", "u1", "12:07")],
[("e04", "u2", "12:14"), ("e05", "u1", "12:04")],
[("e06", "u1", "12:18"), ("e07", "u2", "12:02")],
[("e08", "u1", "12:26"), ("e09", "u2", "12:09")],
[("e10", "u2", "12:31"), ("e11", "u1", "12:11"), ("e12", "u2", "12:03")],
]03. Step 2: Apply the watermark rules by hand
Spark's rules, applied one micro-batch at a time, are:
- Before a batch starts, the watermark becomes the largest event time from earlier batches minus the delay. It never moves backwards.
- Inside the batch, a click is dropped as late when its window already ended at or before the watermark of the previous batch. Otherwise it updates the count of its window.
- At the end of the batch, every window whose end is at or before the current watermark is final. Append mode writes it once and removes it from the state.
The script applies these rules and prints every decision.
"""Replay the clicks through Spark's watermark rules, one micro-batch at a time."""
from clicks import BATCHES
WINDOW, DELAY = 5, 10 # minutes: 5-minute tumbling windows, 10-minute watermark
def minutes(hhmm):
hours, mins = hhmm.split(":")
return int(hours) * 60 + int(mins)
def clock(m):
return f"{m // 60:02d}:{m % 60:02d}" if m >= 0 else "none"
state = {} # window start -> count, for windows that are still open
max_seen = -1 # largest event time seen in earlier batches
watermark = -1 # max_seen - DELAY, computed before each batch, never moves back
for batch_id, clicks in enumerate(BATCHES + [[]]): # the last batch has no data
late_limit = watermark # the previous batch's watermark
watermark = max(watermark, max_seen - DELAY)
print(f"batch {batch_id}: watermark {clock(watermark)},"
f" late if window ends by {clock(late_limit)}")
for event_id, _user, at in clicks:
start = minutes(at) // WINDOW * WINDOW
if start + WINDOW <= late_limit:
print(f" {event_id} {at} dropped: window {clock(start)} is closed")
continue
state[start] = state.get(start, 0) + 1
print(f" {event_id} {at} -> window {clock(start)}, count {state[start]}")
for start in sorted(state):
if start + WINDOW <= watermark: # append mode: final windows only
print(f" emit {clock(start)}-{clock(start + WINDOW)}: {state.pop(start)}")
max_seen = max([max_seen] + [minutes(at) for _, _, at in clicks])
print("still open:", ", ".join(f"{clock(s)}={n}" for s, n in sorted(state.items())))python watermark_sim.pybatch 0: watermark none, late if window ends by none
e01 12:01 -> window 12:00, count 1
e02 12:03 -> window 12:00, count 2
e03 12:07 -> window 12:05, count 1
batch 1: watermark 11:57, late if window ends by none
e04 12:14 -> window 12:10, count 1
e05 12:04 -> window 12:00, count 3
batch 2: watermark 12:04, late if window ends by 11:57
e06 12:18 -> window 12:15, count 1
e07 12:02 -> window 12:00, count 4
batch 3: watermark 12:08, late if window ends by 12:04
e08 12:26 -> window 12:25, count 1
e09 12:09 -> window 12:05, count 2
emit 12:00-12:05: 4
batch 4: watermark 12:16, late if window ends by 12:08
e10 12:31 -> window 12:30, count 1
e11 12:11 -> window 12:10, count 2
e12 12:03 dropped: window 12:00 is closed
emit 12:05-12:10: 2
emit 12:10-12:15: 2
batch 5: watermark 12:21, late if window ends by 12:16
emit 12:15-12:20: 1
still open: 12:25=1, 12:30=1Follow the 12:00 window. Clicks e01, e02, e05 and e07 land in it over three batches. The window is emitted in batch 3, when the watermark (12:18 minus 10 minutes, so 12:08) passes its end at 12:05.
Batch 4 is the tricky one. Its watermark jumps to 12:16 because batch 3 contained e08 at 12:26. e12, at 12:03, belongs to the 12:00 window, which ended long before, so it is dropped. e11, at 12:11, is 15 minutes behind the newest click seen before its batch, more than the 10 minutes you allowed, yet it is counted. So was e07 in batch 2, 12 minutes behind e04. The reason is rule 2: Spark checks late input against the previous batch's watermark (12:08) and uses the new one (12:16) only to decide what to emit. Spark's documentation states the guarantee in one direction only: data less late than the delay is never dropped, and data later than that may or may not be counted. Treat the delay as a lower bound, not as an exact cut-off.
Two windows are still open at the end. They will be emitted only when newer clicks move the watermark past 12:30 and 12:35. If the stream goes quiet, they wait.
04. Step 3: Check the trace with Spark
Now let Spark do the same work. The helper below starts Spark in local mode, in UTC, without the web UI; its lakehouse and catalog options are for lessons 4 and 5. The script writes each micro-batch as one JSON file and reads the folder with maxFilesPerTrigger set to 1, so each file becomes one micro-batch. trigger(availableNow=True) processes what is there and stops. foreachBatch prints what each batch emits, and recentProgress gives each batch's input rows and watermark.
"""Local Spark sessions for the stream-processing lessons."""
from pathlib import Path
from pyspark.sql import SparkSession
LAB = Path(__file__).resolve().parent
PACKAGES = [
"io.delta:delta-spark_4.2_2.13:4.4.1",
"org.apache.spark:spark-sql-kafka-0-10_2.13:4.2.0",
]
def local_session(app_name, lakehouse=False, catalog=False):
"""Spark in local mode. lakehouse=True loads Kafka and Delta Lake; catalog=True
keeps table and view names in a local Hive metastore (folder metastore_db)."""
builder = (
SparkSession.builder.master("local[2]")
.appName(app_name)
.config("spark.driver.host", "127.0.0.1")
.config("spark.driver.bindAddress", "127.0.0.1")
.config("spark.ui.enabled", "false")
.config("spark.sql.session.timeZone", "UTC")
.config("spark.sql.shuffle.partitions", "4")
.config("spark.local.dir", str(LAB / ".spark-tmp"))
)
if lakehouse:
builder = (
builder.config("spark.jars.packages", ",".join(PACKAGES))
.config("spark.jars.ivy", str(LAB / ".ivy"))
.config("spark.sql.extensions", "io.delta.sql.DeltaSparkSessionExtension")
.config(
"spark.sql.catalog.spark_catalog",
"org.apache.spark.sql.delta.catalog.DeltaCatalog",
)
)
if catalog:
builder = builder.config("spark.sql.warehouse.dir", str(LAB / "warehouse"))
builder = builder.enableHiveSupport()
spark = builder.getOrCreate()
spark.sparkContext.setLogLevel("ERROR")
return spark"""Run the clicks through Spark Structured Streaming, one JSON file per micro-batch."""
import json
import os
import shutil
import sys
from pyspark.sql import functions as F
from clicks import BATCHES
from session import local_session
shutil.rmtree("wm/input", ignore_errors=True) # start each run from scratch
os.makedirs("wm/input")
for batch_id, clicks in enumerate(BATCHES):
path = f"wm/input/batch-{batch_id}.json"
with open(path, "w") as f:
for event_id, user, at in clicks:
row = {"event_id": event_id, "user_id": user, "ts": f"2026-11-02 {at}:00"}
f.write(json.dumps(row) + "\n")
stamp = 1_800_000_000 + batch_id # the file source reads oldest files first
os.utime(path, (stamp, stamp))
GROUPS = {
"tumbling": lambda: [F.window("ts", "5 minutes")],
"sliding": lambda: [F.window("ts", "10 minutes", "5 minutes")],
"session": lambda: [F.session_window("ts", "5 minutes").alias("window"), "user_id"],
}
def show(batch, batch_id):
rows = batch.select(
F.date_format("window.start", "HH:mm").alias("start"),
F.date_format("window.end", "HH:mm").alias("end"),
*(["user_id"] if "user_id" in batch.columns else []),
"clicks",
F.array_join("ids", ",").alias("ids"),
).orderBy("start", *(["user_id"] if "user_id" in batch.columns else []))
for r in rows.collect():
who = f" {r['user_id']}" if "user_id" in r else ""
print(f" batch {batch_id} emits {r['start']}-{r['end']}{who}: {r['clicks']}"
f" ({r['ids']})")
spark = local_session("windows")
for kind in sys.argv[1:]: # tumbling, sliding or session
print(f"== {kind}")
shutil.rmtree(f"wm/checkpoint-{kind}", ignore_errors=True)
clicks = (
spark.readStream.schema("event_id string, user_id string, ts timestamp")
.option("maxFilesPerTrigger", 1) # one file = one micro-batch
.json("wm/input")
.withWatermark("ts", "10 minutes")
)
counts = clicks.groupBy(*GROUPS[kind]()).agg(
F.count("*").alias("clicks"),
F.sort_array(F.collect_list("event_id")).alias("ids"),
)
query = (
counts.writeStream.outputMode("append")
.foreachBatch(show)
.option("checkpointLocation", f"wm/checkpoint-{kind}")
.trigger(availableNow=True)
.start()
)
query.awaitTermination()
if kind == "tumbling":
for p in query.recentProgress:
mark = p["eventTime"]["watermark"]
mark = "none" if mark.startswith("1970") else mark[11:16]
print(f"batch {p['batchId']}: {p['numInputRows']} in, watermark {mark}")
spark.stop()python spark_windows.py tumbling== tumbling
batch 3 emits 12:00-12:05: 4 (e01,e02,e05,e07)
batch 4 emits 12:05-12:10: 2 (e03,e09)
batch 4 emits 12:10-12:15: 2 (e04,e11)
batch 5 emits 12:15-12:20: 1 (e06)
batch 0: 3 in, watermark none
batch 1: 2 in, watermark 11:57
batch 2: 2 in, watermark 12:04
batch 3: 2 in, watermark 12:08
batch 4: 3 in, watermark 12:16
batch 5: 0 in, watermark 12:21Spark emits the same windows, in the same batches, with the same clicks as the hand trace: e12 is missing and e11 is counted. Batch 5 has no input rows: it is a no-data batch, which Spark runs when the last batch moved the watermark, so that the windows it closed are emitted.
05. Step 4: Sliding and session windows
Run the same clicks through a sliding window of 10 minutes that starts every 5 minutes, and through session windows per user with a 5-minute gap. Only the grouping changes; the watermark stays the same.
python spark_windows.py sliding session== sliding
batch 3 emits 11:55-12:05: 4 (e01,e02,e05,e07)
batch 4 emits 12:00-12:10: 7 (e01,e02,e03,e05,e07,e09,e12)
batch 4 emits 12:05-12:15: 4 (e03,e04,e09,e11)
batch 5 emits 12:10-12:20: 3 (e04,e06,e11)
== session
batch 3 emits 12:02-12:08 u2: 2 (e02,e07)
batch 4 emits 12:01-12:16 u1: 4 (e01,e03,e05,e11)
batch 5 emits 12:09-12:19 u2: 2 (e04,e09)In the sliding windows, most clicks count twice, because every click falls into two overlapping 10-minute windows. Look at e12 again: it is dropped from the window 11:55 to 12:05, which had already been emitted, but it is counted in 12:00 to 12:10, which was still open. With overlapping windows the late check is made per window, not per click.
Session windows are per key. User u2 has a session from 12:02 to 12:08: its last click was at 12:03, and the session ends one gap later. u1 clicked at 12:01, 12:04, 12:07 and 12:11, each within 5 minutes of the previous click, so one session runs from 12:01 to 12:16, the last click plus the gap. Its click at 12:18 starts a new session that is still open. In streaming queries Spark needs at least one column besides the session window in the grouping key, and it does not support update mode with them.
Choose the window by the question: tumbling for "how many per period", sliding for a rolling figure such as "views in the last 10 minutes, every 5 minutes", and sessions for visits, where a fixed clock boundary would cut one visit in two.
06. What happens to the dropped clicks
Spark discards dropped clicks without an error; only the numRowsDroppedByWatermark metric of each state operator in the query progress shows them. A few lost clicks may be fine for a dashboard, but not for billing. There are three options. You can drop them and document how late is too late. You can quarantine them: before the stateful operator, split the stream on a rule you control, such as "arrived more than 10 minutes after it happened", and write late events to their own table. Or you can correct results later: keep every raw event and let a batch job recompute the affected windows. Lesson 4 builds the quarantine path.
Apache Flink handles the same problem inside its window operator. A window can keep its state for an extra allowedLateness after the watermark passes its end; with the default event-time trigger, each late event within that time fires the window again with an updated result. Events that are later still can be sent to a side output with sideOutputLateData instead of being dropped.
07. Check your understanding
08. Apply it
For the practice project, write a short policy before you build the job in lesson 4:
- The watermark delay for the page-view counts, and the evidence for it: how late do clicks arrive in your data?
- What happens to clicks that are later than that: dropped, quarantined to a table, or corrected by a batch job.
- How you will notice drops, for example with an alert on
numRowsDroppedByWatermark.
Then change clicks.py so that e08 arrives one batch later, predict the new trace by hand, and check it with watermark_sim.py and spark_windows.py tumbling.
09. Review prompt
Without looking back, explain in your own words:
- how Spark computes the watermark, and when it changes;
- when a tumbling window is emitted in append mode, and why the newest windows wait;
- why
e11was counted although it was more than 10 minutes behind the newest click; - how the same late click can be dropped from one sliding window and counted in another.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.