Skip to content
Silver 7 min read · window 3 practice problems ↓

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

Read first: Watermarks and late data (skip if you know it)

In plain words first

Tumbling: hours on a clock

9 to 10, 10 to 11, 11 to 12. Every event belongs to exactly one hour, with no gaps or overlaps.

Sliding: "the last 10 minutes", checked every 5

At 10:05 you look back to 09:55, at 10:10 back to 10:00. The pieces overlap, so one event is counted in several of them.

Session: a phone call

It lasts as long as people keep talking, and ends after a silence. Its length is different every time.

The three windows in code

WindowCallEach event lands inTypical question
TumblingF.window("ts", "5 minutes")Exactly one windowClicks per 5 minutes
SlidingF.window("ts", "10 minutes", "5 minutes")length / slide windows (here 2)A 10-minute total, refreshed every 5 minutes
SessionF.session_window("ts", "5 minutes")One session per key, ended by 5 quiet minutesHow 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

It falls in 09:55-10:05 and in 10:00-10:10. Spark copies the row once per window before counting.

Event 10:07 · two windows

It falls in 10:00-10:10 and 10:05-10:15. The 10:00-10:10 window now counts both events.

The cost · × 2

With length / slide = 2, every event is counted twice and twice as many windows are kept in memory. A 1-hour window sliding every minute keeps 60 copies: choose the slide as large as the question allows.

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")).

Watch out: in a streaming query, session windows allow append and complete output modesoutput mode: Which rows a stream writes after each micro-batch: only new final rows (append), rows that changed (update), or the whole result (complete). Learn more →, not update: Spark refuses to start with 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.

ExplorePySpark · One set of clicks, three kinds of window
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.

Production patternPySpark · Windowed counts in a stream, written 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 with startTime, 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?"

Group by user and session_window(event_time, gap), for example 30 minutes, with a watermark on event_time sized from measured lateness. Each output row is one visit: window.start and window.end give its length, and count() its clicks. Use append mode, since update is not supported for session windows; a visit is written once the watermark passes its end. Mention that a late click can merge two sessions, which is why Spark waits for the watermark.

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?"
Pass startTime, the fourth argument of window(): window("ts", "1 day", "1 day", "6 hours"). Windows are aligned to the epoch in UTC, and startTime shifts that grid.
Scenario"A late click arrives between two sessions of the same user. What happens?"
If it is within the watermark, it can bridge the gap, and the two sessions merge into one longer session. That is why Spark only writes a session once the watermark has passed its end, and why update mode is not supported for session windows.
Trap"Windows on a batch DataFrame and on a stream behave differently."
The functions are the same and give the same windows. What a stream adds is time: windows stay open until the watermark finalises them.

Check yourself

3 questions

With 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 read
Deduplicating a stream
Where duplicates come from, dropDuplicatesWithinWatermark, and deduplicating at the sink.

Related lessons

Previous: Watermarks and late data

Primary sources: Window operations on event time · window function · session_window function