What you will be able to do
- Apply select, filter and column expressions to a streaming DataFrame and name the kind of operation a stream cannot support
- Write a streaming aggregation grouped by a key, by an event-time window, or by both
- Choose between tumbling, sliding and session windows and write the matching window() or session_window() call
- Apply the rules for window time columns and duration strings
- Pick an output mode for an aggregated stream and explain why append mode depends on a watermark
Key concept
Event-time window as a grouping key — window() assigns each row to one or more time buckets, based on a timestamp column inside the data. Grouping by that bucket, alone or together with ordinary keys, turns a stream into a set of per-window aggregates. Spark keeps each aggregate in state and updates it as new rows arrive.
1.Selection and projection work on a stream unchanged
A streaming DataFrame accepts the same column operations as a static one. select projects expressions into new columns, filter (or its alias where) keeps the rows that match a condition, and withColumn, alias and the built-in SQL functions all work the same way. The Structured Streaming incremental programming model runs your batch-style query again on each new slice of input. This means a projection written for a table needs no changes to run against spark.readStream.
from pyspark.sql.functions import col, current_timestamp
transformed_df = (raw_df.select(
"*",
col("_metadata.file_path").alias("source_file"),
current_timestamp().alias("processing_time")
)
)Nothing runs when this line executes. transformed_df is a plan describing how to load and transform each record as it arrives. A row is processed only when a sink starts the query.
Selections and projections are stateless. Each output row depends only on the input row it came from, so Spark does not need to remember anything between micro-batches. Aggregations are different, as the next section shows.
Some operations cannot run on a stream at all. A source is treated as unbounded, so any operation that needs to see every row before it can produce output has no point at which it could finish. Sorting the whole stream is the standard example, because it would mean ordering an infinite set of rows. On an exam, if a streaming query fails and its only unusual step is a global sort, the stream's unbounded input is the cause.
Checkpoint 1 of 9· Fill the gap
This projection runs on a streaming DataFrame. It keeps every column and adds two derived ones. Which method completes it?
from pyspark.sql.functions import col, current_timestamp
transformed_df = (raw_df. ? (
"*",
col("_metadata.file_path").alias("source_file"),
current_timestamp().alias("processing_time")
)
)select projects a list of expressions, here "*" plus two aliased columns, into the output. It works on a stream exactly as it does on a static DataFrame. withColumn adds one named column at a time, filter keeps rows, and groupBy starts a stateful aggregation.
Checkpoint 2 of 9· Check yourself
A query reads from spark.readStream, applies filter, adds a column with withColumn, and then calls orderBy on the whole stream. It fails when started. What is the most likely cause?
Selection and projection are stateless and run on a stream unchanged. A global sort has to see the entire input before it can produce output, and a stream's input is unbounded, so the sort is the unsupported step.
“some transformations are not supported in Structured Streaming workloads because they would require sorting an infinite number of items”Source: docs.databricks.com
2.Grouped aggregations hold state across micro-batches
groupBy(...).count(), .agg(sum(...)) and other grouped aggregations are valid on a stream, and they do not need a time window. readings.groupBy("sensorId").count() is a legitimate streaming aggregation. It keeps a running count per sensor and adds to it with every micro-batch. Spark does not reject plain key grouping, and the key can be any groupable type, so no cast is needed.
The cost is state. To update a count instead of recomputing it from scratch, Spark has to keep the current value for every group it has ever seen. That makes aggregation a stateful operator, in the same family as distinct, dropDuplicates and stream-stream joins. The mechanics of the state store are covered in Stateful operators and the StateStore. What matters here is that a key-only aggregation never closes a group. A sensor that reported once a year ago still has a row in state, and the number of rows grows with every new key.
Grouping by an event-time window as well as by a key is what lets that state be bounded. Once a window is far enough in the past, its aggregate can be finalized and removed from state. A plain key has no such endpoint. The next two sections build on this difference.
Checkpoint 3 of 9· Check yourself
Suppose readings.groupBy("sensorId").count() runs on a streaming DataFrame with no window() and no watermark. What does Spark do?
Grouping by a key alone is a valid stateful streaming aggregation. Spark updates each group's count incrementally. A plain key has no endpoint, and there is no watermark here to remove old state, so Spark keeps a row for every key it has seen.
“Streaming queries accumulate state data over time. Watermarks automatically remove old state data to prevent memory errors and increased processing latency.”Source: docs.databricks.com
3.Tumbling, sliding and session windows
window(timeColumn, windowDuration, slideDuration) assigns each row to time buckets based on a timestamp in the data. You place the call inside groupBy, usually next to ordinary key columns. The number of arguments decides the window type.
Tumbling windows have a fixed size and do not overlap, so every row lands in exactly one window. You get them by passing only a window duration, for example window("event_time", "10 minutes"). Use them for discrete period totals such as hourly sales or a count for each 10-minute period.
from pyspark.sql.functions import window
(df
.withWatermark("event_time", "10 minutes")
.groupBy(
window("event_time", "5 minutes"),
"id")
.count()
)Sliding windows add a third argument, the slide. A new window starts every slideDuration, and each window covers windowDuration. When the slide is shorter than the window, windows overlap and one row counts toward several of them. This gives a rolling figure, like a moving average. A click count over 20-minute periods refreshed every 5 minutes is window(click_time, "20 minutes", "5 minutes"), and each click falls into four overlapping windows. The order of the arguments matters: the window length comes first and the slide second. The slide must be less than or equal to the window length, so window(t, "5 minutes", "20 minutes") is invalid. A slide equal to the window length gives non-overlapping windows, which is the same result as a tumbling window, so it is not a way to get overlap.
from pyspark.sql.functions import window, sum
rolling_sales = (orders
.withWatermark("timestamp", "1 hour")
.groupBy(window("timestamp", "6 hours", slideDuration="1 hour"))
.agg(sum("amount").alias("total_sales"))
)Session windows use a different function, session_window(timeColumn, gapDuration), and they have no fixed size. A session opens when a row arrives, and each later row that arrives within the gap extends it. The session closes after a gap with no rows. Sessions fit bursts of activity separated by idle time, such as one user's page views. They are the wrong choice when the requirement names a fixed period such as "every 10 minutes".
from pyspark.sql.functions import session_window, sum
sessionized_page_views = (activity
.withWatermark("timestamp", "1 hour")
.groupBy("user_id", session_window("timestamp", gapDuration="30 minutes"))
.agg(sum("page_views").alias("total_page_views"))
)| Window type | Call | Windows overlap? | Windows per row | Fits |
|---|---|---|---|---|
| Tumbling | window("timestamp", "1 hour") | No | Exactly one | Hourly sales totals |
| Sliding | window("timestamp", "6 hours", slideDuration="1 hour") | Yes, when slide < window | Possibly several | Sales over a rolling 6-hour period |
| Session | session_window("timestamp", gapDuration="30 minutes") | No fixed size; closes after the gap | One session per key | A user's page views between idle periods |
Checkpoint 4 of 9· Match them up
Each call below is placed inside groupBy on a streaming DataFrame. Match each call to the windows it produces.
Tap a term, then the definition that fits it.
With only a duration, window() gives tumbling windows. A third argument shorter than the window gives overlapping sliding windows. session_window sizes each window by an inactivity gap. The second argument is the window length and the third is the slide, and the slide may not be longer than the window, so the 5-minute window with a 20-minute slide is invalid.
“slideDuration must be less than or equal to the windowDuration.”Source: docs.databricks.com
Checkpoint 5 of 9· Exam question
A monitoring pipeline reads a streaming DataFrame logins with an event-time column event_time and needs 10-minute tumbling windows that report a fresh count for every 10-minute period with no overlap between consecutive windows. Which line correctly defines this windowed aggregation?
result = logins.groupBy(
___
).count()
Correct answer: A — window(logins.event_time, "10 minutes")
- A. This is correct because omitting the slide duration argument to
window()makes the slide equal to the window duration, which produces non-overlapping tumbling 10-minute windows. - B. This is incorrect because passing a 5-minute slide duration alongside the 10-minute window duration creates overlapping sliding windows, not the non-overlapping tumbling windows the scenario requires.
- C. This is incorrect because
session_windowproduces variable-length windows based on gaps between events, not the fixed-size tumbling windows the pipeline needs. - D. This is incorrect because writing the slide duration explicitly as equal to the window duration is redundant with omitting it, and a mismatched literal like this is easy to get wrong; the cleaner, standard tumbling-window call omits the third argument entirely.
- E. This is incorrect because a 5-minute window with a 10-minute slide leaves 5-minute gaps between windows where no data is captured, rather than producing continuous non-overlapping coverage.
Checkpoint 6 of 9· Exam question
A dashboard needs a running count of clicks per page over 20-minute periods, refreshed every 5 minutes so overlapping windows continuously update as new data arrives, similar to a moving average. Which window() call produces this behavior?
clicks.groupBy(
___,
clicks.page
).count()
Correct answer: A — window(clicks.click_time, "20 minutes", "5 minutes")
- A. This is correct because a 20-minute window duration with a 5-minute slide duration makes each window wider than the gap between window starts, producing overlapping sliding windows that refresh every 5 minutes.
- B. This is incorrect because it swaps the arguments, defining 5-minute windows that slide every 20 minutes, which would produce gaps between windows rather than the frequent overlapping refresh the dashboard needs.
- C. This is incorrect because omitting the slide duration makes the slide equal the window duration, producing non-overlapping tumbling windows, and chaining
repartitionafterward only changes parallelism, not window overlap. - D. This is incorrect because
session_windowbuilds variable-length windows from inactivity gaps in the data, not fixed 20-minute periods refreshing every 5 minutes. - E. This is incorrect because setting the slide duration equal to the window duration again produces non-overlapping tumbling windows, not the overlapping refresh cadence described.
4.Rules for the time column and window durations
The time column must be a timestamp. Both window() and session_window() need a TimestampType or TimestampNTZType column. A string column such as "2024-05-01 10:00" or an epoch number has to be converted first. If you want windows based on arrival time instead of event time, window on current_timestamp().
Durations are strings made of a number and a unit, for example '10 minutes', '1 second' or '1 day 12 hours'. The valid units are week, day, hour, minute, second, millisecond and microsecond. Each duration is a fixed length of time, not a calendar period, so 1 day is always 86,400,000 milliseconds. That is also why windows measured in months are not supported.
Window boundaries include the start and exclude the end. An event at 12:05 belongs to [12:05, 12:10) and not to [12:00, 12:05). By default, windows line up with 1970-01-01 00:00:00 UTC. The optional startTime argument shifts them, so hourly windows with a startTime of 15 minutes run 12:15–13:15, 13:15–14:15 and so on.
The result column is a struct named window with nested start and end timestamps. Select window.start and window.end when the sink needs flat columns.
Two more rules apply when a watermark is involved. The window must be built on the same timestamp column that the watermark is declared on. Inside groupBy() and window(), refer to that column by name ("event_time" or col("event_time")) so Spark keeps the event-time marker that the watermark relies on.
The window and the watermark are on different columns. The window has to use the same timestamp column as the watermark, otherwise the watermark cannot decide when a window is finished.
Checkpoint 7 of 9· Check yourself
In a streaming DataFrame, ts is a TimestampType column and ts_str is a StringType column with values like "2024-05-01 10:00". Which window() call inside groupBy is valid as written?
Durations are fixed lengths, built from units from microseconds up to weeks, so "1 day 12 hours" on a timestamp column gives valid 36-hour windows. Month durations are not supported, whether as the window length or as the slide. A string column has to be converted to TimestampType or TimestampNTZType before it can be windowed.
“You can set window durations from microseconds up to days. Month durations and longer are not supported.”Source: docs.databricks.com
5.Output modes after an aggregation
Adding an aggregation limits which output modes you can use. All three modes are covered in Output modes: append, update, complete. For aggregations, two of their definitions matter most. Complete mode works only with streaming aggregations and rewrites every result row on each trigger. Append mode, the default, emits a row only once that row can no longer change, and stateful operators use the watermark to decide when that point has come.
A running count per sensorId can always go up again, so append mode never has a moment when the row is safe to write. Neither the sink nor the missing window is the problem; the issue is that Spark cannot tell when a group is final. Two fixes work. For a running total, use update mode (emit the rows that changed) or complete mode (emit everything). For finalized results, group by an event-time window and declare a watermark. A watermark (withWatermark) sets how late data may arrive, and when it moves past a window's end, that window is closed and append mode can emit it.
Here is a worked example: hourly revenue with a 15-minute watermark. The first micro-batch contains $15 at 2:40pm, $10 at 2:30pm and $30 at 3:10pm, so the watermark is 3:10 − 15 min = 2:55pm. Then $20 arrives at 3:20pm, and the watermark moves to 3:05pm.
| Output mode | After batch 1 (watermark 2:55pm) | After the $20 at 3:20pm (watermark 3:05pm) |
|---|---|---|
| Append | Nothing: both [2pm, 3pm] and [3pm, 4pm] could still change | [2pm, 3pm]: $25, because the watermark has passed the window's end |
| Update | Both windows, since both changed | [3pm, 4pm]: $50, the only window that changed |
| Complete | All windows | All windows |
The choice affects state size as well as how soon results appear. In append and update modes, the state for windows the watermark has passed is dropped. Complete mode never drops aggregation state, because it has to rewrite the whole result on every trigger. Append mode always waits at least the watermark delay before writing a row. A 1-hour watermark therefore means at least a 1-hour delay downstream. In return, each window is written exactly once, which suits sinks that act on every write. A live dashboard that needs fresh numbers is better served by update mode.
Checkpoint 8 of 9· Match them up
A windowed aggregation with a watermark runs under each of the output modes below. Pair each mode with what it writes and what happens to its aggregation state.
Tap a term, then the definition that fits it.
Append waits for the watermark, so each window is written once, and update writes the rows that changed. Both drop state once the watermark passes a window. Complete has to rewrite the whole result on every trigger, so it can never drop aggregation state.
“Complete | Aggregation state isn't dropped. The query rewrites the target table for each trigger.”Source: docs.databricks.com
Checkpoint 9 of 9· Exam question
An engineer writes the following on a streaming DataFrame readings with columns sensorId and value:
counts = readings.groupBy("sensorId").count()
counts.writeStream.outputMode("append").format("console").start()
Running this raises an AnalysisException about the output mode. What is the most likely cause?
Correct answer: A — Append mode cannot emit a row for an aggregation until it is guaranteed never to change again, and without a watermark Spark has no way to know when a group's value is final.
- A. This is correct because append mode only emits a row once it is guaranteed not to change again, which for a non-windowed running aggregation without a watermark is never determinable, so Spark rejects it at analysis time.
- B. This is incorrect because
groupBy("sensorId").count()is a perfectly valid streaming aggregation on its own; awindow()call is only required for event-time windowed aggregations, not for every grouped count. - C. This is incorrect because the console sink supports append, update, and complete modes; it does not silently coerce or reject modes based on sink type.
- D. This is incorrect because streaming sources typically infer or are given a schema already, and schema presence is unrelated to which output modes an aggregation query may use.
- E. This is incorrect because grouping keys in Structured Streaming aggregations work with their native column type and do not require an explicit cast to string.
Sources
(8)
Every claim above is drawn from one of these pages, quoted as it was written on the date shown.
- 1.
“Structured Streaming supports most transformations that are available in Databricks and Spark SQL.”
↩︎ Selection and projection work on a stream unchanged“some transformations are not supported in Structured Streaming workloads because they would require sorting an infinite number of items.”
↩︎ Selection and projection work on a stream unchanged“some transformations are not supported in Structured Streaming workloads because they would require sorting an infinite number of items”
↩︎ Checkpoint - 2.
“Projects a set of expressions and returns a new DataFrame.”
↩︎ Selection and projection work on a stream unchanged - 3.
“Stateless queries process rows without retaining state. Stateful queries maintain intermediate state for aggregations, joins, and deduplication.”
↩︎ Selection and projection work on a stream unchanged - 4.
“Stateful operations include streaming aggregation, distinct, dropDuplicates, stream-stream joins, and custom stateful applications.”
↩︎ Grouped aggregations hold state across micro-batches - 5.
“Streaming queries accumulate state data over time. Watermarks automatically remove old state data to prevent memory errors and increased processing latency.”
↩︎ Grouped aggregations hold state across micro-batches“Tumbling windows are fixed-size with non-overlapping intervals. Each input row belongs to exactly one window.”
↩︎ Tumbling, sliding and session windows“Sliding windows are fixed-size with intervals that can overlap. A single row can belong to multiple windows.”
↩︎ Tumbling, sliding and session windows“Use current_timestamp() to define windows based on processing time rather than event time.”
↩︎ Rules for the time column and window durations“reference columns by name, "<colName>" or col("<colName>"), to ensure the event time marker is preserved.”
↩︎ Rules for the time column and window durations“Aggregation state isn't dropped. The query rewrites the target table for each trigger.”
↩︎ Output modes after an aggregation“A count is collected for each id observed for each non-overlapping 5 minute window.”
↩︎ Key concept“slideDuration must be less than or equal to the windowDuration.”
↩︎ Exam trap 2“Session windows have no fixed size. A window opens when a row arrives and closes after a gap duration that contains no new rows.”
↩︎ Exam trap 3“The timeColumn argument for window() and session_window() must be of TimestampType or TimestampNTZType.”
↩︎ Exam trap 4“slideDuration must be less than or equal to the windowDuration.”
↩︎ Checkpoint“You can set window durations from microseconds up to days. Month durations and longer are not supported.”
↩︎ Checkpoint“Complete | Aggregation state isn't dropped. The query rewrites the target table for each trigger.”
↩︎ Checkpoint - 6.
“If the slideDuration is not provided, the windows will be tumbling windows.”
↩︎ Tumbling, sliding and session windows“Valid interval strings are 'week', 'day', 'hour', 'minute', 'second', 'millisecond', 'microsecond'.”
↩︎ Rules for the time column and window durations“For example, 1 day always means 86,400,000 milliseconds, not a calendar day.”
↩︎ Rules for the time column and window durations“Windows in the order of months are not supported.”
↩︎ Rules for the time column and window durations“Window starts are inclusive but the window ends are exclusive, e.g. 12:05 will be in the window [12:05,12:10) but not in [12:00,12:05).”
↩︎ Rules for the time column and window durations“The startTime is the offset with respect to 1970-01-01 00:00:00 UTC with which to start window intervals.”
↩︎ Rules for the time column and window durations“The output column will be a struct called 'window' by default with the nested columns 'start' and 'end'”
↩︎ Rules for the time column and window durations - 7.
“The window must be based on the same timestamp column as the watermark”
↩︎ Rules for the time column and window durations - 8.
“Complete mode only works with streaming aggregations.”
↩︎ Output modes after an aggregation“In this mode, operators only emit rows that don't change in future triggers. Stateful operators use the watermark to determine when this happens.”
↩︎ Output modes after an aggregation“By the definition of the watermark, that window can no longer change, so it emits the [2pm, 3pm] window.”
↩︎ Output modes after an aggregation“Append mode forces stateful operators to emit results only after stateful results are finalized, which is at least as long as your watermark delay.”
↩︎ Output modes after an aggregation“Append mode forces stateful operators to emit results only after stateful results are finalized, which is at least as long as your watermark delay.”
↩︎ Exam trap 1