Streaming into Delta tables
Delta tables and streams fit together well: a stream can write into a Delta table without ever writing a batch twice, and another stream can read that table as it grows. This lesson shows both directions, how to update rows instead of only adding them, and what keeps such tables fast.
Step 4 · Structured Streaming · Silver · Streams into the lakehouse, lesson 1 of 2
On this page
Read first: Structured Streaming basics · The Delta transaction log (skip if you know them)
In plain words first
A Delta table keeps a numbered log of every change, like a bank passbook where each line is one transaction. A stream writing into it adds one line per 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 →, and writes the batch number on that line, so the same batch can never be entered twice. A stream reading from it simply reads the passbook line by line, picking up each new line as it appears.
Delta as a sink
(events.writeStream .format("delta") .outputMode("append") .option("checkpointLocation", "s3://chk/bronze_events/") .trigger(processingTime="1 minute") .toTable("bronze.events"))
Every micro-batch becomes one commit (one line in the table's log), written all at once or not at all. The commit stores the query id and the batch number; if the same batch is retried after a crash, Delta sees it was already written and skips it. Together with 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 →, that gives exactly-onceexactly-once: Each event affects the output exactly one time, even when work is retried after a failure. Learn more → output.
Delta as a source
silver = (spark.readStream .table("bronze.events") .filter(F.col("event_type").isNotNull()) .withWatermark("event_time", "1 hour") # dedup needs a watermark .dropDuplicatesWithinWatermark(["event_id"])) (silver.writeStream.format("delta") .option("checkpointLocation", "s3://chk/silver_events/") .trigger(availableNow=True) .toTable("silver.events"))
dropDuplicatesWithinWatermarkneedswithWatermarkbefore it: without one, Spark refuses to start the query. The watermarkwatermark: In streaming, how late data may arrive. Spark uses it to know when old state can be dropped. Learn more → decides how long eachevent_idis remembered (Deduplicating a stream).- The stream reads the current snapshotsnapshot: A complete, consistent version of a table at one moment. Readers always see one snapshot, never a half-finished write. Learn more → first, then each new commit in order. Use
startingVersionorstartingTimestampto start from a point in history. maxFilesPerTriggerandmaxBytesPerTriggerlimit how much each batch reads, useful for a first run over a big table.- With
trigger(availableNow=True)on a schedule, the same code is an incremental batch job: it processes only commits added since the last run.
When the source table is updated or deleted
A stream reading a Delta table expects new rows only. If someone runs UPDATE, DELETE, MERGE or overwrites a 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 → in that table, the stream fails: the rewritten files hold rows it has already processed, and it cannot tell what changed.
| Option | Effect | Use when |
|---|---|---|
skipChangeCommits=true | Ignores commits that rewrite files | Deletes for retentionretention: How long Kafka keeps messages before deleting the oldest, by time or size. It is also how far back a reader can replay. Learn more → or GDPR that downstream does not need to mirror |
| Read the Change Data Feed | .option("readChangeFeed", "true") streams inserts, updates and deletes as rows | Downstream must reflect updates and deletes |
| Restart from a new checkpoint | Reprocess from a chosen version | One-off rewrites like a schema fix |
Upserting a stream
Sometimes a stream carries changes, not new facts: "customer 7 moved to Pune". Then each batch must update existing rows and insert new ones, an upsert, done with MERGE inside foreachBatch:
Step 1 · the feed
Step 2 · dedup per batch
The command
w = Window.partitionBy("customer_id").orderBy(F.desc("changed_at")) latest = ( batch_df.withColumn("row_num", F.row_number().over(w)) .filter("row_num = 1") .drop("row_num") )
Step 3 · MERGE
The command
(DeltaTable.forName(spark, "silver.customers").alias("t") .merge(latest.alias("s"), "t.customer_id = s.customer_id") .whenMatchedDelete(condition="s.op = 'D'") .whenMatchedUpdateAll() .whenNotMatchedInsertAll(condition="s.op != 'D'") .execute())
Step 4 · idempotentidempotent: Safe to run again: running a step twice gives the same result as running it once. Learn more →
Keeping streaming tables fast
- A one-minute triggertrigger: The setting that decides when the next micro-batch starts: straight away, on a fixed interval, or once over everything waiting. Learn more → writes 1,440 commits a day, each with small files. Schedule
OPTIMIZE(compaction is safe while the stream runs) or enable auto compaction and optimized writes. - Delta writes a log checkpoint every 10 commits by default, so readers do not replay thousands of JSON commits.
VACUUMmust keep files at least as long as any downstream stream could laglag: How far a stream is behind: data that has arrived but has not been processed yet. Learn more → behind, or the lagging stream fails when its files are gone.- Longer triggers or availableNow schedules reduce commits and files when minute-level freshness is not needed.
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 Delta Lake, with spark already created: each builds its own data.
Goal: Stream changes into a Delta table, merging each micro-batch so every id keeps only its latest version.
import json, os from delta.tables import DeltaTable from pyspark.sql import Window, functions as F os.makedirs("lab/stream_delta/in", exist_ok=True) silver = os.path.abspath("lab/stream_delta/silver") spark.sql(f"""CREATE OR REPLACE TABLE delta.`{silver}` (id INT, city STRING, seq INT) USING delta""") def drop(name, rows): with open(f"lab/stream_delta/in/{name}.json", "w") as f: f.write("\n".join(json.dumps(r) for r in rows)) def upsert(batch, batch_id): newest = Window.partitionBy("id").orderBy(F.col("seq").desc()) latest = batch.withColumn("rn", F.row_number().over(newest)).where("rn = 1") (DeltaTable.forPath(batch.sparkSession, silver).alias("t") .merge(latest.alias("s"), "t.id = s.id") .whenMatchedUpdate(condition="s.seq > t.seq", set={"city": "s.city", "seq": "s.seq"}) .whenNotMatchedInsert(values={"id": "s.id", "city": "s.city", "seq": "s.seq"}) .execute()) def run(): (spark.readStream.schema("id INT, city STRING, seq INT").json("lab/stream_delta/in") .writeStream.foreachBatch(upsert) .option("checkpointLocation", "lab/stream_delta/_checkpoint") .trigger(availableNow=True).start().awaitTermination()) drop("1", [{"id": 1, "city": "Pune", "seq": 1}, {"id": 2, "city": "Delhi", "seq": 1}]) run() drop("2", [{"id": 1, "city": "Mumbai", "seq": 2}, {"id": 1, "city": "Thane", "seq": 3}]) run() spark.read.format("delta").load(silver).orderBy("id").show()
Output from a real run
+---+-----+---+ | id| city|seq| +---+-----+---+ | 1|Thane| 3| | 2|Delhi| 1| +---+-----+---+
What to notice:
- Id 1 is
Thane: the second batch had two changes for it, and the one with the higherseq(3) won. - Id 2 was not in the second batch and is unchanged.
- Keeping one row per id before the MERGE stops it failing on duplicates;
s.seq > t.seqstops a replayed old change overwriting a newer one.
Common mistakes
- UPDATE or DELETE on a table that a stream reads — The stream fails. Use skipChangeCommits or the Change Data Feed.
- MERGE without deduplicating the micro-batch — Fails when several source rows match one target row.
- Aggressive VACUUM with lagging streams — Files a stream still needs are deleted.
- Never compacting a streaming table — Thousands of small files per day.
Key takeaways
- Each micro-batch is one Delta commit; batch ids make retries safe.
- Delta streaming sources expect appends; updates and deletes need skipChangeCommits or CDF.
- foreachBatch + dedup + MERGE upserts a stream idempotently.
- Compact streaming tables and keep VACUUM retention above stream lag.
Interview prep
THE QUESTION
"Design a pipeline that keeps a silver customers table in sync with a CDC stream from Kafka."
Avoid: a single stream from Kafka straight into silver with MERGE and no bronze. You lose replay, and debugging bad events gets hard.
Follow-ups · answer out loud, then open
Follow-up"How do you make a foreachBatch MERGE idempotent if a batch is retried?"
txnAppId and txnVersion (the batch id) so Delta skips a batch it has already committed.Scenario"A downstream stream reads the silver table, and it fails after a MERGE updates rows. Why?"
skipChangeCommits to ignore such commits, or read the Change Data Feed as a stream to get updates and deletes explicitly.Trap"Exactly-once into Delta means each Kafka message appears once in the table."
Check yourself
3 questionsHow does a Delta sink avoid writing a retried micro-batch twice?
Show the answer
It records the query and batch id in the commit and skips a batch already committed. The txn action stores the batch id per query.
A stream reads table A. Someone runs DELETE on A. What happens by default?
Show the answer
The stream fails. Rewritten files break the append-only expectation; use skipChangeCommits or CDF.
Why deduplicate inside foreachBatch before MERGE?
Show the answer
MERGE fails when several source rows match one target row. A target row can only be updated by one source row per MERGE.
Practise this
Problems that use this, graded on hidden tests
Keep going
Up next · Streams into the lakehouse · lesson 2 of 2 · 7 min readIncremental file ingestion
Load each new file exactly once: the streaming file source, Auto Loader, COPY INTO, schema drift and backfills.
Related lessons
Change Data FeedData lake & lakehouse · 7 min read
MERGE INTO and upsertsStructured Streaming · 8 min read
Watermarks and late data
Previous: Deduplicating a stream
Primary sources: Delta table streaming reads and writes · Structured Streaming guide