Skip to content

    System Design

    Dead-Letter Queues and Retries

    Decide which failures to retry, how retries block or free a Kafka partition, what a dead letter must carry, and how to replay safely, with a runnable lab.

    By Published 13 min read

    Share

    Standard lessonintermediateKafka labBackend System Design

    Before this: Delivery Guarantees: At-Most-Once, At-Least-Once and Exactly-Once

    What you'll learn: By the end of this lesson you will be able to sort failures into transient and permanent, explain why retrying in place holds up every record behind the failing one, describe how retry topics free the partition and what they cost in ordering, list what a dead letter must carry to be diagnosable, design a safe redrive, and read the output of a lab that runs all three on a real in-process Kafka broker.

    A sorting office has a letter nobody can deliver. The first try, the neighbour is out, so the postman tries again tomorrow and the day after: that is a retry, and it is sensible because the neighbour will be back. A letter with no such address never will be deliverable, so after the allowed tries it goes into a labelled box with a note saying where it came from and why it failed. Someone looks at the box, fixes the address and sends the letter on. The box is a dead-letter queue. It exists so that one bad letter does not stop the van, and so that nothing is quietly thrown away.

    Message queues gives the working definitions, timeouts, retries, exponential backoff and jitter the backoff arithmetic, and delivery guarantees why a retry produces duplicates. The blog article How Confluent Kafka Works builds a small service with a retrying error handler and a dead-letter topic; this lesson does not repeat it. It asks what that setup does to the records behind a failing one, what the alternatives are, and how to get a dead letter back into service.

    Verified with the Spring for Apache Kafka documentation (the 4.2 pages; the lab runs 4.1.2), Apache Kafka clients 4.2.2, Spring Boot 4.1.2 and Java 25, on 2026-12-01.

    The core idea

    A retry handles a failure that may pass on its own; a dead-letter queue parks the records that will not, with enough context to diagnose and replay them. The design question is not "how many retries" but "what happens to everything behind the failing record".

    Three illustrations run through it, each labelled:

    • Minimal example: six payments, one that fails twice and passes, one invalid and one whose dependency stays down, in the lab's three runs.
    • Realistic example: ShopStream's capture worker when the ledger service is down, in "In practice".
    • Failure example: a redrive that replays a backlog all at once and knocks the dependency over again.

    Classify the failure first

    Retrying helps only when the next attempt can differ from the last. A transient failure (a dependency is briefly unavailable) is worth retrying. A permanent failure (the record is invalid, the field is missing) fails identically every time, so retrying only delays the dead letter and burns capacity.

    flowchart TD accTitle: Deciding what to do with a failed record accDescr: A failed record is classified. A permanent failure goes straight to the dead-letter topic. A transient failure is retried with backoff while attempts remain, and goes to the dead-letter topic when they run out. The dead-letter topic leads to an alert, inspection and a redrive after the fix. F["Handler failed"] --> C{"Can another attempt succeed?"} C -->|"no: permanent"| D["Dead-letter topic now"] C -->|"yes: transient"| R{"Attempts left?"} R -->|"yes"| B["Wait with backoff, try again"] R -->|"no"| D B --> F D --> A["Alert, inspect, redrive after the fix"]

    Figure 1. The decision for one failed record. How to read this: only the transient branch loops. The permanent branch leaves immediately, so a bad record costs one attempt, not a full retry budget.

    Spring for Apache Kafka encodes this in its DefaultErrorHandler. It treats certain exceptions as fatal and skips the retries for them, calling the recoverer on the first failure: DeserializationException, MessageConversionException, ConversionException, MethodArgumentResolutionException, NoSuchMethodException and ClassCastException, "since these exceptions are unlikely to be resolved on a retried delivery". You add your own with addNotRetryableExceptions. Without configuration the handler's default is to retry up to the documented FixedBackOff(0L, 9) with no delay and then log the failed record, which is ten tries with no pause and no dead letter, so set a back-off and a recoverer deliberately.

    Retrying in place blocks the partition

    The DefaultErrorHandler retries the failed record on the same consumer thread. When retries are not exhausted it seeks so that the failed record and all the remaining records of the poll are delivered again; when they are exhausted it recovers the record and commits its offset. The default back-off handler "simply suspends the thread until the back off time passes".

    sequenceDiagram accTitle: Retrying in place with a dead-letter topic accDescr: The container delivers a record to the listener, which fails. The error handler waits for the back-off interval, seeks back and delivers the same record again. On the last failure the recoverer publishes the record to the dead-letter topic and the container moves on to the next record. participant C as Container participant L as Listener participant H as Error handler participant D as Dead-letter topic C->>L: record p-5 (attempt 1) L--xH: fails H->>H: wait for the back-off, seek back C->>L: record p-5 (attempt 2) L--xH: fails C->>L: record p-5 (attempt 3) L--xH: fails, attempts exhausted H->>D: publish p-5 with failure headers H->>C: commit the offset of p-5, continue with p-6

    Figure 2. Blocking retries. How to read this: nothing behind p-5 in its partition is handled while the three attempts and the waits run. The partition resumes only after the record is dead-lettered.

    The cost is paid by innocent records. In the lab's run A there are two retries 50 ms apart, so p-2 and p-5 cause 4 pauses of 50 ms = 200 ms of idle partition (the arithmetic of the lab's own configuration). With a back-off of 1 s then 2 s, as in the blog's project, one failing record holds its partition for 3 s, and a burst of failures multiplies that. Retrying also keeps the thread away from poll(); the consumer documentation defines max.poll.interval.ms (default 300000 ms) as the maximum delay between calls to poll(), so total back-off must stay far below it. Spring also offers ContainerPausingBackOffHandler, which pauses the listener container until the back-off passes instead of suspending the thread.

    Non-blocking retries: retry topics

    The alternative moves the wait out of the consumer. In Spring's non-blocking retries, a failed message "is forwarded to a retry topic with a back off timestamp"; the retry topic's consumer checks the timestamp and, if it is not yet due, "pauses the consumption for that topic's partition", resuming when due. If the retry fails it moves to the next retry topic, and when attempts are exhausted it goes to the dead-letter topic. The main topic's consumer is free the moment the record is forwarded.

    Non-blocking retries: failed records leave the main consumerMain topic to Main consumer (poll); Main consumer to Retry topic (forward with due time); Retry topic to Retry consumer (poll); Retry consumer to Dead-letter topic (attempts used up)Main topic: payments-nbMain topicpayments-nbMain consumer: never waitsMain consumernever waitsRetry topic: payments-nb-retryRetry topicpayments-nb-retryRetry consumer: pauses until dueRetry consumerpauses until dueDead-letter topic: payments-nb-dltDead-lettertopicpayments-nb-dltpollforward with due timepollattempts used up

    Figure 3. A retry topic between the main consumer and the dead-letter topic. How to read this: a failure turns into a forwarded record with a due time, so later records of the main topic carry on. The cost is the one the documentation states: "By using this strategy you lose Kafka's ordering guarantees for that topic."

    The framework creates the topics. The default suffixes are -retry and -dlt, and since Spring for Apache Kafka 4.1 a fixed delay uses a single retry topic. The documentation's exponential example (1000 ms, multiplier 2, four attempts) creates main-topic-retry-1000, -2000, -4000 and main-topic-dlt. The two styles combine: since 2.8.4 you can retry a few times in place, then use retry topics. At the time of writing, non-blocking retries are not supported with batch listeners and cannot combine with container transactions.

    Approach The partition meanwhile Ordering Fits
    No retry, dead-letter at once Never waits Kept except for the parked record Failures that retrying cannot cure
    Blocking retries (in place) Waits for every attempt and pause Kept Short, rare transient errors; strict order
    Non-blocking retries (retry topics) Free Lost for that topic Slow or long-lived transient errors; order not required, or restored by a guard on the state

    What a dead letter must carry

    A dead letter that says only "it failed" cannot be diagnosed or replayed. Spring's DeadLetterPublishingRecoverer publishes the failed record to <originalTopic>-dlt by default, to the same partition, so the dead-letter topic needs at least as many partitions as the original. The record "retains all the headers of the original record", plus headers for the original topic, partition, offset, timestamp and consumer group and for the exception class, cause class, message and stack trace. A listener can also receive kafka_deliveryAttempt, counting from 1, if the container property deliveryAttemptHeader is set.

    Other brokers have their own forms. Amazon SQS uses a redrive policy whose maxReceiveCount is "the number of times a consumer can receive a message from a source queue before it is moved to a dead-letter queue"; it advises a longer retention on the dead-letter queue because for standard queues the original enqueue timestamp is kept, and warns against one on a FIFO queue if you must not break the order. RabbitMQ republishes to a dead letter exchange when a message is rejected, expires, exceeds a queue length limit or reaches a delivery limit, and records the reason in an x-death header.

    Redrive: getting a dead letter back

    A dead letter is waiting for a fix, not for deletion. A redrive reads the dead-letter topic and publishes each record back to its original topic and partition, taken from the headers. SQS offers a managed "dead-letter queue redrive"; on Kafka it is a small program you write. Three rules keep it safe:

    1. The consumer must be idempotent. A redriven record can already have had partial effects; see delivery guarantees.
    2. Order is gone. A redriven record arrives after everything that was processed meanwhile (run B in the lab). Guard state changes so a late event cannot move state backwards.
    3. Throttle it. Replaying a large backlog at once can recreate the load that caused the failures; load shedding and retry storms describes that failure.

    Build it: three runs on a real broker

    This is the minimal example, a lab you can run. The broker is a real Kafka broker started in the test JVM by @EmbeddedKafka from spring-boot-starter-kafka-test, with no Docker. The "payments" are strings and the handler's failures are scripted by record key, so every run is the same.

    Goal. See blocking retries hold up the records behind them, a permanent failure skip the retries, a dead letter carry its context, a redrive reorder the work, and retry topics free the partition.

    Setup. From the repository's examples/spring-labs folder:

    cd examples/spring-labs && ./gradlew :labs:kafka-dead-letter-retries:test

    One test drives the three runs, asserts the ordering claims below and compares its report with examples/spring-labs/golden/kafka-dead-letter-retries.txt. Run C waits through two 2.5-second retry delays. The code is under examples/spring-labs/labs/kafka-dead-letter-retries/src/main/java/buildingai/labs/deadletter/.

    How the model works. Six payments go to a one-partition topic. p-2 fails twice with a transient error and then passes; p-3 always fails with a permanent ValidationException; p-5 fails with a transient error until fix() is called, standing for "the bug is deployed and the dependency is back". Run A configures the error handler like this:

        public static DefaultErrorHandler errorHandler(KafkaOperations<String, String> template) {
            var recoverer = new DeadLetterPublishingRecoverer(template);
            var handler = new DefaultErrorHandler(recoverer, new FixedBackOff(RETRY_INTERVAL_MS, RETRIES));
            handler.addNotRetryableExceptions(PaymentHandler.ValidationException.class);
            return handler;
        }

    FixedBackOff(50, 2) means two retries 50 ms apart, so three attempts. Run B calls fix(), sends each dead letter back to its original topic and partition, and runs the consumer again. Run C uses retry topics on a Spring context, with three attempts and a 2500 ms delay, long enough that every first attempt finishes before any retry is due:

        @RetryableTopic(
            attempts = "3",
            backOff = @BackOff(delay = NonBlockingApp.RETRY_DELAY_MS),
            exclude = PaymentHandler.ValidationException.class,
            numPartitions = "1",
            replicationFactor = "1")
        @KafkaListener(id = "payments-nb-listener", topics = NonBlockingApp.TOPIC, groupId = NonBlockingApp.GROUP)
        public void onPayment(ConsumerRecord<String, String> record) {
            handler.handle(record.key(), record.topic());
        }

    Expected output, captured from a real run (Java 25.0.3, Spring for Apache Kafka 4.1.2, Kafka clients 4.2.2, 2026-12-01):

    Retries and dead-letter topics on a real Kafka broker (in-process, one partition per topic).
    Six payments are sent in order: p-1 p-2 p-3 p-4 p-5 p-6. Each journal line is one call of the handler, in the order it happened.
    p-2 fails twice (dependency down) then passes; p-3 is invalid (permanent); p-5 fails every time until the fix; the rest pass.
    
    Run A. Blocking retries: DefaultErrorHandler, FixedBackOff(50 ms, 2 retries), ValidationException not retryable, dead letters to payments-dlt.
      p-1 attempt 1 on payments: ok
      p-2 attempt 1 on payments: FAILED DependencyDownException
      p-2 attempt 2 on payments: FAILED DependencyDownException
      p-2 attempt 3 on payments: ok
      p-3 attempt 1 on payments: FAILED ValidationException
      p-4 attempt 1 on payments: ok
      p-5 attempt 1 on payments: FAILED DependencyDownException
      p-5 attempt 2 on payments: FAILED DependencyDownException
      p-5 attempt 3 on payments: FAILED DependencyDownException
      p-6 attempt 1 on payments: ok
      effects after run A: [p-1, p-2, p-4, p-6]
    
    Dead-letter topic payments-dlt after run A:
      key=p-3 value="pay p-3" dlt-offset=0 original=payments[0]@2 group=payments-workers cause=PaymentHandler$ValidationException
      key=p-5 value="pay p-5" dlt-offset=1 original=payments[0]@4 group=payments-workers cause=PaymentHandler$DependencyDownException
      headers on a dead letter: kafka_dlt-exception-cause-fqcn, kafka_dlt-exception-fqcn, kafka_dlt-exception-message, kafka_dlt-exception-stacktrace, kafka_dlt-original-consumer-group, kafka_dlt-original-offset, kafka_dlt-original-partition, kafka_dlt-original-timestamp, kafka_dlt-original-timestamp-type, kafka_dlt-original-topic
    
    Run B. The cause is fixed; every dead letter is sent back to payments (a redrive).
      p-3 attempt 2 on payments: ok
      p-5 attempt 4 on payments: ok
      effects after the redrive: [p-1, p-2, p-4, p-6, p-3, p-5]
    
    Run C. Non-blocking retries: @RetryableTopic, 3 attempts, 2500 ms apart, ValidationException excluded.
      topics created: payments-nb, payments-nb-dlt, payments-nb-retry
      p-1 attempt 1 on payments-nb: ok
      p-2 attempt 1 on payments-nb: FAILED DependencyDownException
      p-3 attempt 1 on payments-nb: FAILED ValidationException
      p-4 attempt 1 on payments-nb: ok
      p-5 attempt 1 on payments-nb: FAILED DependencyDownException
      p-6 attempt 1 on payments-nb: ok
      p-2 attempt 2 on payments-nb-retry: FAILED DependencyDownException
      p-5 attempt 2 on payments-nb-retry: FAILED DependencyDownException
      p-2 attempt 3 on payments-nb-retry: ok
      p-5 attempt 3 on payments-nb-retry: FAILED DependencyDownException
      dead letter: p-3 reached payments-nb-dlt
      dead letter: p-5 reached payments-nb-dlt
      effects after run C: [p-1, p-4, p-6, p-2]
    Part What it shows
    Run A, p-2 Three attempts, and p-4 is handled only after p-2's third: the waits are paid by the records behind.
    Run A, p-3 One attempt: the non-retryable exception goes straight to the dead-letter topic.
    Run A, p-5 Three attempts, then payments-dlt, at offsets payments[0]@2 and @4 for the two dead letters.
    Dead-letter headers The original topic, partition, offset and consumer group, and the exception class, message and stack trace.
    Run B After fix() the redriven p-3 and p-5 succeed, and the effects end [..., p-6, p-3, p-5]: order is not restored.
    Run C Three topics were created. All six first attempts happen before p-2's second, and p-2 finishes last: [p-1, p-4, p-6, p-2].

    Break it. Remove the addNotRetryableExceptions line in BlockingRetries.errorHandler: p-3 should then be tried three times instead of once, and the golden test fails. Restore the line and re-run the tests.

    Stretch. Add ContainerPausingBackOffHandler and compare. Give the redrive a cap with a header that counts redrives.

    What the lab leaves out. Several partitions, a real outage, long delays, an alert on dead-letter depth, deserialization failures and Confluent Cloud. The 2500 ms and 50 ms values are lab parameters, not recommendations.

    In practice: ShopStream's payment capture when the ledger is down

    This is the realistic example, an educational scenario on the course's running example, ShopStream; nothing in it describes a real company. Numbers other than the shared ShopStream figures are illustrative.

    This is a realistic scenario, not a case history.

    The situation

    ShopStream's capture worker (see delivery guarantees) writes each capture to a ledger service. At the shared peak of about 58 checkouts per second, a 20-minute ledger outage (illustrative) leaves 58 x 1,200 = 69,600 events. What should the worker do meanwhile?

    Starting architecture

    ShopStream capture worker with retry topics and a dead-letter topicorder-placed topic to Capture worker (poll); Capture worker to Ledger service (write capture); Capture worker to Retry topic (transient); Retry topic to Dead-letter topic (attempts used up)order-placed topicorder-placedtopicCapture worker: classifies errorsCapture workerclassifies errorsLedger service: down for 20 minLedger servicedown for 20 minRetry topic: delayedRetry topicdelayedDead-letter topic: alert on depthDead-lettertopicalert on depthpollwrite capturetransientattempts used up

    Figure 4. The worker's failure paths. How to read this: the red edge is the failing ledger. Transient failures leave through the retry topic; permanent ones go straight to the dead-letter topic; after the last attempt both end in the same place.

    Options considered

    Option Behaviour in the outage Problem
    A. Blocking retries, then dead-letter Partitions stall; most events end up dead-lettered Stalled partitions and a dead-letter backlog at once
    B. Retry topics with longer delays The main consumer keeps up Order is lost, and a long outage still exhausts the attempts
    C. Classify, then pause the consumer while the dependency is down Nothing is burned; records wait on the broker in order Needs a health signal and a resume rule
    D. Dead-letter everything, redrive later Simple A large replay hits the ledger at once

    The decision

    Classify first: invalid records go to the dead-letter topic at once. For an unreachable ledger, pause consumption rather than spend attempts (option C), with a retry topic for isolated slow responses. An alert fires on any dead letter, and a redrive tool replays at a capped rate to an idempotent consumer.

    Rollout and verification

    The team reproduces the lab's runs on a staging topic, then injects a ledger outage and watches the lag, the pause and the resume. In production it watches consumer lag, the records on the retry and dead-letter topics and the age of the oldest dead letter. Verification: a short outage produces lag but no dead letters, and a poison record produces exactly one.

    The 2 a.m. failure

    The page reads: the ledger is failing again an hour after it recovered. During the earlier outage 4,000 records (illustrative) were dead-lettered because pausing was not yet in place, and the on-call engineer ran a redrive that published all of them at once. The ledger, just recovered, took the burst, failed, and the redriven records dead-lettered again.

    The checks: the ledger's request rate against normal, the redrive job's publish rate, and the dead-letter headers of the looping records. The mitigation is stopping the redrive and restarting it throttled. The lasting fix is a rate cap and a redrive-count header, an alert on dead-letter depth, and a rule that the redrive waits for the dependency's health.

    Architect's notes

    • Classify before you configure counts. Permanent failures should cost one attempt.
    • Name what each retry style costs. Blocking keeps order and stalls the partition; non-blocking frees it and loses order.
    • A dead-letter topic is a queue someone owns: an alert, a retention longer than the source's and a replay path.
    • Redrive is a feature. Build it throttled, capped and idempotent before the first outage.
    • Check the version. Spring defaults and retry-topic naming are documented per release.

    Common mistakes

    • Retrying a permanent failure. The record fails identically every time.
    • Unbounded retries. FixedBackOff.UNLIMITED_ATTEMPTS is effectively an infinite loop that blocks the partition.
    • An unwatched dead-letter topic. Failures pile up silently.
    • Assuming order survives retry topics or a redrive. It does not.
    • Redriving everything at once. The replay becomes the next outage.
    • Too few partitions on the dead-letter topic under the default routing.

    Key takeaways

    • A retry is for failures that may pass; a dead-letter queue is for those that will not.
    • Retrying in place blocks the partition for every record behind the failing one.
    • Retry topics free the partition and give up topic ordering.
    • A dead letter keeps the original record and headers for the failure's context.
    • A redrive replays after the fix and needs an idempotent consumer and a throttle.
    • Alert on the dead-letter topic: a queue nobody reads is where data is forgotten.

    Practice exercises

    Exercise 1 (20 min). Classify a 503 from a payment API, a JSON record missing orderId, a database deadlock, a card decline and a timeout as transient or permanent, and give the handling for each.

    Exercise 2 (45 min). Run the lab. For run A, work out how long p-5 holds the partition with 1 s and 2 s waits instead of 50 ms.

    Exercise 3 (1 hour). In run C change the delay to 100 ms and re-run. Say what happens to the ordering assertions and why a delay shorter than the forwarding time makes the lab's claim unsafe.

    Exercise 4 (2 hours). Design ShopStream's redrive: its rate cap, the header that counts redrives, the idempotency key it relies on and what it does with a record that fails again.

    Official documentation

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments