BeginnerSpark · 13 min · 13 challenges

Structured Streaming: Beginner

Friday, 11pm in San Francisco. A concert lets out in SoMa and ride requests triple in 4 minutes. Uber's pricing can only react if the count of open requests per zone is seconds old, and a nightly job would report the spike the next morning. This lesson is about the query that never finishes, and how Spark keeps its answer current.

A Stream Is a Growing Table

Daily Life
Interviews
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: treat the stream as a table.

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_idzonestatusarrived_at
101SoMarequested12:00:02
102Missionrequested12:00:05
103SoMacancelled12:00:07
104SoMarequested12:00:09
105Marinarequested12:00:12
106SoMarequested12:00:15
107Missioncancelled12:00:18
At 12:00:10 the table holds rides 101 to 104. At 12:00:20 it holds all 7. Ask how many rows the table has, and the answer depends on when you ask.

A query that stays standing

A batch query is asked once and answered once. A streaming query is defined once and stays in place while the table grows, which is why it is called a standing query. You write it with the same DataFrame operations you already use.
requested_by_zone = (
ride_requests
.filter(F.col("status") == "requested")
.groupBy("zone")
.count()
)
A standing query writes its output to a second table, called the result table, which Spark keeps up to date. The rule that defines it fits in one sentence: at any moment, the result table holds what the same query would return if you ran it as a batch job over every row that has arrived so far.
Result at 12:00:10 (rides 101 to 104)
zonecount
SoMa2
Mission1
Result at 12:00:20 (rides 101 to 107)
zonecount
SoMa3
Mission1
Marina1
Check the right-hand table against the 7 input rows. Rides 103 and 107 are cancelled, so the filter drops them. That leaves 3 requested rides in SoMa, plus 1 each in Mission and Marina. Between 12:00:10 and 12:00:20 nobody reran anything, and the result still took in rides 105 to 107 as they arrived.
✓Batch query
  • Input is a finished table
  • Runs when you call an action
  • Returns one answer, then ends
  • A rerun reads every row again
✗Standing query
  • 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.

The model also gives you a self-check. When a streaming result puzzles you, freeze the input at one instant, run the query as a batch job over those rows in your head, and compare. The result table at that instant has to match.
Multiple Choice

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?

Hold on to the 2 tables. The input table grows by appends, the result table follows it, and the query between them is ordinary DataFrame code. What remains is how Spark keeps the result current without rereading rides 101 to 107 every time ride 108 shows up.

Micro-Batches

Daily Life
Interviews
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.
driver
Ask the source what is new
driver
Fix the batch's row range
executors
Run one batch job
sink
Write the output

One pass through these 4 steps is one micro-batch. After the write, the driver goes back to step 1.

What each step does
  • 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

Batches are numbered from 0. Here are 3 consecutive batches from the ride stream on a busy evening, with a batch starting every 10 seconds.
BatchRows it coversStarts atJob runs for
611 new rows23:01:002 s
79 new rows, rides 701 to 70923:01:102 s
812 new rows23:01:203 s
Batch 7 reads 9 rows and nothing else. The rows that batches 0 to 6 covered are already accounted for, and no later batch reads them again. A batch's size is set by how many rows arrived since the last one, and the age of the stream has no effect on it.

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_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
For batch 7's own rows the job returns SoMa 4 and Mission 2, with Marina at 1. A standing count has to cover the whole table, so Spark carries each zone's total forward from batch to batch and adds the new counts to it. If SoMa stood at 31 after batch 6, it stands at 35 after batch 7, which is what a batch query over every row so far would return. How Spark stores those carried totals is a later lesson's subject.
Multiple Choice

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.

Loading the challenge
So a streaming query is a loop: find the new rows, fix the range, run a job, write the result. The driver asks one end of that loop for new rows and the job writes to the other. Each end has its own name and its own requirements.

Sources and Sinks

Daily Life
Interviews
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.
Source
Query
Sink
Readers
message log topic
Ride request events
Spark
Requested-rides query
micro-batches
Parquet files
requested rides
reads the files
Zone demand dashboard

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.

SourceA new row isPosition Spark tracksUsed for
Files in a directory (parquet, json, csv, text)A row in a file that appeared since the last batchWhich files it has already readProduction
Message logA message appended to a topicAn offset per topic partitionProduction
rateA generated row with a timestamp and a counter valueThe counterTesting
socketA line of text from a network connectionNone that can be rereadTesting only
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 sequence number called an offset. It was built to hold a stream of events and hand out any range of them on request.

What a source must provide

3 requirements
  • 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.
BatchOffsets it coversRows
64,169 to 4,17911
74,180 to 4,1889
84,189 to 4,20012

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

SinkWhat each batch doesUsed for
Files (parquet, json, csv)Adds new files to an output directoryProduction tables
Message logAppends messages to a topicFeeding other streams and services
consolePrints the batch's rows on the driverDebugging
memoryAdds the rows to a table held in driver memoryDebugging
What a sink must provide mirrors the source: it has to accept output again and again, batch after batch, adding to what is already there. A file sink does this by writing new files for each batch and leaving earlier files alone. A sink that can only replace its whole contents on every write doesn't fit the loop.

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.

The file sink and small files
A file sink writes one file for each partition that holds rows, in every batch. Batches are small by design, so the files are small too. A stream that writes 4 files every 10 seconds leaves 34,560 files behind in a day, which is the small-files problem arriving on a schedule. The section on triggers returns to this.
Multiple Choice

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?

Both production ends are places you already read and write in batch jobs: directories of files, and tables built from them. A stream uses the same storage. What differs is how the read and the write are declared, which comes down to 2 method names and a few options.

readStream and writeStream

Daily Life
Interviews
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.
ride_schema = "ride_id LONG, zone STRING, status STRING"
rides = spark.read.schema(ride_schema).json("/landing/rides/")
requested = rides.where("status = 'requested'").select("ride_id", "zone")
requested.write.parquet("/tables/requested_rides/")
The streaming version keeps the middle line untouched and changes the 2 ends.
rides = spark.readStream.schema(ride_schema).json("/landing/rides/")
requested = rides.where("status = 'requested'").select("ride_id", "zone")
query = (
requested.writeStream
.format("parquet")
.option("path", "/tables/requested_rides/")
.option("checkpointLocation", "/progress/requested_rides/")
.start()
)
PartBatchStreaming
Readspark.readspark.readStream
SchemaOptional, can be inferredRequired for a file source
Transformationswhere, selectThe same lines, unchanged
Writerequested.writerequested.writeStream
What starts the workAn action such as a writestart()
What the call returnsNothing, after the job endsA query handle, at once
When it endsWhen the files are readWhen 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.

ticks = spark.readStream.format("rate").option("rowsPerSecond", 5).load()
query = ticks.writeStream.format("console").start()
query.awaitTermination()
Multiple Choice

What happens when the second line of this program runs?

rides = spark.readStream.schema(ride_schema).json("/landing/rides/")
n = rides.where("status = 'requested'").count()

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.

Triggers

Daily Life
Interviews

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

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

query = (
requested.writeStream
.format("console")
.trigger(processingTime="10 seconds")
.start()
)

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.

Latency under a fixed interval has a worst case you can compute. A ride that arrives right after a batch begins waits one full interval for the next batch, then for that batch's job. With a 10-second interval and 3-second jobs, the worst case is 13 seconds. Under the default trigger with the same jobs it is about 6: up to 3 seconds for the running batch to finish, then 3 for its own.
The interval is a request, and a slow job can break it. If a batch takes 14 seconds against a 10-second interval, the driver starts the next batch as soon as the slow one finishes. The 2 never overlap. A stream in that state runs back to back whatever the trigger says.

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

TriggerA batch startsWorst-case wait for a rowCluster
DefaultWhen the last one endsAbout 2 batch durationsAlways on, busy
processingTime, 1 minuteEvery 60 seconds1 minute plus one batch durationAlways on, mostly idle
availableNow, hourlyWhen the scheduler launches it1 hour plus the runOn only during the run
The cluster column is where the money is. With a fixed number of executors, the usual setup for a stream, the application holds them from start to stop, so a stream on a 1-minute trigger holds its executors for all 60 seconds even when a batch is busy for only 5 of them. A longer interval saves files and overhead, and the idle executors still cost the same. Only available-now releases them, and it pays with latency measured in the gap between runs.
File counts move with the trigger too. Suppose every batch writes 4 files. Back-to-back 3-second batches make 28,800 batches a day, a 1-minute interval makes 1,440, and an hourly available-now run, at one batch per run, makes 24.
115,200
files a day, back-to-back batches
5,760
files a day, 1-minute interval
96
files a day, hourly runs

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.

Then verify in the Spark UI. A running stream adds a Structured Streaming tab that charts input rate against processing rate, along with each batch's duration. Durations well under your interval mean the trigger is doing what you asked. Durations at or above it mean the stream is running back to back, and the fix lies in the batch job: open the slow batch in the Jobs tab and find its slow stage.
Multiple Choice

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?

Whatever the trigger, the query computes the same answer: the result table at any instant is the batch answer over the rows so far. The trigger decides how often Spark catches the result up, and what you pay for that.
PUTTING IT ALL TOGETHER

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

Both outputs start from the same growing table of ride events, and each is a standing query whose result must match a batch run over the rows so far.
The pricing count has a 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.
The events come from a message log that can return any range again by offset, and the finance table goes to a file sink that adds Parquet files each batch.
The code for each query differs from its batch form only at the ends: readStream with a declared schema, and writeStream ending in start().
Pricing runs on the default trigger for seconds of latency and keeps a cluster busy. Finance runs available-now before the morning report, writes a few large files and releases its executors.
KEY TAKEAWAYS
A stream is an input table that only gains rows, and a streaming query is a standing query whose result table always matches the batch answer over the rows so far.
Spark computes it in micro-batches: the driver finds the new rows, fixes their range, runs one ordinary job and writes the output, then repeats.
Each micro-batch is a normal job, so a groupBy means a shuffle in every batch, and a slow stream is debugged in the Jobs tab like any slow job.
A source must give positions, a second read of any range and a schema up front. A sink must accept output batch after batch.
read becomes readStream and write becomes writeStream. In place of the action you call start(), and the transformations in between stay the same.
The trigger sets when batches start: back to back for seconds of latency, a fixed interval for fewer and larger batches, available-now for scheduled runs that release the cluster.

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

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

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

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

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

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