BeginnerSpark · 13 min · 13 challenges

Structured Streaming: Beginner

At 11:58 pm on New Year's Eve, ride requests flood Uber's app from San Francisco's SoMa district. Surge pricing for each zone is only as good as the request counts behind it: a count that lands 10 minutes late prices a crowd that has already gone home. Here is how Spark keeps that count current, one small batch at a time, and what makes it fast or cheap.

A Stream Is a Growing Table

Daily Life
Interviews
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 forever. You write an ordinary DataFrame query against that table, and Spark keeps the query standing. Each time rows are appended, Spark updates the query's answer, and the promise is exact: the answer matches what the batch query would return if you ran it over every row received so far.

The input table and the result table

Two tables are in play. The input table holds every event the stream has delivered, a row per event, and it only grows at the bottom. The result table holds the query's answer over the input table. Here is a query that counts requests per zone, followed through 30 seconds of New Year's Eve in San Francisco:
ClockRows appendedInput tableResult table
23:58:00ride 1 (SoMa), ride 2 (Mission), ride 3 (SoMa)3 rowsSoMa 2, Mission 1
23:58:10ride 4 (SoMa), ride 5 (Marina)5 rowsSoMa 3, Mission 1, Marina 1
23:58:20ride 6 (Mission)6 rowsSoMa 3, Mission 2, Marina 1
23:58:30none6 rowsSoMa 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

Rerunning the batch query over the whole input table on every update would keep the contract and fail on cost. By morning that table holds every request since the stream started, and each rerun would read more than the one before. Spark reads only the rows appended since its previous update and folds them into the answer it already holds. At 23:58:20 the only new row was ride 6, so Spark added 1 to Mission's count. Where Spark keeps that running answer between updates is the subject of a later lesson. For now, treat the input table as a model for reasoning about the query: Spark never stores it whole.
✓Batch query
  • 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
✗Streaming query
  • 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
Multiple Choice

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

Between updates, the result table describes the past. Ride 5 is in the stream from the moment its phone sends it, but Marina has no row in the result until the update that reads it. That gap, from an event arriving to the result including it, is the stream's latency, and the rest of this lesson is about what sets it.
TIP
To test a standing query, save a copy of its input, run the same transformations with 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()

Micro-Batches

Daily Life
Interviews
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

What the driver does for each micro-batch
  • ▸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.
Fixing the range before reading turns an endless stream into a bounded input. From the executors' side, batch 7 is a small table with a known set of rows, and they handle it like any other job's input. Where the driver keeps those ranges, and how it uses them after a crash, comes in a later lesson.

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()
)
batch_79 rows
ride_id
zone
status
701
SoMa
requested
702
Mission
requested
703
SoMa
requested
704
Marina
cancelled
705
SoMa
requested
706
Mission
cancelled
707
Marina
requested
708
SoMa
requested
709
Mission
requested
Preparing the animation
Of batch 7's 7 requests, 4 come from SoMa and 2 from Mission, with Marina's 1 making up the rest. The 2 cancelled rides are dropped in the read tasks before anything crosses the network. Spark then adds those 3 counts to the totals carried over from batches 0 to 6. The job's shape does not depend on the batch's size: with 9 rows or 9 million, it runs as 2 stages with a shuffle between them.

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.

100 ms
lowest latency the Spark docs cite
Those fixed costs put a floor under latency. No micro-batch can deliver a row faster than a job's own overhead from planning to commit, so micro-batching suits answers needed within seconds or minutes and fits poorly where a decision must land within a few milliseconds.

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:

{
"batchId": 7,
"numInputRows": 9,
"inputRowsPerSecond": 0.9,
"processedRowsPerSecond": 2.25,
"durationMs": {
"triggerExecution": 4000
}
}
Set the 2 rates side by side: rows arrived at 0.9 a second and were processed at 2.25 a second, so batch 7 ran at 2.5 times the speed it needed. The Structured Streaming tab of the Spark UI charts the same 2 rates for every batch, beside batch duration. A process rate that stays under the input rate for minutes on end means the stream is losing ground, and the fix starts at the slowest stage inside each batch's job, found the way the Spark UI lesson showed.
Multiple Choice

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?

Sources and Sinks

Daily Life
Interviews
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.
Sources
Engine
Sinks
JSON files
Landing folder
numbered offsets
Message log
Spark micro-batches
Standing query
PARTITIONS200
file sink
Parquet folder
foreachBatch writer
Surge dashboard

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

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 file in the folder missing from that list is new. A message log answers with an offset per partition. Batch 7 might cover offsets 1,200 through 1,204 in partition 0 and 830 through 833 in partition 1, 9 messages in all, and batch 8 then starts at 1,205 and 834.

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.

SourceFormat nameHow it tells what is newUse
Files in a folderjson, csv, parquet, orc, textRemembers every file it has readData landed by other jobs
Message logset by the log's connectorTracks an offset per log partitionEvents from apps and services
RaterateCounts the rows it has generatedLoad tests: rows of timestamp and value at rowsPerSecond
SocketsocketNumbers lines in memory only; cannot replay them after a restartDemos 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.

SinkFormat nameWhat it does with a batchUse
Fileparquet, json, csv, orc, textAdds new files and never rewrites old onesTables that later jobs read
Message logset by the log's connectorPublishes each output row as a messageFeeding other services
foreachBatcha function you writeCalls it with the batch as a DataFrame and its idAny destination a batch writer reaches
ConsoleconsolePrints the batch's rows on the driverDebugging
MemorymemoryKeeps all output as a table in driver memoryDebugging 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.

def write_batch(batch_df, batch_id):
(
batch_df
.write
.mode("append")
.parquet("/lake/surge_inputs")
)
query = (
requests
.writeStream
.foreachBatch(write_batch)
.option("checkpointLocation", "/chk/surge_inputs")
.start()
)
TIP
Point a new query at .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.
Multiple Choice

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?

readStream and writeStream

Daily Life
Interviews
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:
requests = (
spark.read
.json("/landing/ride_requests")
)
requested = (
requests
.where("status = 'requested'")
.select("ride_id", "zone", "requested_at")
)
(
requested
.write
.mode("append")
.parquet("/lake/requested_rides")
)
The same job as a stream reads every file that lands in the folder from now on:
requests = (
spark.readStream
.schema("ride_id BIGINT, zone STRING, status STRING, requested_at TIMESTAMP")
.json("/landing/ride_requests")
)
requested = (
requests
.where("status = 'requested'")
.select("ride_id", "zone", "requested_at")
)
query = (
requested
.writeStream
.format("parquet")
.option("path", "/lake/requested_rides")
.option("checkpointLocation", "/chk/requested_rides")
.start()
)

What changed, line by line

PartBatchStreamWhy
Read`spark.read``spark.readStream`Returns a streaming DataFrame
SchemaInferred by scanning the filesStated with `.schema(...)`Every batch must yield the same columns
Transformations`where`, `select`UnchangedSame DataFrame API, planned per batch
Write`write` ... `parquet()``writeStream` ... `start()`Launches a query that runs until stopped
Progress folderNone`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:

query.status
query.lastProgress
query.awaitTermination()
query.stop()

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.

Multiple Choice

A teammate tests a new stream with the program below. What happens when it runs?

events = (
spark.readStream
.schema("event_id BIGINT, user_id BIGINT, event_name STRING")
.json("/landing/app_events")
)
purchases = events.where("event_name = 'purchase'")
print(purchases.count())

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()

Triggers

Daily Life
Interviews

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:

TriggerCodeWhen the next batch startsWhen the query stops
Defaultno `.trigger` callAs soon as the previous batch ends, if new data existsWhen you stop it
Fixed interval`.trigger(processingTime="10 seconds")`At the next 10-second boundary, if new data existsWhen you stop it
Available now`.trigger(availableNow=True)`Right away, batch after batch, until the data present at start is doneOnce that data is processed
Once`.trigger(once=True)`Right away, as a single batch holding all data present at startAfter 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.

BatchPlanned startActual startDurationWhat follows
723:59:0023:59:004 sExecutors idle 6 s until 23:59:10
823:59:1023:59:1014 sBatch 9 starts at 23:59:24, no wait
923:59:2023:59:245 sExecutors idle 1 s until 23:59:30
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.
Multiple Choice

A stream runs with .trigger(processingTime="10 seconds"), and every batch now takes 25 seconds. When do its batches start?

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 10 seconds with 4-second batches, that is up to 14 seconds from a phone's request to the zone count. Cost follows the cluster: the default trigger and a fixed interval both keep executors allocated around the clock, because the query never stops between batches, so you pay for them even while they sit idle.
8,640
micro-batches a day at 10 seconds
1,440
micro-batches a day at 1 minute
Every micro-batch that writes to the file sink adds a new file for every task that produced output, so the interval sets how fast the folder fills. That is the small-files problem from the partitioning lesson, produced on a timer, and every job that reads the folder later pays to open them.

Matching the trigger to the need

NeedTriggerWhy
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 allowDefaultEach batch starts the moment the last one ends
Finance table refreshed each morning`availableNow=True`, started by a schedulerThe 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.

Multiple Choice

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?

❯❯❯PUTTING IT ALL TOGETHER

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

The landing folder is the source: the stream states its schema, and the file list tells each micro-batch which requests are new.
Each 10-second batch is a small job with a shuffle for the zone count, and its 200 reduce tasks are the first thing to check in the Spark UI when batches overrun.
The dashboard sink is a foreachBatch function, because the dashboard's database has no built-in sink.
The finance copy runs at 06:00 with availableNow, so its executors are paid for only while it catches up, and it writes fewer, larger files than a 10-second stream would.
KEY TAKEAWAYS
A streaming query is a standing query over an input table that only grows, and its result matches the batch query over every row so far.
Spark runs it as a loop of micro-batches: the driver fixes each batch's range, then runs an ordinary job over only the rows in that range.
Each micro-batch pays a job's fixed costs, including spark.sql.shuffle.partitions reduce tasks after a shuffle, with Adaptive Query Execution switched off.
A source must say what is new and supply a schema up front; a sink must accept batch after batch and confirm each write.
readStream and writeStream ... start() replace the batch ends, the transformations between them stay the same, and actions are refused.
The trigger sets freshness and cost: the default and fixed intervals keep executors running, while 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

  1. 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

  2. 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

  3. 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

  4. 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

  5. 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