Video in progress
How true is the claim "Kafka gives you exactly-once", and how do you get it end to end?
Kafka transactions give exactly-once only in a "read from Kafka, write to Kafka" chain. If an external DB or API is involved, the real guarantee is at-least-once delivery plus idempotent processing, so the effect of the result happens once.
📖 Answer
An idempotent producer (enable.idempotence=true) removes duplicate writes to the broker. Transactions combine the consumer offset and the outgoing messages into one atomic commit. processing.guarantee=exactly_once_v2 in Kafka Streams uses this. It really works, but only inside Kafka.
What happens if a consumer reads a message and writes to Postgres? The DB commit went through, and the pod died before the offset commit. After a rebalance the message comes again. Kafka knows nothing about that DB write.
End-to-end options:
- Idempotent writes. Give the result record a natural key:
INSERT ... ON CONFLICT (event_id) DO NOTHINGor anUPSERT. The simplest and most widely used way. - Store the offset in the DB. The result and
(partition, offset)are written in a single DB transaction; on startup the consumer usesseek()to begin from the offset in the DB. It doesn't rely on the Kafka offset commit at all. - A processed-events table. Save
event_idin the same transaction as the business record, then skip duplicates. You need to clean the table periodically.
@Transactional
public void handle(PaymentCaptured e) {
int inserted = jdbc.update(
"INSERT INTO processed_events(id) VALUES (?) ON CONFLICT DO NOTHING", e.id());
if (inserted == 0) return; // already processed
ledger.credit(e.merchantId(), e.amount());
}
If it's an external HTTP API, you use their idempotency key; if they don't have one, exactly-once doesn't exist at all, and you have to say so openly.
In an interview I swap the term: not "exactly-once delivery" but "effectively-once processing". Making this an architecture rule, every consumer is idempotent, is far more reliable than tying your guarantees to a single technology.
Sign up to mark studied questions and save your progress.