Bad records and dead-letter queues
Sooner or later, a message arrives that your code cannot read. If the stream stops for it, nothing else gets through. If the stream skips it, that data is lost and nobody knows. This lesson shows the usual fix, a dead-letter queue: put bad records to one side, watch how many there are, and send them through again once the bug is fixed.
Step 4 · Structured Streaming · Silver · Correct results end to end, lesson 3 of 3
On this page
Read first: Sources and sinks · Delivery guarantees end to end (skip if you know them)
In plain words first
A post office sorts thousands of letters an hour. Now and then a letter has an address nobody can read. The sorters do not stop the whole line for it. They do not throw it away either. They put it in a separate bin, the dead letter office, with a note saying what was wrong. Every day someone checks the bin, works out the right address, and sends the letter on.
A stream needs the same bin:
The bin
The note
error_reason column that says why each record failed.Checking the bin
Sending it on
Neither stop nor drop
There are two easy ways to handle a bad record, and both are wrong:
- Stop. The query fails. When it restarts, it reads the same message and fails again, every time. One bad message (people call it a poison pill) blocks all the good data behind it.
- Drop. The stream skips the record. Nothing breaks, but the data is gone and nobody notices.
A dead-letter queue (DLQ) is the third way. The bad record is saved somewhere else with its reason, and the stream keeps going.
Finding the bad rows
A record can be bad in two ways:
It cannot be read
It reads, but breaks a rule
order_id is missing or the amount is negative.Give every row an error_reason. It stays null when the row is fine and holds a short message when it is not:
# keep the original text and where it came from raw = kafka.select(F.col("value").cast("string").alias("raw"), "topic", "partition", "offset") # parse it; _corrupt_record catches text that is not valid JSON o = F.from_json("raw", "order_id INT, amount INT, _corrupt_record STRING") # null reason = good row; anything else = bad row reason = (F.when(o.isNull() | o["_corrupt_record"].isNotNull(), "unparseable JSON or wrong type") .when(o["order_id"].isNull(), "missing order_id") .when(o["amount"] < 0, "negative amount")) labelled = raw.select("*", o.alias("o"), reason.alias("error_reason"))
from_json to return null for broken JSON. It does not. By default it returns a row where every field is null, and a field with the wrong type just becomes null. So checking o IS NULL lets bad rows through. Add a _corrupt_record STRING field to the schema: Spark puts the broken text there. A missing field is not "broken", so check required fields yourself.Sending good and bad rows to different places
foreachBatch gives you each 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 → as a normal DataFrame, so you can write it to two tables: good rows to silver, bad rows to the dead-letter table.
def route(batch_df, batch_id): batch_df.persist() # two writes, compute the batch once # good rows -> silver (batch_df.where("error_reason IS NULL").select("o.order_id", "o.amount") .write.format("delta").mode("append") # txnAppId + txnVersion: Delta skips a batch it already wrote .option("txnAppId", "orders_silver").option("txnVersion", batch_id) .saveAsTable("silver.orders")) # bad rows -> dead-letter table, with the reason and where they came from (batch_df.where("error_reason IS NOT NULL") .select("raw", "error_reason", "topic", "partition", "offset", F.lit(batch_id).alias("batch_id"), F.current_timestamp().alias("failed_at")) .write.format("delta").mode("append") .option("txnAppId", "orders_dlq").option("txnVersion", batch_id) .saveAsTable("ops.orders_dead_letter")) batch_df.unpersist()
Four rules for the dead-letter table:
- Save the original message, exactly as it arrived. 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 → deletes old messages after a while. Later, the replay needs this copy to try again with the fixed code.
- Save where it came from: topic, 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 → and 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 →. For a file sourcesource: Where a stream reads from: a Kafka topic, a folder of files, a Delta table. Learn more →, save the file name from
_metadata.file_path. - Make both writes safe to run twice. Spark can run the same batch again after a crash. The
txnAppIdandtxnVersionoptions make Delta skip a batch it has already written (Delivery guarantees). - Only bad data goes in the bin. If the target table is down, that is an outage, not a bad record. Let the batch fail so Spark tries again. Putting outages in the DLQ hides them.
A table or a topic?
The bin can be a Delta table or a Kafka topic. Most lakehouse teams start with a table, because SQL makes it easy to look inside.
| Dead-letter Delta table | Dead-letter Kafka topic | |
|---|---|---|
| Looking inside | SQL: count by reason, see examples | Needs a consumerconsumer: An application that reads events from a topic and keeps track of how far it has read. Learn more → |
| Replaying | A batch job picks rows by reason | Read again by offset, or send back to the main topic |
| Keeps rows for | As long as you choose | The topic's 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 → |
| Good when | One team owns the pipeline | Another team or service owns the fix |
For a topic, write the original message as the value and the reason as a Kafka header: F.array(F.struct(F.lit("error_reason").alias("key"), F.col("error_reason").cast("binary").alias("value"))).alias("headers").
Getting an alert when bad rows pile up
A bin nobody checks is just data loss with extra steps. Do not alert on every bad row: a few a day can be normal. Alert on the share of bad rows. If it jumps from 0.1% to 30%, a producerproducer: An application that writes events to a topic. Learn more → has shipped a breaking change.
observe() counts rows as they pass and adds the counts to every progress report. A listener (Monitoring streams) can send them to your alerting tool:
labelled = labelled.observe("quality", F.count(F.lit(1)).alias("rows"), # all rows F.count("error_reason").alias("bad")) # count() skips nulls, so only bad rows
Also alert when rows have sat in the bin too long. That means nobody is fixing them.
Replaying after a fix
- 1Find the cause. Count the dead-letter rows by
error_reason, then fix the parser or the rule. - 2Run the rows again. A batch job reads the rows with that reason that have not been replayed yet, parses them with the fixed code, and MERGEs them into the target on its key. Because it is a MERGE, running the replay twice does no harm.
- 3Mark them done. Set a
replayed_atcolumn on the rows that went through. Leave the rest for the next fix. - 4Fix the totals. Replayed rows belong to old hours or days. Recompute the downstream aggregates for those periods.
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: Keep a stream running past bad records, see why each one failed, then repair the ones a code fix can save.
import os from delta.tables import DeltaTable from pyspark.sql import functions as F SILVER = os.path.abspath("lab/dlq/silver") DLQ = os.path.abspath("lab/dlq/dead_letter") os.makedirs("lab/dlq/in", exist_ok=True) with open("lab/dlq/in/orders-1.txt", "w") as f: f.write("\n".join([ '{"order_id": 1, "amount": 10}', '{"order_id": 2, "amount": -5}', '{"order_id": 3', # cut off mid-message '{"id": 4, "amount": 7}', # a new app version renamed the field '{"order_id": 5, "amount": 20}', ])) def parse(df, accept_renamed_id=False): o = F.from_json("raw", "order_id INT, id INT, amount INT, _corrupt_record STRING") p = df.withColumn("o", o) order_id = F.col("o.order_id") if accept_renamed_id: # the fix order_id = F.coalesce(order_id, F.col("o.id")) reason = (F.when(F.col("o").isNull() | F.col("o._corrupt_record").isNotNull(), "unparseable JSON or wrong type") .when(order_id.isNull(), "missing order_id") .when(F.col("o.amount") < 0, "negative amount")) return p.select("raw", order_id.alias("order_id"), F.col("o.amount").alias("amount"), reason.alias("error_reason")) def route(batch_df, batch_id): batch_df.persist() # two writes, one computation (batch_df.where("error_reason IS NULL").select("order_id", "amount") .write.format("delta").mode("append") .option("txnAppId", "orders_silver").option("txnVersion", batch_id) .save(SILVER)) (batch_df.where("error_reason IS NOT NULL") .select("raw", "error_reason", F.lit(batch_id).alias("batch_id"), F.current_timestamp().alias("failed_at"), F.lit(None).cast("timestamp").alias("replayed_at")) .write.format("delta").mode("append") .option("txnAppId", "orders_dlq").option("txnVersion", batch_id) .save(DLQ)) batch_df.unpersist() stream = (parse(spark.readStream.text("lab/dlq/in").withColumnRenamed("value", "raw")) .observe("quality", F.count(F.lit(1)).alias("rows"), F.count("error_reason").alias("bad"))) # in every progress report query = (stream.writeStream.foreachBatch(route) .option("checkpointLocation", "lab/dlq/_chk") .trigger(availableNow=True).start()) query.awaitTermination() q = query.lastProgress["observedMetrics"]["quality"] print(f"dead-letter rate: {q['bad']} of {q['rows']} rows") (spark.read.format("delta").load(DLQ).select("raw", "error_reason") .orderBy("raw").show(truncate=False)) # the fix ships: replay only the rows it can repair, and record that they were replayed todo = (spark.read.format("delta").load(DLQ) .where("error_reason = 'missing order_id' AND replayed_at IS NULL")) fixed = parse(todo.select("raw"), accept_renamed_id=True).where("error_reason IS NULL") (DeltaTable.forPath(spark, SILVER).alias("t") .merge(fixed.alias("s"), "t.order_id = s.order_id") # safe to run twice .whenNotMatchedInsert(values={"order_id": "s.order_id", "amount": "s.amount"}) .execute()) (DeltaTable.forPath(spark, DLQ).alias("d") .merge(fixed.select("raw").alias("f"), "d.raw = f.raw AND d.replayed_at IS NULL") .whenMatchedUpdate(set={"replayed_at": "current_timestamp()"}) .execute()) spark.read.format("delta").load(SILVER).orderBy("order_id").show() (spark.read.format("delta").load(DLQ) .select("error_reason", F.col("replayed_at").isNotNull().alias("replayed")) .orderBy("error_reason").show(truncate=False))
Output from a real run
dead-letter rate: 3 of 5 rows
+-----------------------------+------------------------------+
|raw |error_reason |
+-----------------------------+------------------------------+
|{"id": 4, "amount": 7} |missing order_id |
|{"order_id": 2, "amount": -5}|negative amount |
|{"order_id": 3 |unparseable JSON or wrong type|
+-----------------------------+------------------------------+
+--------+------+
|order_id|amount|
+--------+------+
| 1| 10|
| 4| 7|
| 5| 20|
+--------+------+
+------------------------------+--------+
|error_reason |replayed|
+------------------------------+--------+
|missing order_id |true |
|negative amount |false |
|unparseable JSON or wrong type|false |
+------------------------------+--------+What to notice:
- The rate line comes from
observe(): 3 of the 5 rows went to the dead-letter table, and the query never failed. - Each dead letter keeps its raw text and a reason. The cut-off message was caught only because the schema has a
_corrupt_recordfield. - After the fix, order 4 is in silver: the replay read its raw text again and accepted the renamed
idfield. - Only the repaired row is marked replayed. The negative amount and the broken message wait for a fix of their own.
Common mistakes
- Failing the query on a bad record — It fails on the same message after every restart, and good data piles up behind it.
- Saving only the parsed columns — A replay needs the original message. Keep it exactly as it arrived.
- Sending every error to the DLQ — A table that is down is an outage, not a bad record. Let the batch fail and retry.
- Checking from_json's result for null — Broken JSON gives a row of nulls, not null. Add a
_corrupt_recordfield and check required fields.
Key takeaways
- A dead-letter queue keeps a stream moving without losing data: bad rows are set aside with the reason they failed.
- from_json returns a struct of nulls for broken input: use a _corrupt_record field and explicit rule checks.
- Keep the raw payload and its source position; make both writes idempotent; send only data errors to the DLQ.
- Alert on the rate and age of dead letters, replay by reason with a MERGE, and recompute affected aggregates.
Interview prep
THE QUESTION
"Producers sometimes send malformed or invalid JSON to a topic your stream reads. Design the handling."
Avoid: "wrap the parse in try/except and log the error". Logs cannot be replayed, nobody counts them, and the bad record is gone once Kafka retention passes.
Follow-ups · answer out loud, then open
Follow-up"How do you know when the dead-letter queue needs attention?"
Scenario"A producer's schema change sent two hours of orders to the dead-letter table, and hourly revenue in gold is too low. How do you recover?"
Trap"PERMISSIVE mode handles bad JSON, so there is nothing else to do."
Check yourself
3 questionsWith the schema "order_id INT, amount INT", what does from_json return for a message cut off half way?
Show the answer
A struct whose fields are all null. PERMISSIVE mode keeps the row and nulls its fields; only a _corrupt_record field captures the text.
Why store the raw payload in the dead-letter table?
Show the answer
A replay can re-parse it with fixed code after Kafka retention deleted the message. The DLQ is the only copy left once the source has expired the message.
The target table is unreachable during a micro-batch. Where should its rows go?
Show the answer
Nowhere: let the batch fail so Spark retries it. An outage is not a data error; a failed batch is re-run on the same input once the sink is back.
Practise this
Interview problems on streaming, graded on hidden tests
Keep going
Up next · new module: Joins and custom state · 7 min readStream joins
Stream-static enrichment, stream-stream joins bounded by watermarks, and why outer joins emit late.
Related lessons
Incremental file ingestionStructured Streaming · 7 min read
Restarts, query changes and reprocessingStructured Streaming · 9 min read
Delivery guarantees end to end
Previous: Ordering and out-of-order events
Primary sources: from_json · JSON options: mode and columnNameOfCorruptRecord · foreachBatch · DataFrame.observe · Writing data to Kafka (headers)