Structured Streaming: Beginner
A table that only gains rows
Picture a table named ride_requests. Each time a rider requests or cancels, one row is appended to the bottom. Existing rows never change and never leave. Spark calls this the input table, and because rows keep arriving it has no last row. Suppose it starts empty at 12:00:00. Here are the 7 rows that arrive in the next 20 seconds, with the second each one landed.
| ride_id | zone | status | arrived_at |
|---|---|---|---|
| 101 | SoMa | requested | 12:00:02 |
| 102 | Mission | requested | 12:00:05 |
| 103 | SoMa | cancelled | 12:00:07 |
| 104 | SoMa | requested | 12:00:09 |
| 105 | Marina | requested | 12:00:12 |
| 106 | SoMa | requested | 12:00:15 |
| 107 | Mission | cancelled | 12:00:18 |
A query that stays standing
| zone | count |
|---|---|
| SoMa | 2 |
| Mission | 1 |
| zone | count |
|---|---|
| SoMa | 3 |
| Mission | 1 |
| Marina | 1 |
- Input is a finished table
- Runs when you call an action
- Returns one answer, then ends
- A rerun reads every row again
- Input is a table that keeps gaining rows
- Runs from the moment it is started
- Keeps a result table current
- Ends when it's stopped or fails
One API for batch and streaming
Before this model, streaming code in Spark was written against a separate API with its own operations, so one piece of logic often lived in 2 codebases: a batch job for history and a streaming job for live data. Treating the stream as a table removes the split. The filter and the groupBy above are the DataFrame calls you know, Catalyst optimizes them the same way, and the plan contains the same shuffle on zone that a batch job would.
At 12:00:25 one more row arrives in ride_requests: ride 108, Marina, cancelled. What does the result table hold once Spark has taken that row into account?
The loop the driver runs
One pass through these 4 steps is one micro-batch. After the write, the driver goes back to step 1.
- Ask the source: where does your data end now? Anything past the previous batch's end is new.
- Fix the range: the driver records which rows this batch covers before any task runs.
- Run the job: executors process only those rows, using the plan Catalyst produced.
- Write the output: the result goes to the sink and the batch is complete.
Batch 7, up close
| Batch | Rows it covers | Starts at | Job runs for |
|---|---|---|---|
| 6 | 11 new rows | 23:01:00 | 2 s |
| 7 | 9 new rows, rides 701 to 709 | 23:01:10 | 2 s |
| 8 | 12 new rows | 23:01:20 | 3 s |
Inside the batch, everything is the Spark you know. The 9 rows sit in 2 input partitions, so the job opens with 2 tasks. The filter is narrow and drops the 2 cancelled rides in place, leaving 7. The groupBy is wide, so those rides cross a shuffle keyed on zone into 3 shuffle partitions, where the counts are finished. The animation plays that job, with collect() standing in for the write to the sink.
result = (batch_7.where("status = 'requested'").groupBy("zone").count().collect())
Batch 7 covered 9 rows and finished. 12 more rows arrive before batch 8 starts. Which rows does batch 8's job read?
Batch costs carry over
Because a micro-batch is a regular job, your batch knowledge transfers whole. A groupBy in the query means a shuffle in every batch, paid again each time. A join that is not broadcast shuffles both sides in every batch too. A join to a small lookup table, such as a list of zones under the 10MB broadcast threshold, gets broadcast instead, so it adds no shuffle. A hot key skews batch 7 the way it would skew a nightly job. And every batch pays a fixed cost before any row moves, since the driver has to plan the job and schedule its tasks. For 9 rows that overhead outweighs the work.
The Spark UI shows this directly. Each micro-batch appears in the Jobs tab as its own job, and the job description carries the batch number, such as batch = 7. Open it and you find the same stage and task breakdown, with shuffle sizes, that you would inspect for any slow job. A slow stream is a sequence of batch jobs that each take too long, and you find the slow stage the way you already know.
Rows enter from the source, pass through one batch job at a time, and land in the sink, where other systems read them.
Built-in sources
Spark ships with a short list of built-in sources. You pick one by name with format(...), the same call a batch read uses.
| Source | A new row is | Position Spark tracks | Used for |
|---|---|---|---|
| Files in a directory (parquet, json, csv, text) | A row in a file that appeared since the last batch | Which files it has already read | Production |
| Message log | A message appended to a topic | An offset per topic partition | Production |
| rate | A generated row with a timestamp and a counter value | The counter | Testing |
| socket | A line of text from a network connection | None that can be reread | Testing only |
What a source must provide
- A position. Every row needs an address, such as an offset or a file name, so the driver can define a batch as a range: offsets 4,180 to 4,188.
- A second read of the same range. If a batch's job fails partway, Spark runs it again over the identical range, so the source has to return those rows a second time.
- A schema known before the data. A batch read can infer a schema by scanning the files. A file stream has to be told its schema, because the files it will read do not exist yet.
| Batch | Offsets it covers | Rows |
|---|---|---|
| 6 | 4,169 to 4,179 | 11 |
| 7 | 4,180 to 4,188 | 9 |
| 8 | 4,189 to 4,200 | 12 |
Batch 8 starts at offset 4,189 because batch 7 ended at 4,188, so no row falls between batches and no row lands in 2 of them. A socket source fails the second requirement: once a line is read from the connection it is gone, so a failed batch loses its rows, and Spark's documentation marks the source for testing only. The third requirement comes from what inference costs: a batch read that infers a schema makes an extra pass over the files before the real read, and a stream has no finished files to make that pass over.
Built-in sinks
| Sink | What each batch does | Used for |
|---|---|---|
| Files (parquet, json, csv) | Adds new files to an output directory | Production tables |
| Message log | Appends messages to a topic | Feeding other streams and services |
| console | Prints the batch's rows on the driver | Debugging |
| memory | Adds the rows to a table held in driver memory | Debugging |
The 2 debugging sinks carry a warning you have heard before. console and memory both bring every output row to the driver, which is the collect() trap on a timer. They suit 20 rows on a laptop and nothing larger.
A team lands a new JSON file of ride events in a storage directory every minute and wants the cleaned rows kept as a table that analysts query. Which pair of ends fits?
| Part | Batch | Streaming |
|---|---|---|
| Read | spark.read | spark.readStream |
| Schema | Optional, can be inferred | Required for a file source |
| Transformations | where, select | The same lines, unchanged |
| Write | requested.write | requested.writeStream |
| What starts the work | An action such as a write | start() |
| What the call returns | Nothing, after the job ends | A query handle, at once |
| When it ends | When the files are read | When it is stopped or fails |
start() is the action
Lazy evaluation still holds. Calls like readStream and where build a plan and run nothing, and so does select. start() plays the role an action plays in batch code: it hands the plan to the driver, which begins the micro-batch loop. The difference is that start() returns immediately with a handle while the loop keeps running in the background.
That handle, query above, is how you talk to a running stream. query.status reports what the loop is doing now. query.lastProgress describes the most recent batch; it includes the batch number and how many rows that batch read. query.stop() ends the loop. query.awaitTermination() blocks the calling program until the stream stops, and a script needs it as its last line: without it the script reaches its end and the application exits, taking the stream with it.
One line in the write has no batch counterpart. A file sink requires a checkpointLocation, a directory where the query keeps notes on its own progress, and Spark refuses to start without one. Treat it as a required line for now; what goes into that directory is the subject of a later lesson.
Batch actions fail on a streaming DataFrame
rides in the streaming version is still a DataFrame, and rides.isStreaming returns True. The usual actions don't apply to it. Calling rides.count() or rides.show() raises an AnalysisException saying that queries with streaming sources must be executed with writeStream.start(), and so does rides.collect(). The reason follows from the growing-table model: count() promises one final number, and a table with no last row has none to give.
The middle runs anywhere
Because the transformations are identical, you can write and test them as a batch job over a table that has stopped growing. Swapping the ends comes after. The cell below runs a filter-and-select middle against the practice orders table, where 'Completed' plays the part of 'requested'.
completed = (
orders
.where("status = 'Completed'")
.select("order_id", "status")
)
completed.show()Run it, then read the where and select lines again and ask what would change if orders came from spark.readStream. Neither line would need an edit, because the same filter would apply to each micro-batch's new rows. The only edit is replacing show() with a writeStream that ends in start().
To watch a real stream on a laptop, pair the 2 testing ends from the previous section. The rate source invents 5 rows a second, and the console sink prints each batch with its number.
What happens when the second line of this program runs?
The translation, then, is short. On the read side read becomes readStream and a file source needs its schema declared. On the write side write becomes writeStream, with start() in place of the action. One choice is still open. Nothing in the code above says how often a batch should run.
The micro-batch loop leaves one setting to you: when the next batch starts. That setting is the trigger, and you declare it on the writer with .trigger(...) before start(). It decides the trade between how fresh the output is and what the stream costs to run. There are 3 choices to know at this stage.
Default: back to back
Fixed interval: processingTime
With processingTime, the driver starts a batch on a clock: one every 10 seconds here. Rows that arrive between ticks wait for the next one. A tick that finds no new rows runs no batch. Compared with the default, each batch holds more rows, so the fixed per-batch overhead is spread over more work and the file sink writes fewer, larger files.
Available-now: catch up and stop
Swap the trigger line for .trigger(availableNow=True), available from Spark 3.3, and the query changes character. It reads everything that has piled up at the source since its last run, processes it in one or more batches, and stops by itself. Launched by a scheduler every hour, it behaves like an hourly batch job that remembers where it left off, so each run reads only the new rows. Between runs the application has ended and its executors are released.
Latency against cost
| Trigger | A batch starts | Worst-case wait for a row | Cluster |
|---|---|---|---|
| Default | When the last one ends | About 2 batch durations | Always on, busy |
| processingTime, 1 minute | Every 60 seconds | 1 minute plus one batch duration | Always on, mostly idle |
| availableNow, hourly | When the scheduler launches it | 1 hour plus the run | On only during the run |
Choosing, and checking the choice
Start from the question the output answers. If someone acts on it within seconds, as a pricing system does, the default trigger fits, and so does an interval of a few seconds. If a dashboard refreshes every few minutes, a 1-minute processingTime loses nothing a viewer could see. If the output feeds a daily or hourly report, schedule available-now runs and stop paying for a cluster that waits.
A stream uses .trigger(processingTime="10 seconds"). One batch starts at 09:00:00 and its job takes 14 seconds. When does the next batch start?
> A ride-hailing marketplace wants 2 outputs from one stream of ride events: a per-zone count of open requests that pricing reads within seconds, and a Parquet table of requested rides that finance reads each morning.
groupBy, so every micro-batch shuffles on zone. If it slows down, that batch's job in the Jobs tab shows which stage is slow.readStream with a declared schema, and writeStream ending in start().groupBy means a shuffle in every batch, and a slow stream is debugged in the Jobs tab like any slow job.read becomes readStream and write becomes writeStream. In place of the action you call start(), and the transformations in between stay the same.A stream is a table that keeps growing. Spark answers it with one small batch job after another.
- 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)
Every Spark job you have run so far read data that was already finished. The files sat in storage, the job read all of them, an action returned an answer, and the job ended. Ride requests work differently: a new one arrives every few milliseconds, and there is no moment when the data is complete. Stream processing means computing over data while it's still arriving. Spark's version is called Structured Streaming, and it rests on one idea that lets you reuse everything you know about DataFrames:
- Micro-Batches (concepts: Structured Streaming)
A Spark job has a beginning and an end: read partitions, run tasks, return a result. A stream has no end, so one job can never cover it. Spark closes the gap by cutting the stream into slices and running one small job per slice. Each slice is called a micro-batch. The loop the driver runs Once a streaming query starts, the driver repeats the same 4 steps for as long as the query lives. Batch 7, up close Batches are numbered from 0. Here are 3 consecutive batches from the ride stream on a busy ev
- Sources and Sinks (concepts: Structured Streaming)
A streaming query has 2 ends. The source is where each micro-batch gets its new rows. The sink is where each batch's output lands. Choosing them is the first decision in any streaming design, because each end has to support the batch loop, and some systems cannot. Built-in sources A message log is a service that stores events in arrival order and lets many readers fetch them later. Events are grouped into named topics, each topic is split into partitions, and every message in a partition gets a
- readStream and writeStream (concepts: Structured Streaming)
Take a batch job you could write today. It reads the JSON files in a landing directory, keeps the requested rides, and writes them out as Parquet. The streaming version keeps the middle line untouched and changes the 2 ends. start() is the action Batch actions fail on a streaming DataFrame The middle runs anywhere
- Triggers (concepts: Structured Streaming)
Default: back to back Declare no trigger and the driver starts the next batch the moment the previous one finishes. If no new rows have arrived, it waits before checking again. This is the lowest latency micro-batching offers, near 100 milliseconds at best according to Spark's documentation, and it keeps executors busy whenever data is flowing. Fixed interval: processingTime Latency under a fixed interval has a worst case you can compute. A ride that arrives right after a batch begins waits one