Structured Streaming: Beginner
The input table and the result table
| Clock | Rows appended | Input table | Result table |
|---|---|---|---|
| 23:58:00 | ride 1 (SoMa), ride 2 (Mission), ride 3 (SoMa) | 3 rows | SoMa 2, Mission 1 |
| 23:58:10 | ride 4 (SoMa), ride 5 (Marina) | 5 rows | SoMa 3, Mission 1, Marina 1 |
| 23:58:20 | ride 6 (Mission) | 6 rows | SoMa 3, Mission 2, Marina 1 |
| 23:58:30 | none | 6 rows | SoMa 3, Mission 2, Marina 1 |
Check the last column against the input size. At 23:58:20 the result is exactly what groupBy("zone").count() returns on the 6 rows received by then. At 23:58:30 nothing new arrived, so the answer stays put. That equivalence is the contract every streaming query keeps: the same answer as the batch query over all data so far, refreshed whenever the data grows.
Updating without rereading
- Input holds a fixed set of rows
- Runs once and ends
- Reads all of its input on every run
- Answer is final when the job ends
- Input gains rows for as long as the query runs
- Runs until you stop it
- Reads only rows new since the last update
- Answer is refreshed each time rows arrive
At 23:58:30 the result table reads SoMa 3, Mission 2, Marina 1. At 23:58:40 the only arrivals are rides 7 and 8, both from SoMa. What does Spark's next update produce, and which rows does it read?
The answer always trails the data
spark.read, and compare. The batch answer must match the stream's result table over the same rows.The seed's stream_msgs table is a saved slice of a message log with a row per message. Each row holds the message's topic and offset, plus the consumer recorded for it, or null where none is. Treat it as an input table frozen at an instant and run the count per topic: the rows that come back are the result table a standing query would show at that instant. Then add .where("consumer IS NOT NULL") before the groupBy and run it again. This standing query counts only messages with a consumer recorded, so no topic's count rises, and a topic with no consumer recorded drops out.
msgs = spark.table("stream_msgs")
per_topic = (
msgs
.where("topic IS NOT NULL")
.groupBy("topic")
.count()
.orderBy("topic")
)
per_topic.show()One turn of the loop
- ▸Asks the source for its newest position: the latest file in a folder, or the latest offset in each partition of a message log.
- ▸Writes down the range from the previous batch's end to that position, before any data is read.
- ▸Plans the query over only the rows inside that range and runs it as a job on the executors.
- ▸Hands the job's output to the sink and marks the batch committed once the write has landed.
- ▸Waits for the trigger, then starts the next batch at the position where this one ended.
Batch 7, played as a job
Take the zone count at batch 7, whose range held 9 rows read as 2 input partitions. Play the job and find its shuffle. The where runs inside the tasks that read each partition, and the groupBy moves rows so that each zone lands on one of 3 reduce tasks, the same exchange a nightly job over a year of requests would run.
result = (batch_7.where("status = 'requested'").groupBy("zone").count().collect())
Small batches pay full job prices
Every micro-batch pays a job's fixed costs before it touches a row: the driver plans and schedules it, then waits for the slowest task to report back. The animation used 3 reduce tasks to fit the screen. A real streaming aggregation shuffles into spark.sql.shuffle.partitions reduce tasks in every batch, 200 by default. Adaptive Query Execution, which would coalesce the empty ones in a batch job, is switched off inside a streaming query. For batch 7, that is 200 reduce tasks to count 3 zones, at least 197 of them with nothing to read. Each micro-batch also appears on the Jobs tab of the Spark UI as at least one job of its own, so a stream left running over a weekend fills that tab.
Keeping up with the stream
One health check outranks the rest: each batch must finish faster than its share of data arrives. If a batch covers 10 seconds of requests and takes 4 seconds, the stream keeps up. If it takes 14, the next batch starts 4 seconds late with a bigger range. That batch runs longer and pushes the one after it later still. Each finished batch leaves a progress report, which the running query exposes as lastProgress:
A stream runs on a 10-second schedule. For the past hour the Structured Streaming tab shows batch durations of 12 to 13 seconds and an input rate above the process rate. What happens to the stream from here?
New files or new offsets enter on the left. Each micro-batch's output leaves on the right through a single sink per query: a Parquet folder, or a function that writes wherever it needs to.
What a source must provide
A source also has to fix a schema before the first batch, because every batch must produce the same columns. File sources refuse to guess by default: spark.readStream.json(path) without a .schema(...) call raises an error on that line, where spark.read.json(path) would have scanned the files to work a schema out. The inferSchema lesson priced that scan for a single read, and a stream would pay it against a folder that never stops changing.
| Source | Format name | How it tells what is new | Use |
|---|---|---|---|
| Files in a folder | json, csv, parquet, orc, text | Remembers every file it has read | Data landed by other jobs |
| Message log | set by the log's connector | Tracks an offset per log partition | Events from apps and services |
| Rate | rate | Counts the rows it has generated | Load tests: rows of timestamp and value at rowsPerSecond |
| Socket | socket | Numbers lines in memory only; cannot replay them after a restart | Demos only: lines read from a host and port |
What a sink must provide
Each batch hands the sink a set of output rows. The sink has to take them batch after batch without disturbing what it wrote earlier, and it has to tell Spark when a batch's write has landed, so the driver can mark that batch committed. The file sink does both by adding new files for each batch and listing, in a _spark_metadata log inside the output folder, which files belong to committed batches. Spark jobs that read the folder later consult that log and see only committed files.
| Sink | Format name | What it does with a batch | Use |
|---|---|---|---|
| File | parquet, json, csv, orc, text | Adds new files and never rewrites old ones | Tables that later jobs read |
| Message log | set by the log's connector | Publishes each output row as a message | Feeding other services |
| foreachBatch | a function you write | Calls it with the batch as a DataFrame and its id | Any destination a batch writer reaches |
| Console | console | Prints the batch's rows on the driver | Debugging |
| Memory | memory | Keeps all output as a table in driver memory | Debugging small streams |
foreachBatch is the sink to reach for when no built-in one fits. Inside your function the micro-batch is an ordinary batch DataFrame, so you can join it or call write on it before handing it to any batch writer you know. The memory sink comes with the opposite warning: it repeats the collect() problem in streaming form, because every output row stays in the driver, and a stream left on overnight can exhaust the driver's heap.
.format("console") first. The console sink prints each micro-batch under a header such as Batch: 7, so you can see which rows landed in which batch before the query writes to a real table.A stream must read JSON files from /landing/payments and update a team dashboard whose database has no built-in Spark sink. Which source setup and sink fit?
What changed, line by line
| Part | Batch | Stream | Why |
|---|---|---|---|
| Read | `spark.read` | `spark.readStream` | Returns a streaming DataFrame |
| Schema | Inferred by scanning the files | Stated with `.schema(...)` | Every batch must yield the same columns |
| Transformations | `where`, `select` | Unchanged | Same DataFrame API, planned per batch |
| Write | `write` ... `parquet()` | `writeStream` ... `start()` | Launches a query that runs until stopped |
| Progress folder | None | `checkpointLocation` | Where the driver records each batch's range |
The middle block is identical to the character. requested.isStreaming returns True, and Catalyst plans the where and select for each micro-batch as it plans them for the batch job; explain() on the streaming DataFrame shows the same filter and projection.
start() hands back a handle
write.parquet() is an action: the call blocks until the files exist, then returns. writeStream.start() launches the query on a background thread in the driver and returns a StreamingQuery handle straight away, while the micro-batches run behind it. Most daily work needs only 4 calls on that handle:
status says whether a batch is running or the query is waiting for data. lastProgress is the batch report from the micro-batch section. awaitTermination() blocks the calling program until the query ends, and a script submitted to a cluster needs it: the background thread does not keep the application alive, so a script that finishes right after start() takes its stream down with it. stop() ends the query.
What a stream refuses
The first thing a stream refuses is an action. Calling requested.count() or requested.show() raises an AnalysisException whose message begins "Queries with streaming sources must be executed with writeStream.start()". An action asks for a single final answer over a fixed input, and a streaming DataFrame has no fixed input to give. Some transformations are refused too, at start() rather than on the line where you wrote them. An orderBy over raw rows is one: placing the first row in order requires seeing the last, and a stream has no last row. The lazy-evaluation lesson showed errors surfacing at the action; in a stream, start() is where the whole plan gets checked.
A teammate tests a new stream with the program below. What happens when it runs?
The seed's app_event_deliveries table is a saved slice of an app's event feed. The cell below runs the batch form of a per-event projection. Run it, then work out the streaming version line by line: which call becomes readStream, and which line writeStream and start() would replace.
deliveries = spark.table("app_event_deliveries")
named = (
deliveries
.where("event_name IS NOT NULL")
.select("event_uuid", "user_id", "event_name", "event_ts")
)
named.show()The trigger decides when the next micro-batch starts. It is a single call on the writer, .trigger(...) placed before start(), and it sets the trade-off between how fresh the result table is and what the stream costs to keep running. Micro-batch queries take 4 trigger settings:
| Trigger | Code | When the next batch starts | When the query stops |
|---|---|---|---|
| Default | no `.trigger` call | As soon as the previous batch ends, if new data exists | When you stop it |
| Fixed interval | `.trigger(processingTime="10 seconds")` | At the next 10-second boundary, if new data exists | When you stop it |
| Available now | `.trigger(availableNow=True)` | Right away, batch after batch, until the data present at start is done | Once that data is processed |
| Once | `.trigger(once=True)` | Right away, as a single batch holding all data present at start | After that batch; deprecated since Spark 3.4 |
A fixed interval under load
With processingTime="10 seconds", Spark aims to start batches at 23:59:00, 23:59:10, 23:59:20 and on through the night. A batch that finishes early leaves the executors idle until the next boundary. A batch that overruns its slot is followed by the next one the moment it ends, and the boundaries it missed are skipped, never queued. If no new data has arrived by a boundary, no batch runs at all.
| Batch | Planned start | Actual start | Duration | What follows |
|---|---|---|---|---|
| 7 | 23:59:00 | 23:59:00 | 4 s | Executors idle 6 s until 23:59:10 |
| 8 | 23:59:10 | 23:59:10 | 14 s | Batch 9 starts at 23:59:24, no wait |
| 9 | 23:59:20 | 23:59:24 | 5 s | Executors idle 1 s until 23:59:30 |
A stream runs with .trigger(processingTime="10 seconds"), and every batch now takes 25 seconds. When do its batches start?
Latency and cost
Matching the trigger to the need
| Need | Trigger | Why |
|---|---|---|
| Surge dashboard fresh within 30 seconds | `processingTime="10 seconds"` | Bounded freshness, with batches big enough to spread each job's fixed cost |
| Fraud score as soon as micro-batches allow | Default | Each batch starts the moment the last one ends |
| Finance table refreshed each morning | `availableNow=True`, started by a scheduler | The cluster runs only while it catches up, then shuts down |
With availableNow=True, a stream behaves like a scheduled batch job that remembers where it stopped. Start it at 06:00 and it processes every file that landed since the previous run, in as many micro-batches as rate limits such as maxFilesPerTrigger allow, then stops, so the job that launched it can finish and release its executors. The next run picks up where this one ended, and no job has to work out which files are new. once=True did the same work in a single batch and ignored rate limits, which turned a large backlog into a single oversized job; Spark 3.4 deprecated it in favor of availableNow.
A finance team needs yesterday's card payments in a Parquet table by 07:00 each day and wants to pay for executors only while they work. Which setup fits?
> Picture Uber's New Year's Eve in San Francisco: requested rides land as JSON files in a landing folder, a stream counts them per zone every 10 seconds for the surge dashboard, and finance wants the same rides as a Parquet table by 07:00 on January 1.
foreachBatch function, because the dashboard's database has no built-in sink.availableNow, so its executors are paid for only while it catches up, and it writes fewer, larger files than a 10-second stream would.spark.sql.shuffle.partitions reduce tasks after a shuffle, with Adaptive Query Execution switched off.readStream and writeStream ... start() replace the batch ends, the transformations between them stay the same, and actions are refused.availableNow clears the backlog and stops.Treat a stream as a table that never stops growing, and let Spark answer your query over it in small batch jobs.
- Category
- Spark
- Difficulty
- beginner
- Duration
- 13 minutes
- Challenges
- 13 hands-on challenges
Topics covered: A Stream Is a Growing Table, Micro-Batches, Sources and Sinks, readStream and writeStream, Triggers
Lesson Sections
- A Stream Is a Growing Table (concepts: Structured Streaming)
The jobs you have run so far read input that sat still: it held a fixed set of rows when the action began, and the job finished once it had read them all. Ride requests never sit still. On a busy night a phone somewhere sends a new one every few milliseconds, so the dataset you want to count has no last row, and any batch job run over it is out of date the moment it ends. Structured Streaming, the stream engine built into Spark since version 2.0, treats the stream as a table that gains rows fore
- Micro-Batches (concepts: Structured Streaming)
Spark runs a standing query as a loop of ordinary batch jobs. Each job, called a micro-batch, covers the rows that arrived since the job before it, and the batches are numbered from 0. A micro-batch runs as tasks on the same driver and executors you already know, with the same shuffles. What Structured Streaming adds is the loop around them and the bookkeeping that hands each job its slice of the stream. One turn of the loop Fixing the range before reading turns an endless stream into a bounded
- Sources and Sinks (concepts: Structured Streaming)
A standing query has 2 ends. The source is where new rows come from, and the sink is where each batch's output goes. The choice of source decides whether Spark can tell which rows are new, and the choice of sink decides what becomes of output already written. What a source must provide Every micro-batch opens with the question "what is new since last time?", so a source has to answer in positions the driver can write down. A file source answers with the list of files it has already read: any fil
- readStream and writeStream (concepts: Structured Streaming)
Turning a batch job into a stream changes the 2 ends of the program and leaves the middle untouched. Here is a batch job that keeps the requested rides from the landing folder and appends them to a Parquet table: The same job as a stream reads every file that lands in the folder from now on: What changed, line by line start() hands back a handle What a stream refuses
- Triggers (concepts: Structured Streaming)
A fixed interval under load Batch 8 overran its slot, so batch 9, due at 23:59:20, began at 23:59:24 without waiting for 23:59:30. One slow batch costs a few seconds of freshness. Batches that overrun every slot run back to back, which is the default trigger in practice, and the freshness the interval promised is gone. Latency and cost Under a fixed interval that the batches keep up with, a row waits up to a full interval for its batch to start, then a batch duration for its result to land. At 1