Structured Streaming basics
Some data never stops arriving: clicks, payments, sensor readings. Structured Streaming lets you process it with the same DataFrame code you already know, by treating the stream as a table that keeps getting new rows. This lesson builds that picture step by step, then shows how Spark makes sure nothing is lost or counted twice.
Step 4 · Structured Streaming · Bronze · First streams, lesson 2 of 5
On this page
Read first: Transformations vs actions · The small file problem (skip if you know them)
In plain words first
Picture a shop's till roll. Every sale adds a line at the bottom, and the roll never ends. At any moment the manager wants the total sales per product. They could re-add the whole roll every time, but that gets slower every day. A smarter manager keeps a running total and, each time they look, adds only the lines printed since last time.
Structured Streaming is that manager. The till roll is your input, a table that keeps growing. Your query is written as if the whole table were there. Spark runs it in small rounds, called micro-batches: each round reads only the new rows, updates the running results, and writes a bookmark so it knows where to continue.
A stream is a table that keeps growing
Every new event is a new row added to an input table that never ends. You write the query on that table with normal DataFrame code. Spark keeps the result up to date: each round it processes only the new rows, and it keeps whatever it needs to remember between rounds (running counts, open time windows), called its state.
# the JSON fields inside each message, as a DDL string order_schema = "order_id STRING, customer STRING, amount DOUBLE, order_ts TIMESTAMP" raw = (spark.readStream # readStream instead of read .format("kafka") .option("kafka.bootstrap.servers", "broker:9092") .option("subscribe", "orders") .option("startingOffsets", "earliest") .load()) orders = (raw .select(F.from_json(F.col("value").cast("string"), order_schema).alias("o")) .select("o.*")) query = (orders.writeStream # writeStream instead of write .format("delta") .outputMode("append") .option("checkpointLocation", "s3://chk/orders/") .trigger(processingTime="1 minute") .toTable("bronze.orders"))
The five parts
| Part | In plain words | Examples | Remember |
|---|---|---|---|
| Sourcesource: Where a stream reads from: a Kafka topic, a folder of files, a Delta table. Learn more → | Where the data comes from | KafkaKafka: A system that stores streams of events in topics, in order within each partition, so many readers can read them, and read them again, at their own pace. Learn more →, files landing in a folder, a Delta table; rate and socket for tests | It must be able to give the same data again after a crash |
| Sinksink: Where a stream writes its results: a Delta table, files, Kafka, or your own code with foreachBatch. Learn more → | Where the results go | Delta or ParquetParquet: A columnar file format: values of each column are stored together, so queries read only the columns they need. Learn more → files, Kafka, your own code with foreachBatch; console and memory for tests | Delta and files never write a batch twice; Kafka can |
| Triggertrigger: The setting that decides when the next micro-batch starts: straight away, on a fixed interval, or once over everything waiting. Learn more → | When the next round starts | processingTime="1 minute", availableNow=True, or straight away (the default) | availableNow processes what is waiting and stops |
| Output modeoutput mode: Which rows a stream writes after each micro-batch: only new final rows (append), rows that changed (update), or the whole result (complete). Learn more → | Which result rows are written after each round | append, update, complete | See below |
| Checkpoint | The bookmark: what was read, and what is remembered | checkpointLocation | One per query, on durable storage, never shared |
Output modes
After each round, the output mode says which rows of the result go to the sink: append (only rows that will never change again), update (rows that changed in this round) or complete (the whole result, every time). Which modes a query may use depends on what it computes; Output modes goes through the rules.
How a stream survives a crash
The checkpoint is a folder where Spark writes down, for every round, what it is about to read and whether it finished. Click through one round, and then a crash:
Step 1 · plan
offsets/42 in the checkpoint before doing anything else. Writing the plan first is called a write-ahead log.Step 2 · process
state folder).Step 3 · write
Step 4 · done
commits/42: batch 42 is finished.Crash · restart
offsets/42 but before commits/42, the restarted query sees an unfinished batch and runs it again on exactly the same range, 1,000 to 1,450. If it dies before offsets/42, nothing was written down, so the batch is simply planned again. A source that can repeat itself, plus a sink that skips repeats, gives exactly-onceexactly-once: Each event affects the output exactly one time, even when work is retried after a failure. Learn more → results.startingOffsets), which means duplicates or gaps. Some code changes, such as grouping by different columns, cannot reuse an old checkpoint. Plan big changes as a new query with a new checkpoint.Where this track goes next
- Which sources can repeat data and which sinks never write twice: Sources and sinks, then foreachBatch for everything else.
- What is inside a checkpoint and how state is stored: Checkpoints and state stores.
- Keeping a running stream healthy: Monitoring streams.
Try it yourself
Each example says what it shows, then the output from a real run and what to notice in it, so you can follow without running anything. To try one yourself, paste it into a local Spark session, with spark already created: each builds its own data.
Goal: Load new JSON files into a bronze table with a stream that runs on a schedule and remembers what it has read.
import json, os from pyspark.sql import functions as F os.makedirs("lab/streaming/landing", exist_ok=True) with open("lab/streaming/landing/orders-001.json", "w") as f: rows = [{"user": "ana", "amount": 10}, {"user": "bo", "amount": 5}] f.write("\n".join(json.dumps(r) for r in rows)) query = (spark.readStream # streams need a schema up front .schema("user STRING, amount INT") .option("maxFilesPerTrigger", 100) # bound each micro-batch .json("lab/streaming/landing") .withColumn("ingested_at", F.current_timestamp()) .writeStream .format("parquet") .option("path", "lab/streaming/bronze") .option("checkpointLocation", "lab/streaming/_checkpoints/bronze") # one per query .queryName("bronze_orders") # a scheduled job; processingTime="1 minute" for a service .trigger(availableNow=True) .start()) query.awaitTermination() print("rows this run:", sum(p["numInputRows"] for p in query.recentProgress)) print("rows in bronze:", spark.read.parquet("lab/streaming/bronze").count()) (spark.read.parquet("lab/streaming/bronze").orderBy("user") .withColumn("ingested_at", F.date_trunc("second", "ingested_at")) .show(truncate=False))
Output from a real run
rows this run: 2 rows in bronze: 2 +----+------+-------------------+ |user|amount|ingested_at | +----+------+-------------------+ |ana |10 |2026-11-28 10:58:50| |bo |5 |2026-11-28 10:58:50| +----+------+-------------------+
What to notice:
- 2 rows read, 2 rows in bronze, each stamped with the time it was loaded.
- Run it again and it reads nothing: the checkpoint remembers which files it processed. Add a second file and run once more to see only that file loaded.
Goal: Keep running totals in a stream, stop it, and restart it without losing the totals.
import json, os from pyspark.sql import functions as F os.makedirs("lab/streaming/in", exist_ok=True) def drop_file(name, rows): # simulate a producer writing a new file with open(f"lab/streaming/in/{name}.json", "w") as f: f.write("\n".join(json.dumps(r) for r in rows)) def run_once(): (spark.readStream.schema("user STRING, amount INT").json("lab/streaming/in") .groupBy("user").agg(F.sum("amount").alias("spent")) # memory sink: keeps the result in a temp table named "totals" .writeStream.outputMode("complete").format("memory").queryName("totals") .option("checkpointLocation", "lab/streaming/_checkpoints/totals") .trigger(availableNow=True) .start().awaitTermination()) spark.table("totals").orderBy("user").show() drop_file("batch1", [{"user": "ana", "amount": 10}, {"user": "bo", "amount": 5}]) run_once() drop_file("batch2", [{"user": "ana", "amount": 7}]) run_once() # restarts from the checkpoint: reads only batch2, keeps the totals
Output from a real run
+----+-----+ |user|spent| +----+-----+ | ana| 10| | bo| 5| +----+-----+ +----+-----+ |user|spent| +----+-----+ | ana| 17| | bo| 5| +----+-----+
What to notice:
- Where
totalscomes from: thememorysink keeps the stream's result in a temporary in-memory table, named byqueryName("totals").spark.table("totals")reads that table. It is for tests and demos only; a real job writes to Delta or files. - First run: ana 10, bo 5.
- Second run read only the new file (ana 7) and continued from the saved totals: ana is now 17, bo still 5.
- The totals survived the restart because they are stored in the checkpoint.
Common mistakes
- Sharing or deleting a checkpoint — Lost or duplicated data. One checkpoint per query, kept as long as the query lives.
- complete mode on a large aggregation — The whole result is rewritten every round.
- A foreachBatch write that is not safe to repeat — A batch that runs twice is appended twice. Use MERGE, or write with the batch id.
- Aggregating without a watermarkwatermark: In streaming, how late data may arrive. Spark uses it to know when old state can be dropped. Learn more → — State grows forever and eventually the job runs out of memory.
Key takeaways
- A stream is a table that keeps growing; Spark processes the new rows in small rounds called micro-batches.
- Every query has a source, a sink, a trigger, an output mode and a checkpoint.
- The checkpoint writes down what each round will read before reading it, and marks it done after: that is how a crash is recovered exactly.
- Exactly-once needs a source that can repeat data, the checkpoint, and a sink that skips repeats.
Interview prep
THE QUESTION
"How does Structured Streaming achieve exactly-once?"
Avoid: "Spark guarantees exactly-once" without saying it needs a replayable source, a checkpoint and an idempotent or transactional sink.
Follow-ups · answer out loud, then open
Follow-up"What is the difference between append, update and complete output modes?"
Scenario"You need to upsert each micro-batch into a Delta table. How?"
foreachBatch: inside it, run a MERGE of the batch into the target. Deduplicate the batch first on the key so MERGE does not fail on duplicate source rows, and make the write idempotent (Delta's txnAppId/txnVersion options or MERGE semantics) so a retried batch does not double-apply.Trap"I changed the query and pointed it at the same checkpoint. It should continue from where it stopped."
Check yourself
3 questionsWhat does the offsets log in a checkpoint record?
Show the answer
What each batch will read, written before it is processed. It is written first, so a failed batch can be re-run on exactly the same input.
Which output mode writes only rows that changed in this batch?
Show the answer
update. update writes the result rows that changed.
What does trigger(availableNow=True) do?
Show the answer
Processes all the data waiting, then stops. It runs like a batch job that still uses the checkpoint to process only new data.
Practise this
Problems that use this, graded on hidden tests
- Live Page View CountsStreaming Easy
- Enrich a Stream of Orders with Customer DataStreaming Easy
- Click Counts in 5-Minute Windows with Late DataStreaming Medium
Keep going
Up next · First streams · lesson 3 of 5 · 8 min readSources and sinks
Which sources can replay data, how Kafka and file sources track their position, and which sinks are exactly-once.
Related lessons
Batch, micro-batch or streaming?Structured Streaming · 8 min read
Watermarks and late dataStructured Streaming · 7 min read
Streaming into Delta tables
Previous: Batch, micro-batch or streaming?
Primary sources: Structured Streaming guide · Kafka integration