Idempotency, Retries & Transactional Outbox
Why networks force at-least-once delivery, how Idempotency-Key deduplication stops double charges, and how the transactional outbox eliminates DB-plus-Kafka dual writes.
When a client sends POST /charges and gets a network timeout after 5
seconds, there are two indistinguishable realities:
- The request dropped on the way in — the server never saw it.
- The server committed the $50 charge, and the
200 OKresponse dropped on the way back.
No protocol can distinguish those two cases from the client’s side alone. That fundamental ambiguity is why distributed messaging reduces to three delivery semantics:
at-most-once
never retry · fast, silently drops writes
at-least-once
retry on timeout · never drops, sends duplicates
effectively-once
at-least-once delivery + idempotent handler
Break it: the dropped-response double charge
If a payment API is not idempotent, a single dropped 200 OK packet causes the
client to retry and charge the customer twice.
Trigger drop response & retry below in naive mode to watch a $50 order debit $100, then switch to idempotency key mode to see the server safely replay the cached result.
interactive · drop a response after commit to see double-charging vs safe key replay
status: DOUBLE CHARGE · debited $100 for one $50 orderswitch to idempotency key and retry
How Idempotency-Key works under the hood
Idempotency means repeating the same request produces the exact same
server state as running it once. GET, PUT, and DELETE are naturally
idempotent; POST (create charge, create order) is not — unless the client
supplies a unique Idempotency-Key (typically a UUID generated when the user
clicks Checkout).
To make it airtight under concurrent retries, the server stores the key inside the same ACID database transaction as the business mutation:
BEGIN; -- 1. Claim the key (unique index fails fast on duplicate/concurrent retry) INSERT INTO idempotency_keys (key, status) VALUES ($key, 'in_progress');
-- 2. Execute the business mutation atomically UPDATE accounts SET balance = balance - 50 WHERE id = $acct; INSERT INTO charges (id, account_id, amount) VALUES ($cid, $acct, 50);
-- 3. Cache the exact HTTP response for future retries UPDATE idempotency_keys SET status = 'completed', response_body = $json WHERE key = $key;COMMIT;- Retry after completion:
INSERThits the unique key constraint, so the server readsresponse_bodyand returns the original200 OKwithout touchingaccounts. - Concurrent in-flight retry: if the first request is still
in_progress, return409 Conflict(or wait briefly) so two workers never execute the charge simultaneously. - Key expiry: prune keys after 24–72 hours via TTL or a daily partition drop so the table stays small.
Retries done right: exponential backoff + jitter
Idempotency makes retries safe, but naive tight-loop retries can still take down a recovering service (a retry storm).
- Exponential backoff: double the delay on each attempt (
100ms,200ms,400ms,800ms), capped at a ceiling (e.g.10s). - Full jitter: randomize each sleep between
0and the backoff ceiling so 10,000 clients that failed together do not wake up and hammer the server at the exact same millisecond. - Retry budget: cap retries to 10% of total traffic; only retry transient
errors (
429,502,503,504, network timeouts), never400or402.
The dual-write bug & Transactional Outbox
Now suppose your checkout service must do two things when an order succeeds:
- Insert the row into PostgreSQL (
orderstable). - Publish an
OrderCreatedevent to Kafka so shipping and email run.
Writing to both directly is a dual write, and it always fails in one of two ways:
- DB first, then Kafka: PostgreSQL commits, then the process crashes before Kafka acknowledges. The customer paid, but shipping never hears about it.
- Kafka first, then DB: Kafka publishes
OrderCreated, then PostgreSQL rolls back. Shipping mails a free item for an order that does not exist.
The fix is the outbox pattern: never publish to Kafka inside the HTTP
request path. Instead, write the domain row and an outbox_events row in
the same single-database transaction:
BEGIN; INSERT INTO orders (id, user_id, total) VALUES ($oid, $uid, 50); INSERT INTO outbox_events (id, topic, payload) VALUES ($eid, 'orders.created', $json);COMMIT;A separate relay process (either a polling worker or a Change Data Capture tool
like Debezium tailing the database’s WAL) reads committed rows from
outbox_events, publishes them to Kafka, and marks them sent.
note
The outbox relay guarantees at-least-once delivery to Kafka (if the relay
crashes after publishing to Kafka but before marking the row sent, it will
publish the same event_id again). That is why downstream Kafka consumers
still deduplicate by event_id — completing the effectively-once chain end to
end.
Where this shows up in system design
- Stripe Payment IntentsClients attach an `Idempotency-Key` header on every POST; Stripe stores the key and replays the exact response for 24 hours on retries.
- Webhook delivery pipelinesWebhook dispatchers use at-least-once delivery with exponential backoff + jitter and an `event_id` so receivers deduplicate safely.
- E-commerce order -> Kafka publishOrders and `outbox_events` commit atomically in PostgreSQL; Debezium streams the WAL to Kafka to eliminate dual writes.
- Ride-hailing dispatch retriesPoor cellular links drop booking responses; client-generated trip request IDs stop a rider from accidentally summoning two cars.
Check yourself: system design scenarios
interactive · pick the right reliability pattern for each scenario
1. Mobile checkout over spotty 4G
payment mutation · client retries · zero double-charges
Users tap 'Pay $50' in a subway tunnel. The server commits the charge, but the 200 OK response drops and the mobile SDK automatically retries 3 seconds later.
Select an option to check the trade-off.
2. Order DB + Kafka notification consistency
PostgreSQL + Kafka · no lost events · no ghost events
When an order is placed, you must insert a row into PostgreSQL and publish an OrderPlaced event to Kafka. During deploys, pods occasionally crash right between the two calls.
Select an option to check the trade-off.
3. Recovering from a 10-second downstream outage
5,000 callers · avoid thundering retry storm · fast recovery
A downstream tax API goes down for 10 seconds while 5,000 checkout requests are in flight. Every caller is configured to retry failed requests.
Select an option to check the trade-off.
idempotencyreliability
Property where repeating the exact same request multiple times produces the same final state as executing it once.
outbox patternmessaging
Writing a domain change and its outgoing event to the same DB transaction, then relaying the event asynchronously to avoid dual writes.
WALstorage
Write-Ahead Log: an append-only disk log written before mutating in-memory structures so crashes never lose committed writes.