Idempotency Key and Transactional Outbox: The Exactly-Once Myth
Why retries create duplicate charges and lost events, and how idempotency keys, a transactional outbox and idempotent consumers give an exactly-once effect.
New12 min read

An idempotency key is a unique id the client creates once for an operation and sends again on every retry, so the server can tell "a new payment" from "the same payment, asked twice". Together with the transactional outbox pattern and an idempotent consumer, it is how real systems stop a network timeout from turning into a double charge, a lost event or a second shipment.
This guide is for backend developers, especially Java and Spring developers, who build payment, order or booking flows, or who are preparing for a system design interview where "what happens on a retry?" is a standard follow-up. You will learn why retries create duplicates, what the three delivery guarantees promise, why exactly-once delivery to another system is a myth, and how to get an exactly-once effect anyway. The code and numbers come from the companion labs of Book 2 of the TechTribers Guide Series.
In this guide
- Why retries create duplicates
- Delivery guarantees: at most once, at least once, exactly once
- Idempotency keys on write APIs
- The dual-write problem
- The transactional outbox and its relay
- Idempotent consumers
- What the lab measured
- How to say it in the interview
From the book: this guide is based on building block 8 and Case 10 of System Design 2026: Classic + AI Era, where 18 case studies are worked step by step, with runnable Java labs. Read the free 5-page sample on the book page.
Why retries create duplicates
The nastiest network failure comes after the server has finished the work, when only the reply is lost. The client sees a timeout and cannot tell "never arrived" from "done, answer lost", so it tries again. For a read, that is harmless. For a UPI-style payment, a blind retry debits the payer a second time.
Picture a courier counter. If you hand in a parcel with a docket number the clerk has already booked, the clerk simply says so and books nothing new. That makes booking idempotent: repeating it changes nothing after the first time. The docket number plays the role of the idempotency key, created once for the operation and repeated on each retry.
Some calls are idempotent by nature, such as a read or "set the status to PAID". The ones that need a key are writes where a repeat changes the result: payments, orders, bookings.
Delivery guarantees: at most once, at least once, exactly once
Retries also happen between services and a message broker. The Apache Kafka documentation names three delivery guarantees in its design section on message delivery semantics:
- At most once: messages may be lost but are never redelivered.
- At least once: messages are never lost but may be redelivered.
- Exactly once: each message is processed once and only once.
Kafka's default is at least once. You can get at most once by turning off producer retries and committing the consumer offset before processing a batch. Kafka also has an idempotent producer, so a producer resend does not create a duplicate entry in the log, and transactions that write to several partitions atomically. Those tools give exactly-once processing inside Kafka.
When your consumer writes somewhere else, such as a database or a bank, the same Kafka docs say that exactly-once delivery for other destination systems generally requires cooperation with those systems. They describe two ways: a two-phase commit between the consumer position and the output (which many systems do not support), or storing the consumer's position in the same place as its output, so both are updated together or not at all.
That is the "exactly-once myth": no broker can promise on its own that a side effect in another system happens exactly once. What you can build is an exactly-once effect: at-least-once delivery plus a receiver that recognises repeats.
Idempotency keys on write APIs
The book's payment case study (a UPI-style ledger) makes the idempotency key part of the API contract. The payment endpoint is POST /api/v1/payments with an Idempotency-Key header. It answers 201 with the payment pending, or 409 when a key is reused for a different request.
Claim the key in the same transaction
The key is a unique column on the ledger's journal_entry table. A request "claims" it with an insert that does nothing on conflict. In PostgreSQL, ON CONFLICT DO NOTHING skips the insert when the unique constraint already holds that value, and RETURNING only returns rows that were actually inserted. An empty result means "this key was used before".
/** Inserts the entry; null when the key was used before. */
private Long claim(String key, String description) {
List<Long> id = jdbc.queryForList("""
INSERT INTO journal_entry (idempotency_key, description)
VALUES (?, ?)
ON CONFLICT (idempotency_key) DO NOTHING
RETURNING id""", Long.class, key, description);
return id.isEmpty() ? null : id.getFirst();
}
/** Answers a retry with the stored result of the first request. */
private TransferResult replay(Transfer t) {
Map<String, Object> first = jdbc.queryForMap("""
SELECT id, description, status FROM journal_entry
WHERE idempotency_key = ?""", t.idempotencyKey());
if (!t.describe().equals(first.get("description"))) {
throw new IdempotencyConflictException(t.idempotencyKey());
}
return new TransferResult((Long) first.get("id"),
Outcome.valueOf((String) first.get("status")), true);
}The important detail is where this runs. In lab-ledger, the claim, the account locks, the postings and the stored outcome share one database transaction. If the transfer fails, the claim rolls back with it. If it commits, the key and the money movement are saved together, and a later retry gets the first answer back, even a rejection for insufficient funds.
Same key, different body
A key reused with another amount is a client bug, not a retry. The lab compares the stored description with the new request and throws IdempotencyConflictException, which an API answers with 409. Otherwise a buggy client could get a "success" for a payment that never happened.
Timeouts stay pending
Towards the bank, the case study treats a timeout as "pending until the bank is asked", not as a failure. The bank's signed callback can also arrive twice, so the callback endpoint answers 200 for a repeat too.
In the book's lab, 20 concurrent calls with one key produced exactly 1 journal entry. In a larger run (1,106 requests: 1,000 transfers plus 106 retries with the same key), all 106 retries were answered from the ledger, 1,000 journal entries were written and there were 0 duplicate entries. The book also notes that Stripe's API works this way: it takes an idempotency key on writes and, for API v1, replays the saved first response on every retry.
The dual-write problem
Other services, such as shipping, need to hear about each order. The obvious code saves the order in PostgreSQL and then publishes an OrderPlaced event to Kafka. That is a dual write: two systems, no shared transaction.
- Commit, then publish: if the process dies between the two, the order exists but the event is lost. Shipping never hears about it.
- Publish, then commit: if the commit fails after the publish, the event is out but the order is not. That is a ghost event for an order that does not exist.
No ordering of the two calls fixes this, as the lab results below show.
The transactional outbox and its relay
The transactional outbox pattern removes the second system from the request. Instead of publishing to Kafka, the service writes the event as a row in an outbox table, in the same transaction as the order. Either both rows commit or neither does.
public long placeOrder(String topic, String customer,
long amountPaise) {
return tx.execute(status -> {
long orderId = jdbc.queryForObject("""
INSERT INTO orders (customer, amount_paise)
VALUES (?, ?) RETURNING id""",
Long.class, customer, amountPaise);
jdbc.update("""
INSERT INTO outbox (topic, msg_key, payload)
VALUES (?, ?, ?)""",
topic, String.valueOf(orderId),
payload(orderId, amountPaise));
return orderId; // both rows commit, or neither does
});
}Each outbox row gets a message_id (a UUID with a unique constraint) and a nullable sent_at. The message key is the order id. Kafka writes events with the same key to the same partition and keeps their order within a partition, as its introduction explains, so all events for one order stay in order.
The relay
A separate relay moves rows from the outbox to Kafka. In the lab it runs one loop step per transaction:
- Select a batch of unsent rows with
FOR UPDATE SKIP LOCKED. - Send each row to Kafka, with the message id as a record header.
- Wait until the broker has acknowledged every record (the lab also sets
spring.kafka.producer.acks=all). - Mark the batch as sent and commit.
SKIP LOCKED makes PostgreSQL skip rows another transaction has locked. The PostgreSQL docs suggest it for queue-like tables with several consumers, which is what an outbox is: several relays can run, each taking a different batch.
If the relay dies after step 3 and before step 4, the records are in Kafka but the rows are still unsent, so the next run sends them again. The outbox never loses an event, but it can send one twice: delivery is at least once, by design. The book compares two ways to run the relay:
- Outbox with a polling relay: plain SQL that commits with the order. The cost is polling load and some publish lag. The book's pick for most services.
- Outbox with change data capture (CDC): a tool reads the database log instead of polling. No polling, but one more system to run. The pick for high volume.
Idempotent consumers
The outbox can re-send and a consumer group can be rewound, so the consumer must handle repeats. An idempotent consumer records the id of every message it applies, in the same transaction as the side effect.
/** Runs inside one DB transaction; false = a duplicate, skipped. */
boolean apply(String messageId, long orderId) {
int fresh = jdbc.update("""
INSERT INTO processed_messages (message_id)
VALUES (?::uuid)
ON CONFLICT (message_id) DO NOTHING""", messageId);
if (fresh == 0) {
return false; // seen before: no side effect
}
jdbc.update("INSERT INTO shipments (order_id) VALUES (?)",
orderId);
return true; // marker and shipment commit together, or neither
}This is the Kafka docs' "store it with the output" idea, applied to one database. If the shipment insert fails, the marker rolls back too and the next delivery tries again. If both commit, any later copy changes no row. The effect happens once because of this check, not because of the broker.
The idempotency key and the processed-message id are the same idea at two boundaries: one guards against client retries, the other against broker redelivery.
What the lab measured
The book's lab-outbox runs against real PostgreSQL and Kafka containers and injects crashes at named points. These are the book's lab numbers, measured on its build machine; your run may differ.
- Redelivery: 200 orders. The relay crashed after publishing 50 and re-sent them on restart, so 250 deliveries. The idempotent consumer made 200 shipments; a naive consumer with no "seen before?" check made 250, so 50 duplicates.
- Both consumer groups were then rewound to offset 0: 500 deliveries. Still 200 shipments for the idempotent consumer; 300 duplicates for the naive one.
- Dual write versus outbox: 200 requests each, with a 1-in-10 injected crash. Both dual writes saw 15 crashes: commit-then-publish lost 15 events, publish-then-commit invented 15 ghost events. The outbox, with its relay crashing at the same odds, lost 0 and invented 0. Its relay sent 230 records for 200 events: re-sends after its crashes, which the consumer deduplicated.
How to say it in the interview
In a design round, three points are enough: the order and its event commit together through an outbox table, with a relay publishing to Kafka; because that gives at-least-once delivery, the consumer saves each message id alongside its side effect and ignores repeats; and the price is one more table and slight publish lag, paid for zero lost or ghost events.
For a payment API, add the key: the client sends an idempotency key, the server claims it as a unique column inside the same transaction as the ledger postings, and a retry gets the first answer. The book lists "the key is part of the transaction" among what interviewers listen for, and treating a timeout as a failure and retrying blindly as a red flag. Two more mistakes follow from this article: checking the key in a separate step, and claiming the broker delivers exactly once into your database.
When should you skip all this? When the call is already idempotent, when losing the odd event is fine (a view counter, a log line), or when the state and its reader share one database, where a single transaction is enough.
Go deeper
Book 2, System Design: Classic and AI Era, covers this in building block 8, "Idempotency, retries and the exactly-once myth", and puts it to work in Case Study 10, "Payment system: a UPI-style ledger". Its deep dives cover double-entry posting, retries and timeouts with the idempotency key, and nightly reconciliation with the bank. With the companion labs lab-outbox and lab-ledger you run the crash and retry tests yourself, then practise follow-ups such as refunding half a payment.
See the book on its product page, which has a free 5-page sample.
Related reading
- Kafka consumer groups, partitions and rebalancing
- Spring Boot Kafka example
- Back of the envelope estimation for system design
FAQ
What is an idempotency key?
A unique value the client generates once per operation, such as one payment, and sends with every retry. The server stores it with the result, usually in a unique column, so a repeat returns the first result instead of doing the work again.
Is exactly-once delivery possible in Kafka?
Inside Kafka, yes: the idempotent producer and transactions give exactly-once processing between Kafka topics. To another system, such as a database or a bank, the Kafka docs say it generally requires that system's cooperation. In practice you use at-least-once delivery and make the consumer idempotent, so the effect happens once.
What is the transactional outbox pattern?
The service writes the event as a row in an outbox table, in the same database transaction as the business data. A separate relay publishes unsent rows to the broker and marks them sent. A crash can cause a re-send, but never a lost or ghost event.
What is the difference between at-least-once and exactly-once delivery?
At-least-once never loses a message but may deliver it twice; exactly-once processes each message once and only once. Most systems get an exactly-once effect from at-least-once delivery plus deduplication on a message id.
Where should an idempotency key be stored?
In the same database and the same transaction as the change it protects. In the book's payment lab it is a unique column on the journal entry, claimed with an insert that does nothing on conflict, so the key and the postings commit together or not at all.






