Video in progress

Strong Middle 🧩 Microservices

How do you build an idempotent consumer, and is a "processed_messages" table enough?

Each message's unique ID is written to a table with a unique constraint, in the same transaction as the business change. If a duplicate arrives, the constraint fails and the message is skipped. But this only protects side effects that take part in the transaction.

📖 Answer

The broker gives an at-least-once guarantee, so it is normal for one message to arrive twice. The consumer must not notice.

@KafkaListener(topics = "payment-completed")
@Transactional
public void on(PaymentCompleted evt) {
    try {
        processedRepo.saveAndFlush(new ProcessedMessage(evt.eventId(), "order-service"));
    } catch (DataIntegrityViolationException dup) {
        return; // already processed
    }
    orderService.markPaid(evt.orderId());
}

Important points:

  • The producer assigns the ID and it travels with the message. A Kafka offset doesn't work as an ID: if the outbox resends, the offset will be different.
  • The insert and the business change are in one transaction. If they are separate, a crash in between again leads to a duplicate.
  • The table keeps growing, so clean out old rows after a period longer than the retention.

One catch: if the listener sends an email or calls an external API, those don't take part in the DB transaction. Such side effects should also go out through an outbox, or you should pass an idempotency key to that external system.

Sometimes a separate table isn't needed at all: natural idempotency like "if the status is PAID, do nothing" or UPDATE ... WHERE version = ? is enough.