Video in progress

Strong Junior 🧩 Microservices

Can a Kafka consumer receive the same message twice? How do you prepare for it?

Yes, in the default "at-least-once" mode that's normal: if the message was processed and the consumer goes down before the offset is committed, or a rebalance happens, the message comes again. The protection is to make the consumer idempotent, for example by storing the IDs of processed messages.

📖 Answer

When a duplicate arrives:

  • the consumer processed the message but went down before it could commit the offset;
  • processing took longer than max.poll.interval.ms, the consumer was removed from the group, and the partition moved to another one;
  • the producer retried and the broker wrote the message twice (when the idempotent producer is off).

The simplest protection is a table of processed messages:

@KafkaListener(topics = "payment-completed")
@Transactional
public void on(PaymentCompleted event) {
    if (processedRepo.existsById(event.eventId())) {
        return;                                  // already done
    }
    orderService.markPaid(event.orderId());
    processedRepo.save(new ProcessedEvent(event.eventId()));
}

Because the processed_event.event_id column is a PRIMARY KEY, two parallel runs also stop each other. What matters is that the business change and the "processed" mark are in one transaction.

Sometimes you can do it without a separate table: if the operation itself is naturally idempotent. For example, UPDATE orders SET status = 'PAID' WHERE id = ? AND status = 'PENDING' changes no rows the second time.

"Exactly-once" Kafka transactions work only for read-write inside Kafka; for writing to your database you still need idempotency.