IDEMPOTENCY & EXACTLY-ONCE

At-least-once delivery plus an idempotent handler is as good as it gets

L215 MINDISTRIBUTED SYSTEMS
PREDICT

The client sends an idempotency key, one id per checkout that it reuses on every retry. The server looks up the key, charges the card, then records the key. It crashes right after the charge. The client retries with the same key. What happens?

A timeout tells the client nothing. The request may never have arrived, or the server may have charged the card and the response got lost. The client has to retry, so delivery is at-least-once. Exactly-once delivery does not exist; exactly-once effect does.

You get it by making the handler idempotent. The client attaches one key per logical operation and reuses it on every retry. The server stores key → result and answers repeats from the store. The catch: the check and the record must not leave a window where a crash or a duplicate sees no key.

▶ SIMULATION
CLIENT
order: r1, $50
attempts: 0
response: —
idle
LEDGER + KEY STORE
charges for r1: 0
billed: $0
key store: no key store
mode: naive
SERVER
status: idle
in flight: —
idle
✓ each request id is applied at most once
SCHEDULE
01[CLIENT]CLIENT: POST /charge $50, request id r1 (attempt 1)
02[SERVER]SERVER: charge the card $50 (skipped if the key store already has r1)
03[SERVER]SERVER: send 200 OK
04[NET]NET: response lost — client times out
05[CLIENT]CLIENT: timed out — retry r1 (same request id)
06[SERVER]SERVER: charge the card $50 (skipped if the key store already has r1)
07[SERVER]SERVER: send 200 OK
08[CLIENT]CLIENT: receive response
Start of naive retry scenario. 8 steps.
// handler
function charge(req) {
  const result = card.charge(req.amount);   // side effect
  return result;                            // response lost -> client retries -> charged again
}

The invariant strip tracks each request id is applied at most once. NAIVE RETRY breaks it on the second charge. IDEMPOTENCY KEY holds for a lost response, then CRASH BETWEEN CHARGE AND RECORD breaks it again. RESERVE, THEN ONE TRANSACTION survives the same crash and the same retry.

Note the switch in that last scenario: the charge becomes a ledger row in your own database, so it can share a transaction with the key. A charge on a card network cannot sit inside your transaction. For that, pass the key downstream so the payment provider deduplicates too, or record the intent locally and send it from an outbox (see the last card). One more simplification: the sim lets a retry reclaim a pending key the moment its owner crashes. A real server cannot see that crash, so it puts a timeout or lease on the reservation, and a slow owner that outlives it is the leases-and-fencing problem again.

BREAK IT NOT YET

The key store is deployed and the retry is served from it. Inject a duplicate delivery of r1 (or a crash) at a point where it still charges the card twice.

GOAL: r1 is charged more than once

FIX IT NOT YET

Make handle charge each request id exactly once. The grader replays a request after success, crashes the server at every point and retries, and delivers a duplicate to a second worker, trying every interleaving of the two. Each worker gets its own transaction; a reserve of a key that another open transaction has written waits for that transaction to finish, as a unique index would.

Mental model:

the network gives you at-least-once; you turn it into exactly-once effect with an idempotency key that is reserved before the side effect and committed atomically with its result. A key checked in one step and written in another is check-then-act across a database, and it fails the same way.

IN PRODUCTION

Payment APIs (an Idempotency-Key header), message consumers that dedupe by message id, Kafka's idempotent producer, webhook receivers, and any job queue with retries. The symptom: duplicate orders, double charges or double emails after a timeout or a redeploy.

IN INTERVIEWS

“How do you make a payment endpoint safe to retry?” Say that the client generates the key, the server reserves it with insert-if-absent before the side effect, stores the result in the same transaction, returns the stored result on a repeat and a 409 while a first attempt is in flight, and that external side effects go through an outbox that passes the key downstream.

RECALL CARDS Tap to flip. They join your review deck when you mark the lesson complete.

USED IN

Chapters that build on this lesson.

NEXT: CAPSTONE: REPLICATED KV UNDER PARTITION →