Video in progress

What is wrong with the following idempotent consumer code, and how do you fix it?

@KafkaListener(topics = "payments")
public void onPayment(PaymentEvent e) {
    if (processedRepo.existsById(e.eventId())) {
        return;
    }
    accountService.credit(e.accountId(), e.amount()); // its own transaction
    processedRepo.save(new ProcessedEvent(e.eventId()));
}

The check and the write are separate steps without a transaction: two parallel consumers can both see the same message as "new". The dedup record must be written in the same transaction as the business change, through a unique constraint.

📖 Answer

There are two different problems here.

The first is a race. During a rebalance or a retry, one message can land on two consumers. Both call existsById at the same time, both get false, and the account is credited twice.

The second is no atomicity. credit committed, and the service died before save. The Kafka offset wasn't committed, the message comes again, the dedup table has no record, and it's credited twice again.

The fixed version:

@KafkaListener(topics = "payments")
@Transactional
public void onPayment(PaymentEvent e) {
    int inserted = jdbc.update("""
        INSERT INTO processed_event(event_id, processed_at)
        VALUES (?, now())
        ON CONFLICT (event_id) DO NOTHING
        """, e.eventId());
    if (inserted == 0) {
        return; // already processed
    }
    accountRepo.credit(e.accountId(), e.amount()); // inside this transaction
}

Now the dedup row and the balance change are in one DB transaction. The unique constraint resolves the race at the DB level: the second consumer gets 0 or waits until the first one commits.

Some subtle points:

  • eventId must be generated once on the producer side, so a retry doesn't produce a new one.
  • Don't let the processed_event table grow without limit: delete rows older than the window in which events can be redelivered (say 7–14 days).
  • If the consumer calls an external API (not the DB), this approach doesn't fully help: you need to send an idempotency key to the external side too.