Video in progress
The business demands "every payment must be processed exactly once", and the chain has Kafka, a DB and an external bank API. How do you respond?
In a distributed system there's no "exactly-once delivery", but you can get an "exactly-once effect": at-least-once delivery plus idempotency at every stage. Kafka transactions cover only the part inside Kafka; for the DB and the bank API you need an idempotency key and dedup.
📖 Answer
First I clarify the requirement: the business doesn't need "the message arrives once", it needs "the money is charged once". That's a different problem, and it can be solved.
I split the chain into pieces:
Kafka → Kafka. A transactional producer + read_committed: this part really is exactly-once.
Kafka → DB. A Kafka transaction doesn't cover the DB. The fix: store the offset or event ID in the same DB transaction as the business data. Or store the offset in the DB and seek() to it at startup, so you don't rely on the Kafka commit at all.
DB → bank API. The most dangerous part. On a network timeout, it's unknown whether the request reached the bank. So:
- the payment is first written to the DB in the
PENDINGstate with a uniqueidempotencyKey; - the bank API is called with that key (serious providers support this);
- retrying on a timeout is safe, because the bank recognizes the repeat;
- if the bank doesn't support idempotency, do a status query before retrying ("is there a payment with this ID?"), plus reconciliation.
Reconciliation is the last line of defense. Compare the internal ledger with the daily bank statement and send the differences to a separate queue. Every design leaves edge cases, and there must be a process that finds them.
This is what I tell the business: "Technical delivery may repeat, but every stage recognizes the repeat; the remaining rare cases are caught by the daily comparison". That's an honest promise that can be verified. Promising "Kafka gives exactly-once" ends, some day, with money charged twice.
Sign up to mark studied questions and save your progress.