Did it work?
You press a button that sends a delivery lift, and each trip costs money. The lift goes, but the light doesn't come on. Did it work? You can't tell, so you press again. A careless lift sends a second trip, and you pay twice.
Lost replies and retries
When a request times out, the client can't know whether it failed before, during or after the server did the work. The only safe reaction is to retry, and that's only safe if the operation is idempotent: doing it twice has the same effect as doing it once.
GET, PUT (set to a value) and DELETE are idempotent by design. "Add ยฃ20" and most POSTs are not, so a retry
can double-charge, double-ship or double-book.
A ticket for each press
A smart lift gives each press a ticket number. If the same ticket comes in again, the lift knows it already went, and just turns your light on. A new trip gets a new ticket.
Idempotency keys
The client generates a unique key per logical operation (a UUID) and sends it, often in an Idempotency-Key header,
on every retry of that operation. The server:
- looks the key up; if it's done, returns the stored response,
- otherwise does the work and stores the key with its result in the same transaction,
- handles two concurrent requests with the same key, for example with a unique constraint.
This is how payment APIs like Stripe make POST safe to retry.
The same letter twice
The post room has the same problem. If the clerk's "got it" goes missing, the letter is delivered again. So the clerk keeps a done list, and anything already on it is just acknowledged.
Exactly-once processing
Message brokers can't guarantee exactly-once delivery over an unreliable network; they offer at-least-once (redeliver until acknowledged). Consumers get an exactly-once effect by being idempotent: record processed message ids alongside the work, use upserts instead of inserts, or make updates conditional ("set status to SHIPPED where status is PAID").
Kafka's transactions give exactly-once between Kafka topics, but any side effect outside Kafka still needs this.
When the lift gets confused
Even a smart lift can slip. Two presses with the same ticket can arrive at the very same moment, and both ask the lift's ticket list "has it gone?" before either writes. So the lift writes the ticket first, and the list refuses a ticket that is already there. Or the lift writes the ticket, then loses power before the trip: the next press sees the ticket and thinks it went. So the ticket and the trip go in its trip book together, or not at all. Tickets are also thrown away after a while. A very late press finds no ticket and sends a new trip. And if someone presses with an old ticket but asks for a different floor, the lift says "that ticket was for something else" and refuses.
What can go wrong
- Two identical requests at once. Both check the key, both see "not seen", both do the work. Symptom: a double
charge despite keys, visible only under concurrency. Fix: don't check then insert. Do an atomic insert on a column
with a unique constraint (or
INSERT ... ON CONFLICT DO NOTHING) and let exactly one request win; the loser gets the stored response, or409 Conflictwhile the first is still running. To answer 409 while the first request runs, commit the key first with statusin_progress; the work then finishes it (next bullet). Recover stalein_progressrows after a timeout. WithJdbcTemplate, Spring throwsDuplicateKeyException; through JPA/Hibernate you get its parent,DataIntegrityViolationException, so catch that. - Key and effect not committed together. If you mark the key done and crash before the work, retries see a
finished key and the work never happens (a lost operation). If you do the work and crash before recording the
key, the retry repeats it (a duplicate). Fix: commit the effect and the key's final state (
done, with the stored response) in one database transaction (see transactions), so a crash leaves either an unfinished key that is safe to retry or a finished key with its effect, never one without the other. - The key expires before a late retry. Keys can't be kept forever, so a retry after the retention window looks new and runs again. Symptom: duplicates only from slow, queued or offline clients. Fix: keep keys longer than any client's maximum retry horizon, and have clients stop retrying after a deadline.
- Same key, different body. A client bug reuses a key for another request. Returning the stored response would
hide the mistake. Fix: store a hash of the request with the key and reject a mismatch with
422 Unprocessable Content(as the IETF Idempotency-Key header draft suggests); log it, since it is always a client bug. - Side effects outside your database. An email or a call to a payment provider isn't covered by your transaction. Crash after sending and before recording, and the retry sends again. Fix: pass your own key on to the provider as their idempotency key, or write an outbox row in the same transaction and let a relay deliver it, with the consumer deduplicating (see the outbox in sagas).
| Choice | You gain | You pay |
|---|---|---|
| Long key retention | Late retries are still caught | More storage, and the key table must be cleaned up |
| Short key retention | A small, cheap table | Retries after expiry run twice |
| Store the full response | Retries get the same answer, status and body | More storage, and sensitive data kept around |
| Dedupe at the edge (gateway) | Duplicates never reach your code | It can't share your transaction, so key and effect may disagree |
1// run the insert in its own transaction, or use INSERT ... ON CONFLICT DO NOTHING and check the row count2try {3keys.insert(key, requestHash); // INSERT INTO idempotency_keys ...4} catch (DataIntegrityViolationException e) {5return keys.storedResponse(key, requestHash); // same hash: replay; else 4226}