Video in progress

Strong Middle 🏗️ System design

What is a poison message, and how does a dead letter queue handle it?

A poison message is one that makes the consumer fail every time (broken JSON, an ID that isn't in the database). It blocks the queue with endless retries. After a few attempts you need to move it to a dead letter queue and carry on with the other messages.

📖 Answer

In Kafka this hurts especially: there's order within a partition, and if the consumer gets stuck on one message, all the messages after it wait too. Lag grows, and the log has the same stack trace thousands of times.

In Spring Kafka:

@Bean
DefaultErrorHandler errorHandler(KafkaTemplate<Object, Object> template) {
    var recoverer = new DeadLetterPublishingRecoverer(template); // orders -> orders.DLT (Spring Kafka 3.x)
    var handler = new DefaultErrorHandler(recoverer, new FixedBackOff(1000L, 3));
    handler.addNotRetryableExceptions(
            DeserializationException.class, IllegalArgumentException.class);
    return handler;
}

Two kinds of errors are separated here:

  • transient (DB busy, timeout) — retrying makes sense;
  • permanent (broken format, fails validation) — retrying is pointless, straight to the DLT.

To catch deserialization errors you also need ErrorHandlingDeserializer — otherwise the error comes out during poll, before it reaches the listener.

You must have a plan for working with the DLT:

  • the reason and the original topic/offset are added to the message as headers (Spring does this automatically);
  • an alert on the DLT size;
  • a tool to resend from the DLT to the original topic after the bug is fixed.

One catch: if ordering matters (the events of a single order), moving one message to the DLT and processing the following ones can corrupt state. In a case like that you have to pause the following messages for that key too, or resolve it by hand.

In RabbitMQ there are the dead-letter exchange and x-delivery-limit (in quorum queues) for this.