Skip to content
Silver 10 min read · foreachBatch 2 practice problems ↓

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

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

A dead-letter table (or topictopic: A named stream of events in Kafka or Pub/Sub, such as "orders". Producers write to it; consumers read from it. Learn more →) where bad records wait.

The note

An error_reason column that says why each record failed.

Checking the bin

An alert when too many records land there.

Sending it on

A replay: once the code is fixed, process the waiting records again.

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

Broken JSON, a message cut off half way, or text where a number should be.

It reads, but breaks a rule

The JSON is fine, but the 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:

PySpark · Parse, then label each row
# 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"))
Watch out: The from_json trap. You might expect 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.

PySpark · Valid rows to silver, invalid 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 txnAppId and txnVersion options 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 tableDead-letter Kafka topic
Looking insideSQL: count by reason, see examplesNeeds a consumerconsumer: An application that reads events from a topic and keeps track of how far it has read. Learn more →
ReplayingA batch job picks rows by reasonRead again by offset, or send back to the main topic
Keeps rows forAs long as you chooseThe 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 whenOne team owns the pipelineAnother 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:

PySpark · Counts in query.lastProgress["observedMetrics"]["quality"]
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

  1. 1
    Find the cause. Count the dead-letter rows by error_reason, then fix the parser or the rule.
  2. 2
    Run 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.
  3. 3
    Mark them done. Set a replayed_at column on the rows that went through. Leave the rest for the next fix.
  4. 4
    Fix the totals. Replayed rows belong to old hours or days. Recompute the downstream aggregates for those periods.
Tip: Replay straight into the target table, not into the live stream's source. Replayed rows have old event times, and a windowed aggregation would drop them as too late for its watermarkwatermark: In streaming, how late data may arrive. Spark uses it to know when old state can be dropped. Learn more →.

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.

Production patternPySpark · Route bad records to a dead-letter table, then replay them after a fix
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_record field.
  • After the fix, order 4 is in silver: the replay read its raw text again and accepted the renamed id field.
  • 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_record field 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."

Parse with from_json and a _corrupt_record field, check required fields and business rules, and give every row an error reason. In foreachBatch, write valid rows to silver and invalid ones to a dead-letter Delta table with the raw payload, the reason, topic, partition and offset, and the batch id, both writes idempotent. The query never fails on bad data, but still fails on infrastructure errors so Spark retries. Alert on the dead-letter rate per batch through observe() and a listener, and on rows waiting too long. After a fix, a batch job replays rows by reason with a MERGE on the key, marks them replayed, and affected aggregates are recomputed.

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?"
Alert on the rate per batch against its usual level, not on any row at all: a jump from a fraction of a percent to tens of percent means a producer shipped a breaking change. Group by error_reason to see which. Also alert on age: rows that have waited days without a replay are a fix nobody owns.
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?"
Fix the parser and deploy it so new orders flow again. Replay the two hours from the dead-letter table with a batch job: parse with the fixed code and MERGE into silver on order_id, so a rerun is harmless, then mark the rows replayed. The gold windows for those hours were already written, so recompute gold for exactly those hours. Afterwards, ask the producer team for a schema check in their CI.
Trap"PERMISSIVE mode handles bad JSON, so there is nothing else to do."
PERMISSIVE does not remove bad rows, it nulls their fields. They flow into silver looking like real orders with missing values, which is worse than an error. Capture the text with a _corrupt_record field, check required fields, and route those rows away from silver.

Check yourself

3 questions

With 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 read
Stream joins
Stream-static enrichment, stream-stream joins bounded by watermarks, and why outer joins emit late.

Related lessons

Previous: Ordering and out-of-order events

Primary sources: from_json · JSON options: mode and columnNameOfCorruptRecord · foreachBatch · DataFrame.observe · Writing data to Kafka (headers)