Video in progress

Strong Middle 📨 Kafka and messaging

What happens to a failing message with this Spring Kafka configuration?

@Bean
DefaultErrorHandler errorHandler(KafkaTemplate<Object, Object> template) {
    var recoverer = new DeadLetterPublishingRecoverer(template);
    var handler = new DefaultErrorHandler(recoverer, new FixedBackOff(1000L, 3));
    handler.addNotRetryableExceptions(IllegalArgumentException.class);
    return handler;
}

@KafkaListener(topics = "orders", groupId = "billing")
void on(OrderEvent e) { billing.charge(e); }

The message is retried 3 times, 1 second apart (4 attempts in total), then it's sent to the orders.DLT topic with the same partition number and the offset is committed. An IllegalArgumentException goes straight to the DLT without retries.

📖 Answer

DefaultErrorHandler does blocking retry: when an error occurs, the container seeks back to that record and tries again, so the next messages in the partition wait. FixedBackOff(1000L, 3) means 3 additional attempts.

When the attempts run out, DeadLetterPublishingRecoverer kicks in. By default it sends to <topic>.DLT with the original partition number. So the DLT topic must have at least as many partitions as the original topic, otherwise publishing fails. The original topic, partition, offset and the exception stack trace are added to the headers, which makes later analysis easy.

Things to watch:

  • the total wait during retries must not exceed max.poll.interval.ms. Spring tries to keep polling during the backoff too, but be careful with long backoffs anyway;
  • if publishing to the DLT itself fails, the record gets processed again, so the DLT needs monitoring too;
  • retrying "unfixable" errors like IllegalArgumentException is pointless, so they go straight out. Deserialization errors are on this list by default.

To verify it, I usually write a test with @EmbeddedKafka: the listener always throws an exception, and the test waits for one message in the DLT.