Producing and consuming with retries and a dead-letter queue
Build a billing consumer for order events on a local Kafka broker: bounded retries with backoff for a flaky payment provider, a dead-letter topic with error headers for events that cannot succeed, a re-drive script, and idempotent effects: a deduplication table plus an idempotency key that the payment provider honours. Then crash the consumer right after a payment, restart it and prove from both ledgers that no order was lost or paid twice, and watch consumer lag during a burst.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: Create the topics and publish orders
- Step 2: A consumer with retries and a dead-letter topic
- Step 3: Inspect the dead letters
- Step 4: Re-drive what can now succeed
- Step 5: Crash mid-batch and restart
- Step 6: Watch lag during a burst
- Check your understanding
- Apply it
- Review prompt
Lessons of Messaging & Event Streaming
- Queues, topics and logs Concept · 20 min
- Delivery guarantees and idempotent consumers Concept · 20 min
- Partitions, keys, consumer groups and offsets Concept · 20 min
- Producing and consuming with retries and a dead-letter queue Lab · 30 min
- Load leveling, backpressure, claim checks and broker sizing Worked example · 25 min
- Messaging check Knowledge check · 8 questions
What you will learn
- Choose delivery semantics (at-most-once, at-least-once, effectively-once) and make consumers idempotent.
- Level load and handle backpressure, consumer lag, retries, dead-letter queues and oversized payloads (claim check), and size a broker from message rate and retention.
01. Goal and setup
You build the consumer that turns order events into card charges. Three kinds of failure happen on purpose, and each needs a different answer:
- A transient failure: the payment provider times out, but a later try works. The answer is a retry with backoff, a growing pause between tries.
- A permanent failure: the event itself is broken (invalid JSON, a negative amount). Retrying cannot help, so the consumer moves it to a dead-letter queue (DLQ), here the topic
order-events-dlq, and carries on. - A crash right after the provider took the payment, before the consumer recorded it or committed the offset. The event is delivered again and the provider is called again; only an idempotency key, as in lesson 2, stops the money being taken twice.
You need the mq-lab folder and the running broker from lesson 3, with its kafka.sh, lag.sh and .venv (Python 3.10 or newer with confluent-kafka 2.16.1). If you removed the broker, run lesson 3's "Start a broker" blocks again. Tested with apache/kafka:3.7.2. The consumer and the stand-in payment provider each keep a ledger in their own SQLite file, as two separate systems would.
02. Step 1: Create the topics and publish orders
Create a 3-partition topic for the events and a 1-partition topic for the dead letters. The producer publishes a fixed batch of order events, keyed by order id, each with a unique event_id that the consumer will use for deduplication. Two are broken on purpose. payments.py stands in for a payment provider: like real payment APIs, it returns the first payment when it sees an idempotency key again, and it times out on a fixed schedule, so every run behaves the same.
./kafka.sh kafka-topics.sh --create --topic order-events --partitions 3
./kafka.sh kafka-topics.sh --create --topic order-events-dlq --partitions 1Created topic order-events.
Created topic order-events-dlq."""Publish a fixed batch of order events. Usage: python produce_orders.py FIRST LAST
Two events are bad on purpose: order-1007 is not valid JSON, order-1009 has a
negative amount."""
import json
import sys
from confluent_kafka import Producer
first, last = int(sys.argv[1]), int(sys.argv[2])
producer = Producer({"bootstrap.servers": "localhost:19092",
"partitioner": "murmur2_random", "enable.idempotence": True})
for n in range(first, last + 1):
order_id = f"order-{n}"
event = {"event_id": f"evt-{n}", "order_id": order_id,
"customer": f"cust-{n % 4}", "amount_cents": 1000 + (n % 7) * 250}
value = json.dumps(event)
if n == 1007:
value = value[:-5] # cut off: not valid JSON
if n == 1009:
value = json.dumps(event | {"amount_cents": -500})
producer.produce("order-events", key=order_id, value=value)
producer.flush(10)
print(f"published order-{first} .. order-{last}")"""A stand-in payment provider with its own ledger, provider.db. Like real payment
APIs, it honours an idempotency key: a repeated key returns the first payment
instead of charging again. It also times out on purpose: order-1004 fails twice,
and order-1010 fails until PROVIDER_FIXED=1."""
import os
import sqlite3
class PaymentTimeout(Exception):
"""Transient: trying again later may succeed."""
ledger = sqlite3.connect("provider.db", isolation_level=None) # autocommit
ledger.executescript("""
CREATE TABLE IF NOT EXISTS payments (idempotency_key TEXT PRIMARY KEY,
order_id TEXT, amount_cents INT, payment_id TEXT);
CREATE TABLE IF NOT EXISTS calls (idempotency_key TEXT, outcome TEXT);""")
_attempts = {}
def charge(order_id, amount_cents, idempotency_key):
"""Return (payment_id, replayed). Raises PaymentTimeout on a simulated outage."""
_attempts[order_id] = _attempts.get(order_id, 0) + 1
if (order_id == "order-1004" and _attempts[order_id] <= 2) or (
order_id == "order-1010" and os.environ.get("PROVIDER_FIXED") != "1"):
ledger.execute("INSERT INTO calls VALUES (?, 'timeout')", [idempotency_key])
raise PaymentTimeout("provider did not answer in 2 s")
earlier = ledger.execute("SELECT payment_id FROM payments"
" WHERE idempotency_key = ?", [idempotency_key]).fetchone()
if earlier: # same key: no second charge
ledger.execute("INSERT INTO calls VALUES (?, 'replayed')", [idempotency_key])
return earlier[0], True
n = 1 + ledger.execute("SELECT count(*) FROM payments WHERE order_id = ?",
[order_id]).fetchone()[0]
payment_id = f"pay-{order_id[-4:]}-{n}" # a second payment would end in -2
ledger.execute("INSERT INTO payments VALUES (?, ?, ?, ?)",
[idempotency_key, order_id, amount_cents, payment_id])
ledger.execute("INSERT INTO calls VALUES (?, 'charged')", [idempotency_key])
return payment_id, False.venv/bin/python produce_orders.py 1001 1012published order-1001 .. order-101203. Step 2: A consumer with retries and a dead-letter topic
Read the consumer first. It parses and validates each event; a ValueError (including invalid JSON) means the event can never succeed, so it goes straight to the DLQ. Otherwise it calls the provider up to MAX_ATTEMPTS times, sleeping 200 ms and then 400 ms between tries. If every attempt fails, the event goes to the DLQ too. A dead-lettered copy keeps the original key and bytes and adds headers saying what went wrong and where the event came from.
Two things protect the payment. Before calling the provider, the consumer skips an event whose id is already in its processed table. When it calls, it passes the event id as the idempotency key, which covers the window the table cannot: a crash after the payment, before the database write. The billing row and the event id are then written in one SQLite transaction, and the offset is committed only after that, so a crash can repeat an event but not lose it. The DLQ producer flushes before the commit for the same reason. The loop stops after 5 quiet seconds once it has partitions.
"""Billing consumer: bounded retries, a dead-letter topic, idempotent effects.
Usage: python consumer.py [--crash-on ORDER_ID] [--delay SECONDS]
--crash-on stops the process right after that order's payment, before anything
is written to billing.db or committed to Kafka."""
import argparse
import json
import os
import sqlite3
import time
from confluent_kafka import Consumer, Producer
from payments import PaymentTimeout, charge
MAX_ATTEMPTS = 3
args = argparse.ArgumentParser()
args.add_argument("--crash-on")
args.add_argument("--delay", type=float, default=0.0)
opts = args.parse_args()
db = sqlite3.connect("billing.db")
db.executescript("""
PRAGMA journal_mode = WAL; -- fewer disk syncs per transaction
PRAGMA synchronous = NORMAL; -- a commit survives a process crash
CREATE TABLE IF NOT EXISTS processed (event_id TEXT PRIMARY KEY);
CREATE TABLE IF NOT EXISTS charges (order_id TEXT PRIMARY KEY, customer TEXT,
amount_cents INT, payment_id TEXT);""")
consumer = Consumer({"bootstrap.servers": "localhost:19092", "group.id": "billing",
"enable.auto.commit": False, "auto.offset.reset": "earliest",
"session.timeout.ms": 10000}) # a dead member is dropped in 10 s
dlq = Producer({"bootstrap.servers": "localhost:19092", "enable.idempotence": True})
assigned = []
consumer.subscribe(["order-events"], on_assign=lambda c, parts: assigned.extend(parts))
def parse(raw):
"""Raise ValueError for a message that can never succeed."""
event = json.loads(raw) # JSONDecodeError is a ValueError
if event["amount_cents"] <= 0:
raise ValueError(f"amount_cents must be positive, got {event['amount_cents']}")
return event
def to_dlq(msg, error, attempts):
headers = {"error": str(error), "error.class": type(error).__name__,
"source.partition": str(msg.partition()),
"source.offset": str(msg.offset()), "attempts": str(attempts)}
dlq.produce("order-events-dlq", key=msg.key(), value=msg.value(), headers=headers)
dlq.flush(10) # parked before we commit
def handle(msg):
key = msg.key().decode()
try:
event = parse(msg.value())
except ValueError as error:
print(f"{key} invalid ({type(error).__name__}), sent to order-events-dlq")
return to_dlq(msg, error, attempts=1)
if db.execute("SELECT 1 FROM processed WHERE event_id = ?",
(event["event_id"],)).fetchone():
print(f"{key} already applied, skipped") # cheap check before any payment
return
for attempt in range(1, MAX_ATTEMPTS + 1):
try: # the event id is the idempotency key
payment_id, replayed = charge(event["order_id"], event["amount_cents"],
idempotency_key=event["event_id"])
break
except PaymentTimeout as error:
if attempt == MAX_ATTEMPTS:
print(f"{key} failed {attempt} times, sent to order-events-dlq")
return to_dlq(msg, error, attempts=attempt)
backoff_ms = 200 * 2 ** (attempt - 1) # 200 ms, then 400 ms
print(f"{key} attempt {attempt} failed ({error}), retry in {backoff_ms} ms")
time.sleep(backoff_ms / 1000)
if replayed:
print(f"{key} provider returned the earlier {payment_id} for the same key")
if opts.crash_on == key:
print(f"{key} paid, crashing before billing.db and the commit", flush=True)
os._exit(1) # like kill -9: no clean-up at all
with db: # effect + dedup key, one transaction
db.execute("INSERT INTO processed VALUES (?)", (event["event_id"],))
db.execute("INSERT INTO charges VALUES (?, ?, ?, ?)", (event["order_id"],
event["customer"], event["amount_cents"], payment_id))
verb = "recorded" if replayed else "charged" # a replayed call moved no money
print(f"{key} {verb} {event['amount_cents']} cents")
idle = 0
while idle < 5: # stop after 5 quiet seconds
msg = consumer.poll(1.0)
if msg is None:
idle += 1 if assigned else 0 # still joining the group: keep waiting
continue
idle = 0
if msg.error():
raise SystemExit(msg.error())
handle(msg)
time.sleep(opts.delay)
consumer.commit(message=msg, asynchronous=False)
consumer.close().venv/bin/python consumer.py | sort -s -k1,1order-1001 charged 1000 cents
order-1002 charged 1250 cents
order-1003 charged 1500 cents
order-1004 attempt 1 failed (provider did not answer in 2 s), retry in 200 ms
order-1004 attempt 2 failed (provider did not answer in 2 s), retry in 400 ms
order-1004 charged 1750 cents
order-1005 charged 2000 cents
order-1006 charged 2250 cents
order-1007 invalid (JSONDecodeError), sent to order-events-dlq
order-1008 charged 1000 cents
order-1009 invalid (ValueError), sent to order-events-dlq
order-1010 attempt 1 failed (provider did not answer in 2 s), retry in 200 ms
order-1010 attempt 2 failed (provider did not answer in 2 s), retry in 400 ms
order-1010 failed 3 times, sent to order-events-dlq
order-1011 charged 1750 cents
order-1012 charged 2000 centsEvents from the three partitions are processed in parallel order, so the output is sorted by order id (sort -s keeps each order's own lines in sequence). order-1004 needed two retries and was charged on the third attempt. order-1010 used all three attempts and was parked. order-1007 and order-1009 were parked at once, without wasting retries, and no bad event blocked the rest.
These retries are blocking: while the consumer sleeps, the rest of that partition waits. For long outages, many systems publish the event to a delayed retry topic instead, so the main partition keeps moving. Either way the attempts are bounded.
04. Step 3: Inspect the dead letters
A DLQ is only useful if someone looks at it. The script reads the DLQ without committing anything and prints each event with its headers.
"""List the dead-letter topic, sorted by key, with the headers the consumer added."""
from confluent_kafka import Consumer
consumer = Consumer({"bootstrap.servers": "localhost:19092", "group.id": "dlq-inspect",
"enable.auto.commit": False, "auto.offset.reset": "earliest"})
consumer.subscribe(["order-events-dlq"])
rows = []
while (msg := consumer.poll(5.0)) is not None:
h = {k: v.decode() for k, v in msg.headers()}
rows.append(f"{msg.key().decode()} {h['error.class']:<15} attempts={h['attempts']}"
f" p{h['source.partition']}/{h['source.offset']} {h['error']}")
consumer.close() # read-only: commits nothing
print("\n".join(sorted(rows))).venv/bin/python inspect_dlq.pyorder-1007 JSONDecodeError attempts=1 p0/4 Expecting value: line 1 column 90 (char 89)
order-1009 ValueError attempts=1 p2/0 amount_cents must be positive, got -500
order-1010 PaymentTimeout attempts=3 p1/3 provider did not answer in 2 sThe headers tell two stories. The JSONDecodeError and ValueError events are bad data: the producer must be fixed and the events corrected or dropped. The PaymentTimeout event was valid; only the provider was down. Alert the owning team when the DLQ is not empty.
05. Step 4: Re-drive what can now succeed
Now the provider is healthy again (PROVIDER_FIXED=1 stops the stand-in timing out). Re-driving means publishing parked events back to the main topic. The script re-drives only transient failures and commits its own position in the DLQ, so running it twice does not re-drive the same event twice. Then run the consumer again.
"""Send dead-lettered events that failed for a transient reason back to order-events.
Invalid events stay parked: they need a data or code fix, not another try."""
from confluent_kafka import Consumer, Producer
consumer = Consumer({"bootstrap.servers": "localhost:19092", "group.id": "dlq-redrive",
"enable.auto.commit": False, "auto.offset.reset": "earliest"})
producer = Producer({"bootstrap.servers": "localhost:19092",
"partitioner": "murmur2_random", "enable.idempotence": True})
consumer.subscribe(["order-events-dlq"])
while (msg := consumer.poll(5.0)) is not None:
error_class = dict(msg.headers())["error.class"].decode()
if error_class == "PaymentTimeout":
producer.produce("order-events", key=msg.key(), value=msg.value())
producer.flush(10)
print(f"{msg.key().decode()} re-driven to order-events")
else:
print(f"{msg.key().decode()} left in order-events-dlq ({error_class})")
consumer.commit(message=msg, asynchronous=False) # never re-drive it twice
consumer.close().venv/bin/python redrive.py | sort
PROVIDER_FIXED=1 .venv/bin/python consumer.pyorder-1007 left in order-events-dlq (JSONDecodeError)
order-1009 left in order-events-dlq (ValueError)
order-1010 re-driven to order-events
order-1010 charged 1500 centsA re-driven event goes to the end of its partition, behind newer events for the same key. Here each order has one event, so that is harmless. If your events form a sequence per key (created, paid, cancelled), parking one and letting the next pass can apply them out of order: park the later events of that key too, or store a version per row and ignore older events.
06. Step 5: Crash mid-batch and restart
Publish six more orders and run the consumer with --crash-on order-1015. It takes that payment from the provider, then exits with os._exit(1) before it writes to billing.db. Like kill -9, this skips all clean-up. It is the most dangerous moment to crash: the money has moved and the consumer has no record of it. Then start it again.
.venv/bin/python produce_orders.py 1013 1018
.venv/bin/python consumer.py --crash-on order-1015 | tail -n 1
echo "exit ${PIPESTATUS[0]}"published order-1013 .. order-1018
order-1015 paid, crashing before billing.db and the commit
exit 1.venv/bin/python consumer.py | grep order-1015
bash lag.sh billingorder-1015 provider returned the earlier pay-1015-1 for the same key
order-1015 recorded 1000 cents
TOPIC PARTITION CURRENT-OFFSET LOG-END-OFFSET LAG
order-events 0 7 7 0
order-events 1 10 10 0
order-events 2 2 2 0The restart took a few seconds longer: the broker kept the crashed member in the group until session.timeout.ms (10 s here) passed, then reassigned its partitions. The event for order-1015 was delivered again, as at-least-once delivery promises. The processed table had no row for it, because the crash came before the database write, so the consumer called the provider again. The provider saw the same idempotency key and returned the payment it had already made, pay-1015-1, instead of taking the money a second time, so the consumer only records it. The lag is 0, so every event is committed. Now check both ledgers against what was published:
"""Check both sides against what was published (order-1001 .. order-1018): the
provider's ledger (money actually taken) and the billing table."""
import sqlite3
from confluent_kafka import Consumer
published = {f"order-{n}" for n in range(1001, 1019)}
provider = sqlite3.connect("provider.db")
calls = dict(provider.execute("SELECT outcome, count(*) FROM calls GROUP BY 1"))
paid = dict(provider.execute("SELECT order_id, count(*) FROM payments GROUP BY 1"))
billing = sqlite3.connect("billing.db")
charged = {r[0] for r in billing.execute("SELECT order_id FROM charges")}
billing.execute("ATTACH 'provider.db' AS provider")
unmatched = billing.execute("SELECT count(*) FROM charges WHERE payment_id NOT IN"
" (SELECT payment_id FROM provider.payments)").fetchone()[0]
consumer = Consumer({"bootstrap.servers": "localhost:19092", "group.id": "report",
"enable.auto.commit": False, "auto.offset.reset": "earliest"})
consumer.subscribe(["order-events-dlq"])
parked = set()
while (msg := consumer.poll(5.0)) is not None:
parked.add(msg.key().decode())
consumer.close()
print(f"provider calls: {dict(sorted(calls.items()))}")
print(f"orders paid once: {sum(n == 1 for n in paid.values())},"
f" paid twice or more: {sum(n > 1 for n in paid.values())}")
print(f"billing rows: {len(charged)}, without a matching payment: {unmatched}")
print("parked in the DLQ and not charged:", sorted(parked - charged))
print("lost (neither charged nor parked):", sorted(published - charged - parked)).venv/bin/python report.pyprovider calls: {'charged': 16, 'replayed': 1, 'timeout': 5}
orders paid once: 16, paid twice or more: 0
billing rows: 16, without a matching payment: 0
parked in the DLQ and not charged: ['order-1007', 'order-1009']
lost (neither charged nor parked): []The provider's ledger is the one that matters for money: 16 orders paid once, none paid twice, and one call for order-1015 that was answered from the key instead of charging. Every billing row matches a provider payment, the two invalid orders are parked, and none is lost. The proof comes from both systems' data, not from the consumer's own log lines.
07. Step 6: Watch lag during a burst
Lag tells you whether consumers keep up. Publish a burst of 600 orders and start a slowed-down consumer in the background (--delay 0.01 adds 10 ms per event). Check lag while it works and after it finishes.
.venv/bin/python produce_orders.py 2001 2600
.venv/bin/python consumer.py --delay 0.01 > burst.log 2>&1 &
echo $! > burst.pid
sleep 4
bash lag.sh billingpublished order-2001 .. order-2600
TOPIC PARTITION CURRENT-OFFSET LOG-END-OFFSET LAG
order-events 0 36 213 177
order-events 1 10 198 188
order-events 2 2 208 206Your numbers will differ with your machine. What matters is the shape: lag jumps when the burst arrives and then falls. If it keeps growing, consumers are slower than producers, and you need more consumer instances (up to the partition count) or faster processing. Wait for the background consumer to finish, then look again.
while kill -0 "$(cat burst.pid)" 2> /dev/null; do sleep 1; done
bash lag.sh billingTOPIC PARTITION CURRENT-OFFSET LOG-END-OFFSET LAG
order-events 0 213 213 0
order-events 1 198 198 0
order-events 2 208 208 0The committed offsets are now at the end of every partition. In production, export lag per partition as a metric and alert when it stays above a threshold for several minutes. Keep the broker running if you continue with lesson 5; otherwise remove it with docker rm -f mq-kafka.
08. Check your understanding
09. Apply it
This lab is most of the skill practice. To finish it, run two consumer instances in the same group while publishing, kill one with kill -9 in the middle of a batch, and repeat the report from step 5. Add a metric or a log line for DLQ size and consumer lag, and write down the alert thresholds you would use. As a stretch, move the retries to a delayed retry topic so the main partition keeps flowing during a long provider outage.
10. Review prompt
Without looking back, explain: how the consumer tells a transient failure from a permanent one; why retries need a bound and a backoff; what a dead-lettered event should carry; why the DLQ producer flushes before the offset commit; how re-driving can break per-key order; which two mechanisms stop a redelivered event from paying twice, and which crash window each one covers; and what consumer lag tells you during a burst.
References
- Apache Kafka 4.4 documentation: Consumer configs (session.timeout.ms, enable.auto.commit)
- Apache Kafka 4.4 documentation: Monitoring (consumer lag)
- confluent-kafka Python client documentation
- Enterprise Integration Patterns: Dead Letter Channel
- Enterprise Integration Patterns: Idempotent Receiver
- SQLite: Write-Ahead Logging
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.