Sources and sinks
Every stream reads from somewhere and writes somewhere. Where it reads decides whether a crash can be recovered; where it writes decides whether a retry can create duplicates. This lesson compares the common sources and sinks, and points to foreachBatch for destinations without a sink.
Step 4 · Structured Streaming · Bronze · First streams, lesson 3 of 5
On this page
Read first: Structured Streaming basics (skip if you know it)
In plain words first
Compare a live radio show with a recorded podcast. If your phone dies during the radio show, the part you missed is gone. With the podcast, you open it again and it continues from the minute you stopped. A stream needs a podcast-like source: one it can ask for "the same data again, from here".
On the other side, the sink is where results go. A good sink is like a till that refuses to charge the same receipt number twice: if a crash makes Spark write a batch again, the sink notices and ignores it.
What makes a source safe
After a crash, Spark runs the unfinished micro-batchmicro-batch: One small round of a stream: Spark takes the data that arrived since the last round, processes it like a little batch job, and saves its progress. Learn more → again, so the source must hand back exactly the same input. It can only do that if it has a position Spark can save in the checkpointcheckpoint: In streaming, the folder where Spark records which input it has processed and its state, so a restarted query continues where it stopped. Learn more → and ask for later:
| Source | Position saved in the checkpoint | Can repeat data? | Use it for |
|---|---|---|---|
| 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 → | An offsetoffset: The position of a message inside a Kafka partition: 0, 1, 2, ... A stream stores the offsets it has read in its checkpoint. Learn more → per partitionpartition: In Kafka, one ordered slice of a topic, read in order. In Spark, one chunk of a DataFrame's rows, processed as one task. Learn more → | Yes, while Kafka still keeps the messages | Event streams |
| Files in a folder (JSON, CSV, ParquetParquet: A columnar file format: values of each column are stored together, so queries read only the columns they need. Learn more →...) | The list of files already read | Yes | Files dropped by other systems |
| Delta table | A table version | Yes, while VACUUM has not deleted the files | Bronze → silver → gold |
| Rate | Generated rows | Yes | Load tests |
| Socket | Nothing | No | Demos only: a restart loses data |
Reading Kafka
New to Kafka itself? Kafka in plain words explains topicstopic: A named stream of events in Kafka or Pub/Sub, such as "orders". Producers write to it; consumers read from it. Learn more →, partitions and offsets first.
# the JSON fields inside each message, as a DDL string click_schema = "user_id STRING, page STRING, event_time TIMESTAMP" events = (spark.readStream .format("kafka") .option("kafka.bootstrap.servers", "broker:9092") .option("subscribe", "clicks") .option("startingOffsets", "earliest") # only for the very first run .option("maxOffsetsPerTrigger", 100000) # at most 100k messages per micro-batch .load() .select(F.col("key").cast("string"), F.from_json(F.col("value").cast("string"), click_schema).alias("c"), "topic", "partition", "offset", "timestamp"))
keyandvaluearrive as raw bytes: cast them to strings, and parse the value withfrom_json(or the AvroAvro: A compact binary format whose messages need a schema to be read; common on Kafka. Learn more → / Protobuf functions).startingOffsetsis used only on the very first run. After that, the checkpoint knows where to continue, whatever the option says.maxOffsetsPerTriggerlimits each batch. Without it, the first run after a long outage tries to read the whole backlog at once (Backpressure).failOnDataLoss(on by default) stops the query if Kafka already deleted messages it still needed. Keep it on: silently skipping data is worse than an alert.
Reading a folder of files
The file source looks at the folder on every triggertrigger: The setting that decides when the next micro-batch starts: straight away, on a fixed interval, or once over everything waiting. Learn more → and reads the files it has not seen yet. You must give it the schema, so the columns cannot change under a running query. Every file it reads is written to the checkpoint (sources/0), so a restart never reads a file twice. maxFilesPerTrigger limits each batch, and cleanSource ("archive" with a sourceArchiveDir, or "delete") moves finished files out, so the folder does not grow forever.
Sinks and what they promise
| Sink | Output modes | If a batch is written twice | How |
|---|---|---|---|
| Delta table | append, complete | Ignored: exactly-onceexactly-once: Each event affects the output exactly one time, even when work is retried after a failure. Learn more → | Each batch is one commit tagged with the batch id; a repeat is skipped |
| Files (Parquet, JSON...) | append | Ignored, when read with Spark | A _spark_metadata log lists the finished files; Spark reads the folder through it |
| Kafka | append, update, complete | Sent again: at-least-onceat-least-once: No event is lost, but after a failure some can be processed or written twice. Learn more → | Messages from the retried batch are sent a second time |
| foreachBatch | all | Up to your code | You get each batch as a normal DataFrame |
| console, memory | append, update, complete | No promise | Testing only; memory keeps everything on the driverdriver: The process that runs your program, plans the work and sends tasks to executors. Learn more → |
The file sink has a catch. If a batch fails half way, some of its files may already be in the folder. Spark ignores them, because it reads the folder through the _spark_metadata log, which lists only finished batches. Another engine that just lists the folder sees them too. The second lab below shows the difference.
And when there is no sink?
Some destinations have no streaming sink: a Postgres table, a REST API, or two tables at once. foreachBatch hands each micro-batch to your own function as a normal DataFrame, so any batch writer works. It has its own lesson: foreachBatch: write a stream anywhere.
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: Read a landing folder one file per batch, and move processed files to an archive.
import json, os os.makedirs("lab/src/landing", exist_ok=True) for i, rows in enumerate([[("ana", 10), ("bo", 5)], [("cy", 7)]]): path = f"lab/src/landing/part-{i}.json" with open(path, "w") as f: f.write("\n".join(json.dumps({"user": u, "amount": a}) for u, a in rows)) os.utime(path, (1_700_000_000 + i, 1_700_000_000 + i)) # read in this order query = (spark.readStream .schema("user STRING, amount INT") # a file source needs the schema .option("maxFilesPerTrigger", 1) # at most one file per micro-batch .option("cleanSource", "archive") # move processed files away .option("sourceArchiveDir", "lab/src/archive") .json("lab/src/landing") .writeStream .format("parquet") .option("path", "lab/src/bronze") .option("checkpointLocation", "lab/src/_chk") .trigger(availableNow=True) .start()) query.awaitTermination() print("rows per micro-batch:", [p["numInputRows"] for p in query.recentProgress]) print("rows in bronze:", spark.read.parquet("lab/src/bronze").count()) log = [f for f in os.listdir("lab/src/_chk/sources/0") if not f.startswith(".")] print("file-source log entries in the checkpoint:", len(log))
Output from a real run
rows per micro-batch: [2, 1] rows in bronze: 3 file-source log entries in the checkpoint: 2
What to notice:
- Two micro-batches, 2 rows then 1: one file each, because of
maxFilesPerTrigger. - The checkpoint has 2 entries under
sources/0: every file read is recorded, so a restart never reads one twice. cleanSourcemoves a file to the archive once a later batch has committed it, so the landing folder does not grow forever.
Goal: See why a stream's file output is exactly-once: the _spark_metadata log.
import glob, os, shutil out = "lab/src/bronze" # written by the stream above log = sorted(f for f in os.listdir(f"{out}/_spark_metadata") if not f.startswith(".")) print("committed batches in _spark_metadata:", log) # A crash mid-batch can leave a data file that was never committed. Simulate one. files = glob.glob(f"{out}/*.parquet") biggest = max(files, key=lambda f: spark.read.parquet(f).count()) shutil.copy(biggest, f"{out}/part-from-a-failed-batch.parquet") print("read the folder (through the log):", spark.read.parquet(out).count()) direct = spark.read.parquet(f"{out}/*.parquet") print("read the files directly (no log): ", direct.count())
Output from a real run
committed batches in _spark_metadata: ['0', '1'] read the folder (through the log): 3 read the files directly (no log): 5
What to notice:
_spark_metadatalists batches 0 and 1: the committed ones.- Reading the folder gives 3 rows: Spark goes through the log and ignores the stray file from a "failed" batch.
- Reading the files directly gives 5: the stray file counted twice. Other engines that list the folder see the same, so read stream output with Spark, or use Delta.
Common mistakes
- Expecting startingOffsets to rewind a running query — It only applies to a new checkpoint. To reprocess, start a new query with a new checkpoint.
- Reading a file-sink folder with another engine — It can see files from failed batches. Read stream output with Spark, or write to Delta.
- Treating the Kafka sink as exactly-once — Retries send messages again. Give consumersconsumer: An application that reads events from a topic and keeps track of how far it has read. Learn more → an event id to deduplicate on.
- Turning off failOnDataLoss to make an error go away — The query then skips the lost data without telling anyone.
Key takeaways
- A source must be able to give the same data again: Kafka, files or Delta, never a socket.
- startingOffsets matters only on the first run; limit batches with maxOffsetsPerTrigger or maxFilesPerTrigger.
- Delta and file sinks skip a repeated batch; Kafka sends it again.
- Where no sink exists, foreachBatch hands each batch to your own code.
Interview prep
THE QUESTION
"Your stream writes to Kafka and a downstream team sees duplicate messages. Why, and what do you do?"
Avoid: "Kafka in, Delta out, so it is exactly-once" without saying why each end qualifies: replayable offsets in, transactional commits out, and the checkpoint in between.
Follow-ups · answer out loud, then open
Follow-up"The first run after a week-long outage takes hours and runs out of memory. Why?"
Scenario"A partner rewrites yesterday's file in the landing folder with corrections. Does the stream pick it up?"
Trap"Reading the file sink's output folder with any engine gives exactly-once results."
Check yourself
3 questionsA query has a checkpoint. You change startingOffsets to "latest" and restart. Where does it read from?
Show the answer
Where the checkpoint says it stopped. startingOffsets is only used when there is no checkpoint yet.
Why is the socket source only for demos?
Show the answer
It cannot give data again, so a restart loses input. Without a saved position, a failed batch cannot be re-run on the same input.
Which sink can produce duplicates when a micro-batch is retried?
Show the answer
Kafka. The Kafka sink is at-least-once.
Practise this
Interview problems on streaming, graded on hidden tests
Keep going
Up next · First streams · lesson 4 of 5 · 7 min readforeachBatch: write a stream anywhere
Hand each micro-batch to your own code as a normal DataFrame, and the four rules that keep the writes correct.
Related lessons
TriggersStructured Streaming · 7 min read
Incremental file ingestionStructured Streaming · 7 min read
Streaming into Delta tables
Previous: Structured Streaming basics
Primary sources: Input sources · Output sinks · Kafka integration