Event-time windows
Most questions about a stream are about time: clicks per minute, a rolling hourly total, how long a visit lasted. Windows cut the stream into pieces of time to answer them. This lesson shows the three kinds of window, what each one costs, and when a window's number is final.
Step 4 · Structured Streaming · Silver · Stateful streams, lesson 2 of 3
On this page
Read first: Watermarks and late data (skip if you know it)
In plain words first
Tumbling: hours on a clock
Sliding: "the last 10 minutes", checked every 5
Session: a phone call
The three windows in code
| Window | Call | Each event lands in | Typical question |
|---|---|---|---|
| Tumbling | F.window("ts", "5 minutes") | Exactly one window | Clicks per 5 minutes |
| Sliding | F.window("ts", "10 minutes", "5 minutes") | length / slide windows (here 2) | A 10-minute total, refreshed every 5 minutes |
| Session | F.session_window("ts", "5 minutes") | One session per key, ended by 5 quiet minutes | How long a visit lasted |
All three produce a window column with a start and an end, which you group by together with any other keys. Windows line up with the clock in UTC: 5-minute windows start at :00, :05, :10. The optional fourth argument of F.window (startTime) shifts them, for example to make daily windows start at 06:00 instead of midnight.
Sliding windows: one event, several windows
Event 10:03 · two windows
Event 10:07 · two windows
The cost · × 2
Session windows
A session starts with an event and stays open while events keep coming within the gap. A click 3 minutes later extends it; 5 quiet minutes end it. Sessions are per user, so group by the user as well. The gap can also depend on the row, for example longer for mobile users: F.session_window("ts", F.when(F.col("device") == "mobile", "10 minutes").otherwise("5 minutes")).
STREAMING_OUTPUT_MODE.UNSUPPORTED_OPERATION. A late eventlate data: Events that arrive after newer events have already been seen, for example from a phone that was offline. Learn more → can join two sessions into one, which an update could not express.When a window is final
A window can change as long as events for it may still arrive. The watermarkwatermark: In streaming, how late data may arrive. Spark uses it to know when old state can be dropped. Learn more → decides when that stops: once it passes a window's end, the window is final, append mode writes it, and Spark forgets it. With withWatermark("ts", "5 minutes") and 5-minute tumbling windows, the 10:00-10:05 window is written once an event later than 10:10 has been seen. A session is final once the watermark passes its end, which is its last event plus the gap.
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: Group the same clicks into tumbling, sliding and session windows.
from pyspark.sql import functions as F clicks = spark.createDataFrame( [("ana", "2026-01-01 10:01:00"), ("ana", "2026-01-01 10:03:00"), ("ana", "2026-01-01 10:12:00"), ("bo", "2026-01-01 10:06:00")], "user STRING, ts STRING").withColumn("ts", F.to_timestamp("ts")) span = [F.date_format("w.start", "HH:mm").alias("from"), F.date_format("w.end", "HH:mm").alias("to")] tumbling = clicks.groupBy(F.window("ts", "5 minutes").alias("w")).count() tumbling.select(*span, "count").orderBy("from").show() sliding = clicks.groupBy(F.window("ts", "10 minutes", "5 minutes").alias("w")).count() sliding.select(*span, "count").orderBy("from").show() by_session = F.session_window("ts", "5 minutes").alias("w") sessions = clicks.groupBy("user", by_session).count() sessions.select("user", *span, "count").orderBy("user", "from").show()
Output from a real run
+-----+-----+-----+ | from| to|count| +-----+-----+-----+ |10:00|10:05| 2| |10:05|10:10| 1| |10:10|10:15| 1| +-----+-----+-----+ +-----+-----+-----+ | from| to|count| +-----+-----+-----+ |09:55|10:05| 2| |10:00|10:10| 3| |10:05|10:15| 2| |10:10|10:20| 1| +-----+-----+-----+ +----+-----+-----+-----+ |user| from| to|count| +----+-----+-----+-----+ | ana|10:01|10:08| 2| | ana|10:12|10:17| 1| | bo|10:06|10:11| 1| +----+-----+-----+-----+
What to notice:
- Tumbling (5 minutes): each click is in exactly one window.
- Sliding (10 minutes, every 5): each click is in two windows, so the counts add up to 8 for 4 clicks.
- Session (5-minute gap, per user): ana has two sessions because she was idle from 10:03 to 10:12. A session ends 5 minutes after its last click.
Goal: Write windowed counts from a stream only once each window is final.
import json, os from pyspark.sql import functions as F os.makedirs("lab/win/in", exist_ok=True) def land(name, times): with open(f"lab/win/in/{name}.json", "w") as f: f.write("\n".join(json.dumps({"event_time": f"2026-01-01 {t}"}) for t in times)) def run(): (spark.readStream.schema("event_time TIMESTAMP").json("lab/win/in") .withWatermark("event_time", "5 minutes") .groupBy(F.window("event_time", "5 minutes")).count() .select(F.date_format("window.start", "HH:mm").alias("window"), "count") .writeStream.outputMode("append").format("parquet") .option("path", "lab/win/out") .option("checkpointLocation", "lab/win/_chk") .trigger(availableNow=True) .start().awaitTermination()) spark.read.parquet("lab/win/out").orderBy("window").show() land("a", ["10:01:00", "10:02:00", "10:07:00"]) run() # nothing final yet: the watermark is 10:02 land("b", ["10:16:00"]) run() # the watermark moves to 10:11: windows 10:00 and 10:05 are final
Output from a real run
+------+-----+ |window|count| +------+-----+ +------+-----+ +------+-----+ |window|count| +------+-----+ | 10:00| 2| | 10:05| 1| +------+-----+
What to notice:
- The first run wrote nothing: the latest event was 10:07, so the watermark (10:02) had not passed the end of any window.
- After a 10:16 event, the watermark reached 10:11, and the 10:00 and 10:05 windows were written: 2 and 1.
- Each window is written once and never changes. The cost is delay: a window appears at least one window length plus the watermark after it opens.
Common mistakes
- A tiny slide on a long window —
F.window("ts", "1 hour", "1 minute")puts every event in 60 windows, so memory and work grow 60 times. Use a larger slide, or a tumbling window. - A session window without the user key —
groupBy(F.session_window("ts", "5 minutes"))alone mixes all users: one user's click keeps another user's session open. Group by the user too. - update mode with session windows — The query is refused at start. Use append (with a watermark) or complete.
- Expecting daily windows to follow local midnight —
F.window("ts", "1 day")runs midnight to midnight UTC, which is 05:30 to 05:30 in India. Shift it withstartTime, or report in UTC days.
Key takeaways
- Tumbling for counts per fixed period, sliding for a rolling total refreshed often, session for how long a visit lasted.
- A sliding window counts each event length / slide times: keep the slide large.
- A window is final once the watermark passes its end: append writes it once and forgets it.
- Session windows need the user key, and allow append or complete, not update.
Interview prep
THE QUESTION
"How would you compute visit lengths from a clickstream, in real time?"
Avoid: a sliding window with a one-minute slide on a one-hour window without mentioning that every event is then counted in 60 windows.
Follow-ups · answer out loud, then open
Follow-up"How do you make daily windows start at 06:00 instead of midnight?"
Scenario"A late click arrives between two sessions of the same user. What happens?"
Trap"Windows on a batch DataFrame and on a stream behave differently."
Check yourself
3 questionsWith window("ts", "1 hour", "15 minutes"), how many windows does each event fall into?
Show the answer
4. Length / slide = 60 / 15 = 4.
A user clicks at 10:00, 10:03 and 10:20. With session_window gap 5 minutes, how many sessions?
Show the answer
2. 10:00 and 10:03 form one session (ending 10:08); 10:20 starts another.
Which output mode does a streaming session window refuse?
Show the answer
update. Spark rejects update mode for session window aggregations.
Practise this
Problems that use this, graded on hidden tests
Keep going
Up next · Stateful streams · lesson 3 of 3 · 7 min readDeduplicating a stream
Where duplicates come from, dropDuplicatesWithinWatermark, and deduplicating at the sink.
Related lessons
Watermarks and late dataStructured Streaming · 6 min read
Output modes: append, update, completePySpark functions · 7 min read
Gaps and islands
Previous: Watermarks and late data
Primary sources: Window operations on event time · window function · session_window function