AlgoViz

Apache Spark Streaming

medium 28 min

Spark 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

0:00 / 4:05

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

  1. 2009 to 2010

    Spark starts as research at the UC Berkeley AMPLab and is open sourced in early 2010.

  2. February 2013

    Spark 0.7.0 is tagged, with the first alpha of Spark Streaming (DStreams).

  3. November 2013

    The paper "Discretized Streams" at SOSP explains streams as a series of small deterministic batches.

  4. July 2016

    Spark 2.0.0 is tagged and brings the first, experimental Structured Streaming.

  5. 2017

    Spark 2.2.0 declares the Structured Streaming APIs generally available.

  6. December 2025

    Spark 4.1.0 introduces Real-time Mode for stateless queries.

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

Step 1 of 3

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.

One bus, one plan
Plan: Done: bus 6Stop123Bus 7Whoever waits gets on

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?

NameStatus in Spark 4.3Unit of workUse it
Structured Streaming, micro-batchCurrent, the defaultDataFrame batchMost pipelines
Structured Streaming, Real-time ModeCurrent, since 4.1Long batch, row by rowMilliseconds, supported queries
Continuous ProcessingExperimental, since 2.3Row by row, map onlyNo. Use Real-time Mode
Spark Streaming (DStreams)Legacy, no updatesRDD per intervalOnly existing jobs
Continuous Processing gives at-least-once only. Spark is licensed under the Apache License 2.0.
  • 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 driver inside the Spark application learns new offsets from Kafka, writes plan and commit to object storage and sends tasks to an executor. Two executors read rows from Kafka and write to a sink. An executor writes state to object storage.
Tasks and state are drawn for one executor. Every executor gets tasks and stores its part of the state.

The parts

PartJobIf it dies
DriverPlans batches, keeps the watermark, commitsThe query stops until the application restarts
ExecutorRuns tasks, holds state partitionsTasks run on others, state is loaded from the checkpoint
Checkpoint locationOffsets, commits, stateLost checkpoint: the query starts as a new one
SourceKeeps rows that can be read againThe query waits or fails
SinkReceives each batchThe batch fails and is retried
Use a cluster manager such as Kubernetes to restart the driver. Put the checkpoint on object storage or HDFS, one location per query.

The key idea

One micro-batch, step by step

Plan, run, commit

Offsets live in the checkpoint. Spark does not rely on the committed offsets of a Kafka consumer group.

What a restart does

At most one batch is open in the default mode, so at most one batch is repeated.

How late is a result?

average≈I2+Pworst≈I+P\text{average} \approx \frac{I}{2} + P \qquad \text{worst} \approx I + P
II is the trigger interval and PP the time to process a batch, with PP below II. With I=10I = 10 s and P=6P = 6 s a row waits 11 s on average and 16 s at most.

Is the query fast enough, and how fast does it catch up?

P=rIc=30,000×1050,000=6 sT=r tc−r=30,000×60020,000=900 sP = \frac{r I}{c} = \frac{30{,}000 \times 10}{50{,}000} = 6\,\text{s} \qquad T = \frac{r\, t}{c - r} = \frac{30{,}000 \times 600}{20{,}000} = 900\,\text{s}
rr rows per second arrive, cc rows per second is the capacity. After 10 minutes of downtime this query needs 15 minutes to catch up. Design for the peak, three times the average.

Triggers

When the next batch starts

TriggerBehaviourGood for
None given (default)Next batch as soon as the last one endsLowest micro-batch delay
Fixed intervalEvery n seconds. A late batch is followed at onceFewer, larger writes
Available nowEverything that is there, in one or more batches, then stopScheduled, cheap pipelines
Once (deprecated)One big batch, then stopNothing new
Real timeLong running tasks, checkpoint each intervalMillisecond results
A fixed interval starts no batch when there is no new data. In Kafka, maxOffsetsPerTrigger limits the rows of one batch. It has no default.

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

ProviderState lives inChoose it when
HDFS-backed (default in micro-batch)A map in the executor's JVM memory, files in the checkpointState is small
RocksDB (built in since 3.2)Native memory and local disk, saved to the checkpointMillions of keys, long garbage collection pauses
Changelog checkpointing for RocksDB uploads the changes instead of snapshots. It is off by default in micro-batch. RocksDB is an LSM tree.

The watermark

Wn+1=max⁡rows up to batch n(tevent)−dW_{n+1} = \max_{\text{rows up to batch } n} (t_{\text{event}}) - d
dd is the delay in withWatermark. It is computed at the end of a batch and used from the next one. A window is final when the watermark passes its end.

A row meets a window

The guarantee is one-sided. Rows within the delay are always counted. Later rows may or may not be.

Output modes

ModeWritesWith a windowed count
Append (default)Rows that will never changeEach window once, after the watermark
UpdateRows changed in this batchA new value each time, so upsert
CompleteThe whole resultEverything each time. State is never dropped

Joins need limits too

  1. 1

    Stream with a static table

    No state for the join. The table should fit a broadcast for speed.

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

    Stream with stream, outer

    Watermarks and a time condition are required, because Spark must know when no match can come any more.

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

The batch id is the same when a batch is repeated. That is what makes it a deduplication key. See idempotency.

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

    It bounds the replay

    After a failure the query goes back to the last committed offsets and may write rows again.

  3. 3

    It also delays batch-scoped work

    The watermark advances only between batches, so state for closed windows is removed later.

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

QuestionDStreamsStructured Streaming
Entry pointStreamingContext with a batch intervalSparkSession, readStream, writeStream
DataRDD per intervalDataFrame, optimized by Catalyst
TimeArrival timeEvent time with watermarks
IntervalFixed for the whole contextA trigger per query, changeable at restart
StateupdateStateByKey, mapWithStateAggregations, transformWithState
Backpressurespark.streaming.backpressure.enabled, off by defaultLimits per trigger
SupportLegacy, no updatesCurrent

A safe move

  1. 1

    Write the query anew

    State and checkpoints cannot be carried over. Treat it as a new job.

  2. 2

    Run both

    Same source, different sinks. Compare results per window.

  3. 3

    Choose a start point

    Give the new query explicit starting offsets that overlap with the old job.

  4. 4

    Switch the readers

    Then stop the old job and delete its checkpoint.

Operations

Running it

Python
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()
The number of shuffle partitions is 200 by default and becomes part of the state. It stays the same for the life of the checkpoint.

What may change at a restart

ChangeAllowed?
Trigger, rate limitsYes
Add or remove a filterYes
Another output topicYes
Subscribed topicsGenerally not
Number or type of sourcesNo
Grouping keys, aggregates, deduplication columns, join typeNo
Shuffle partitions, state store providerNo
For a forbidden change start with a new checkpoint and replay. Plan for that: keep the source long enough.

Red flags

You seeCauseRemedy
Processed rows per second below input rowsNot enough capacityMore cores, fewer partitions with skew, cheaper code
Batch time above the intervalThe same, or a slow sinkBatch the writes, raise the interval
State rows grow for daysNo watermark, or complete modeWatermark, time condition, update mode
Append mode writes nothingThe watermark does not pass the window endWait, shorten the delay, check timestamps
One long task per stageSkewed keySalt the key and merge in a second step
Many tiny filesA short interval with a file sinkA 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 StreamingFlink
Default modelMicro-batchRecord by record
LatencyAbout 100 ms and up, milliseconds in Real-time ModeMilliseconds
Recovery unitRepeat the open batchGo back to a checkpoint
Kafka outputAt-least-onceTransactions possible
Planned upgradesSame checkpoint, limited changesSavepoints
Batch and MLVery strongSmaller ecosystem
The details of the other side are on Apache Flink.

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