Apache Spark Streaming
medium 28 minSpark treats a stream as a table that keeps growing and runs your query again and again on the new rows, in small batches.
Video lesson · Chapter 1 of 5
A continuously updated result from bounded batches
Micro-batches in 75 seconds
1:15Reel coming soon
Theory
Read or listen first. About 2 min.
What it is
Structured Streaming is the stream engine inside Apache Spark. You write the same DataFrame or SQL query you would write for a file. Spark runs it incrementally: every few moments it takes the rows that have arrived, computes what changes, and updates the result.
Each of these runs is a micro-batch, a small ordinary Spark job. The documentation gives about 100 milliseconds as the best latency of that mode. Real-time Mode, added in Spark 4.1, keeps tasks running and reaches milliseconds for the queries it supports.
The name Spark Streaming also means an older library, DStreams. The project calls it the previous generation, says it gets no updates, and asks you to use Structured Streaming. This page teaches the current engine and enough of the old one to recognise and replace it.
Why it exists
Many teams already have batch jobs in Spark. With one engine for both, the daily job and the live job can share functions, schemas, SQL and people. That avoids the double code of a lambda architecture.
Batches are also a simple way to recover. If the plan of a batch is written down before it runs, a crash means: run the same batch again. That works well when the source can be read again and the sink does not mind a repeat.
Windows, event time and delivery guarantees in general belong to stream processing, and the choice of batch or stream to batch versus stream. This page is about the product.
A short history
2009 to 2010
Spark starts as research at the UC Berkeley AMPLab and is open sourced in early 2010.
February 2013
Spark 0.7.0 is tagged, with the first alpha of Spark Streaming (DStreams).
November 2013
The paper "Discretized Streams" at SOSP explains streams as a series of small deterministic batches.
July 2016
Spark 2.0.0 is tagged and brings the first, experimental Structured Streaming.
2017
Spark 2.2.0 declares the Structured Streaming APIs generally available.
December 2025
Spark 4.1.0 introduces Real-time Mode for stateless queries.
October 2026
Spark 4.3.0 adds deduplication, aggregation and transformWithState on the JVM to Real-time Mode.
Words to know
- Micro-batch
- One small job over the rows that arrived since the last one.
- Trigger
- The rule that says when the next batch starts.
- Checkpoint location
- A durable folder with the planned offsets, the finished batches and the state of a query.
- Output mode
- Append, update or complete: which rows of the result are written each time.
- Watermark
- The newest event time seen minus a delay you choose. It decides when old state may go.
- State store
- A versioned key-value store on the executors, for example for counts and joins.
- DStream
- The legacy abstraction: a series of RDDs, one per batch interval.
How it works
Step through the idea, or press Play.
Plan. The driver writes the offsets of the next batch
Understand it
Start here
The bus that leaves every few seconds
Imagine a bus stop where a bus leaves every few seconds with whoever is waiting. Before a bus goes, the person at the stop writes a plan on the board: which bus, which riders. When it has arrived, the board says done. If a bus breaks down, the plan is still there, so another bus makes the same trip with the same riders.
The plan makes the trip repeatable. Whether riders are greeted twice at the other end depends on the sink.
Names
Which Spark streaming do you mean?
| Name | Status in Spark 4.3 | Unit of work | Use it |
|---|---|---|---|
| Structured Streaming, micro-batch | Current, the default | DataFrame batch | Most pipelines |
| Structured Streaming, Real-time Mode | Current, since 4.1 | Long batch, row by row | Milliseconds, supported queries |
| Continuous Processing | Experimental, since 2.3 | Row by row, map only | No. Use Real-time Mode |
| Spark Streaming (DStreams) | Legacy, no updates | RDD per interval | Only existing jobs |
One API
The same DataFrame or SQL query on a table and on a stream.
Planned batches
Each batch has written offsets, so it can be repeated exactly.
Event time
Windows by the time in the event, with watermarks for late rows.
Joins
Stream with table, and stream with stream inside a time range.
High throughput
Batches use the same optimizer and columnar formats as normal Spark.
Run and stop
The available-now trigger processes what is there and ends. Good for cheap hourly jobs.
Architecture
Driver, executors and a checkpoint
One streaming query
The parts
| Part | Job | If it dies |
|---|---|---|
| Driver | Plans batches, keeps the watermark, commits | The query stops until the application restarts |
| Executor | Runs tasks, holds state partitions | Tasks run on others, state is loaded from the checkpoint |
| Checkpoint location | Offsets, commits, state | Lost checkpoint: the query starts as a new one |
| Source | Keeps rows that can be read again | The query waits or fails |
| Sink | Receives each batch | The batch fails and is retried |
The key idea
One micro-batch, step by step
Plan, run, commit
What a restart does
How late is a result?
Is the query fast enough, and how fast does it catch up?
Triggers
When the next batch starts
| Trigger | Behaviour | Good for |
|---|---|---|
| None given (default) | Next batch as soon as the last one ends | Lowest micro-batch delay |
| Fixed interval | Every n seconds. A late batch is followed at once | Fewer, larger writes |
| Available now | Everything that is there, in one or more batches, then stop | Scheduled, cheap pipelines |
| Once (deprecated) | One big batch, then stop | Nothing new |
| Real time | Long running tasks, checkpoint each interval | Millisecond results |
State
State store, windows and watermarks
Counts, joins and deduplication need memory between batches. It lives in a state store on the executors, split by the hash of the key, and each batch makes a new version in the checkpoint.
State store providers
| Provider | State lives in | Choose it when |
|---|---|---|
| HDFS-backed (default in micro-batch) | A map in the executor's JVM memory, files in the checkpoint | State is small |
| RocksDB (built in since 3.2) | Native memory and local disk, saved to the checkpoint | Millions of keys, long garbage collection pauses |
The watermark
A row meets a window
Output modes
| Mode | Writes | With a windowed count |
|---|---|---|
| Append (default) | Rows that will never change | Each window once, after the watermark |
| Update | Rows changed in this batch | A new value each time, so upsert |
| Complete | The whole result | Everything each time. State is never dropped |
Joins need limits too
- 1
Stream with a static table
No state for the join. The table should fit a broadcast for speed.
- 2
Stream with stream, inner
Both sides are kept in state. Watermarks and a time condition are optional but without them the state only grows.
- 3
Stream with stream, outer
Watermarks and a time condition are required, because Spark must know when no match can come any more.
- 4
Several watermarks
By default the query follows the slowest one, so a quiet stream holds back the others.
Output
Exactly-once, and where it stops
Inside Spark
- Each batch has fixed offsets
- State versions belong to batches
- A repeated batch replaces, it does not add
- So state counts every row once
At the sink
- File sink: exactly-once
- Kafka sink: at-least-once
- foreach: at-least-once
- foreachBatch: as good as the code you write
Make foreachBatch safe
Low latency
Real-time Mode
A micro-batch pays for planning and starting tasks every time. Real-time Mode starts long running tasks once per long batch. Rows flow through them as they arrive, and shuffles stream rows directly from task to task instead of writing files first.
What it gives
- Milliseconds instead of about 100 ms
- The same exactly-once state as micro-batch
- Same query, another trigger
- The documentation prefers it to Continuous Processing
What it limits (Spark 4.3)
- Update mode only
- Kafka as source. Kafka, foreach, console, memory as sinks
- No stream-stream joins, no session windows, no foreachBatch
- No Python transformWithState
Understand its interval
- 1
The trigger time is a checkpoint interval
The default is 5 minutes and the minimum 5 seconds. Results do not wait for it.
- 2
It bounds the replay
After a failure the query goes back to the last committed offsets and may write rows again.
- 3
It also delays batch-scoped work
The watermark advances only between batches, so state for closed windows is removed later.
- 4
State uses RocksDB
Stateful queries get RocksDB, checkpoint format 2 and changelog checkpointing by default. A checkpoint made with format 1 cannot be used.
Legacy
DStreams, and how to leave them
A DStream is a series of RDDs, one per fixed batch interval. You work with processing time and functions instead of columns and event time. The project says there are no longer updates to it.
| Question | DStreams | Structured Streaming |
|---|---|---|
| Entry point | StreamingContext with a batch interval | SparkSession, readStream, writeStream |
| Data | RDD per interval | DataFrame, optimized by Catalyst |
| Time | Arrival time | Event time with watermarks |
| Interval | Fixed for the whole context | A trigger per query, changeable at restart |
| State | updateStateByKey, mapWithState | Aggregations, transformWithState |
| Backpressure | spark.streaming.backpressure.enabled, off by default | Limits per trigger |
| Support | Legacy, no updates | Current |
A safe move
- 1
Write the query anew
State and checkpoints cannot be carried over. Treat it as a new job.
- 2
Run both
Same source, different sinks. Compare results per window.
- 3
Choose a start point
Give the new query explicit starting offsets that overlap with the old job.
- 4
Switch the readers
Then stop the old job and delete its checkpoint.
Operations
Running it
spark.conf.set("spark.sql.shuffle.partitions", "48") # before the first startspark.conf.set( "spark.sql.streaming.stateStore.providerClass", "org.apache.spark.sql.execution.streaming.state.RocksDBStateStoreProvider")query = (counts.writeStream .queryName("orders-5m") .outputMode("update") .foreachBatch(upsert) .option("checkpointLocation", "s3a://bucket/checkpoints/orders-5m") .trigger(processingTime="10 seconds") .start())print(query.lastProgress) # rows, rates, durations, watermark, statequery.awaitTermination()What may change at a restart
| Change | Allowed? |
|---|---|
| Trigger, rate limits | Yes |
| Add or remove a filter | Yes |
| Another output topic | Yes |
| Subscribed topics | Generally not |
| Number or type of sources | No |
| Grouping keys, aggregates, deduplication columns, join type | No |
| Shuffle partitions, state store provider | No |
Red flags
| You see | Cause | Remedy |
|---|---|---|
| Processed rows per second below input rows | Not enough capacity | More cores, fewer partitions with skew, cheaper code |
| Batch time above the interval | The same, or a slow sink | Batch the writes, raise the interval |
| State rows grow for days | No watermark, or complete mode | Watermark, time condition, update mode |
| Append mode writes nothing | The watermark does not pass the window end | Wait, shorten the delay, check timestamps |
| One long task per stage | Skewed key | Salt the key and merge in a second step |
| Many tiny files | A short interval with a file sink | A longer interval and compaction |
Choose
When Spark, and when not
Choose Spark
- Batch jobs already run on it
- Seconds to minutes are fine
- Large scans, joins with big tables, machine learning
- Writes into a data lake in good-sized files
- One code for backfill and live data
Choose something else
- Complex state and timers at low latency: Flink
- Kafka in and out inside one service: Kafka Streams
- Only moving events: a connector
- A few events per second: a plain consumer
- A work queue with retries: SQS or RabbitMQ
Compared with Flink
| Spark Structured Streaming | Flink | |
|---|---|---|
| Default model | Micro-batch | Record by record |
| Latency | About 100 ms and up, milliseconds in Real-time Mode | Milliseconds |
| Recovery unit | Repeat the open batch | Go back to a checkpoint |
| Kafka output | At-least-once | Transactions possible |
| Planned upgrades | Same checkpoint, limited changes | Savepoints |
| Batch and ML | Very strong | Smaller ecosystem |
Summary
The whole topic in one minute.
The driver writes the offsets of the next batch into the checkpoint, executors read exactly those rows, update their state and write, and then the batch is marked finished. After a crash the unfinished batch runs again with the same offsets. State is exactly-once. The output is exactly-once only if the sink is idempotent or transactional.
Watermarks limit state and decide when windows are final. Keep the batch time below the trigger interval, limit the input per batch, and never change the checkpoint or the state schema carelessly. Choose Spark when you already use it and seconds are fine. Choose Real-time Mode for supported queries, and Flink for complex state at low latency.
- Structured Streaming is current. DStreams is legacy.
- Plan offsets, run, commit. An open batch is repeated with the same offsets.
- State is exactly-once. The sink decides about the output.
- The watermark is the newest event time minus a delay, updated between batches.
- Batch time must stay below the trigger interval at peak.
- Real-time Mode gives milliseconds for a limited set of queries.
Sources
- Spark 4.3: Structured Streaming guide
- Spark 4.3: APIs on DataFrames and Datasets
- Spark 4.3: Real-time Mode
- Spark 4.3: Kafka integration
- Spark 4.3: DStreams guide (legacy note)
- Armbrust and others: Structured Streaming (SIGMOD 2018)
- Zaharia and others: Discretized Streams (SOSP 2013)
- Spark 4.1.0 release notes