Video in progress

Staff 🌱 Spring

You're asked for "exactly-once" processing with Spring and Kafka. How do you explain it, and how do you approach it in practice?

Kafka's exactly-once guarantee only works inside Kafka: reading, processing and writing back to Kafka in one transaction. If the result goes to an external database or API, "exactly-once" is really at-least-once delivery plus idempotent processing. In practice that's what I design for.

📖 Answer

Inside Kafka this is consume-transform-produce: in Spring Kafka it means transactional.id, KafkaTransactionManager, and isolation.level=read_committed on the consumer. The consumed offset and the produced messages are committed in a single Kafka transaction.

But the most common case involves an external system. The consumer reads a message, writes to the database, then commits the offset. If the application dies after the database write but before the offset commit, the message comes again. You can't eliminate that, you can only make it harmless:

@KafkaListener(topics = "payments")
@Transactional
public void on(PaymentEvent e) {
    if (!processed.tryInsert(e.eventId())) return;   // unique(event_id): a duplicate
    ledger.apply(e);                                  // in the same DB transaction
}

That is, the "processed events" table and the business change are in one DB transaction. From the point of view of the external effect, this is practical exactly-once.

Other points:

  • Ordering exists only within a partition. Events for one account should go to the same partition with the same key.
  • On errors, use a bounded retry with DefaultErrorHandler, then a dead letter topic. A "poison" message shouldn't halt a whole partition.
  • If processing takes longer than max.poll.interval.ms, the consumer is kicked out of the group and the message is handed to another one.
  • On the producer side, enable.idempotence=true (the default in newer clients) removes retry duplicates.

To the business I say it like this: "Every payment is counted exactly once", and that is guaranteed by our design, not by Kafka.