Video in progress

Strong Junior 📨 Kafka and messaging

Where is the bug in this listener code that leads to lost messages?

@KafkaListener(topics = "invoices", groupId = "mailer")
public void onInvoice(InvoiceEvent event) {
    executor.submit(() -> {
        pdfService.render(event);
        mailService.send(event.customerEmail());
    });
}

The listener hands the work off to another thread and returns immediately. The container treats that as "processed successfully" and commits the offset; if the background work fails or the pod goes down, the message never comes back.

📖 Answer

For the Spring container, the fate of a message depends on what the listener method does: it returned normally, so it's OK and the offset is committed. Here the method returns in a millisecond, while the real work may not even have started yet.

As a result:

  • if render throws an exception, nobody knows; neither retry nor DLT kicks in;
  • if the pod is shut down during a deploy, the messages waiting in the executor queue are lost;
  • the order inside the partition breaks too.

The correct version is to do the work synchronously on the listener thread:

@KafkaListener(topics = "invoices", groupId = "mailer", concurrency = "3")
public void onInvoice(InvoiceEvent event) {
    pdfService.render(event);
    mailService.send(event.customerEmail());
}

If you need more parallelism, increase concurrency and the partition count. If you truly need asynchronous processing, you can use AckMode.MANUAL and call ack.acknowledge() when the work is done, but that's a much more complicated path.