TwiceToldby Develoker
ConceptsSystem designLabsCheat sheetsAbout

Develoker makes free tools for learning to build software. TwiceTold explains each idea twice, as an everyday analogy and the real thing; CloudArch lets you design cloud systems and put load on them.

About ยท Labs ยท Cheat sheets ยท Learning paths

All concepts ยท distributed systems ยท apis ยท reliability

Idempotency

Making it safe to repeat a request. Networks lose replies, so clients retry; idempotent operations and idempotency keys make sure a retry has the same effect as the first attempt, never a double charge.

9 min4 animations

๐Ÿ“š Builds on๐Ÿ“ฎ HTTP

๐Ÿ–จ๏ธ Cheat sheet

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.

The lost reply2 steps
๐Ÿง’You๐Ÿ›—Lift control๐Ÿ“’ Lift log
Press play and watch it happen!

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:

  1. looks the key up; if it's done, returns the stored response,
  2. otherwise does the work and stores the key with its result in the same transaction,
  3. 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.

Pressing the button twice3 steps
Pressed buttons0123๐Ÿง’You๐Ÿ›—Lift control๐Ÿ“’ Lift log
Press play and watch it happen!

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.

The same message twice3 steps
Done list0123๐Ÿ“ฎPost room๐Ÿง‘โ€๐Ÿ’ผClerk๐Ÿ“’ Order book
Press play and watch it happen!

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, or 409 Conflict while the first is still running. To answer 409 while the first request runs, commit the key first with status in_progress; the work then finishes it (next bullet). Recover stale in_progress rows after a timeout. With JdbcTemplate, Spring throws DuplicateKeyException; 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).
ChoiceYou gainYou pay
Long key retentionLate retries are still caughtMore storage, and the key table must be cleaned up
Short key retentionA small, cheap tableRetries after expiry run twice
Store the full responseRetries get the same answer, status and bodyMore storage, and sensitive data kept around
Dedupe at the edge (gateway)Duplicates never reach your codeIt 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 {3    keys.insert(key, requestHash);        // INSERT INTO idempotency_keys ...4} catch (DataIntegrityViolationException e) {5    return keys.storedResponse(key, requestHash);   // same hash: replay; else 4226}
Two copies race for one key5 steps
Pressed buttons0123๐Ÿง‘First press๐Ÿง‘Second press๐Ÿ›—Smart lift๐Ÿ“’ Lift log
Press play and watch it happen!

๐Ÿ”Ž Spot it in real code

This is the smart lift as real Java code. A press arrives with a ticket number, and the lift decides whether to go, to turn the light on again, or to refuse. Pick a label, then tap the line where that happens.

Tap the line where you see: The ticket number that comes with the press.

0 of 5 placed

๐Ÿงฉ Finish the code

Now build the smart lift's ticket list yourself. A ticket may be used for only one trip. A second press with the same ticket must get the same answer told again, a press with the same ticket but a different request must be refused, and a trip and its ticket must be written in the trip book together or not at all. Pick the right piece of code for each gap.
  1. 1 When the ticket is already on the list, do nothing and say so
  2. 2 Refuse when this request is not the one the ticket was first used for
  3. 3 Write the ticket and the trip in the trip book together
  4. 4 Fill in the ticket's finished entry with the answer before leaving
1// IdempotencyKeys repository: unique index on the key column2boolean claim(String key, String hash) {3    return jdbc.update("""4        INSERT INTO idempotency_keys (key, request_hash)5        VALUES (?, ?)6        1""", key, hash) == 1;7}8 9String replay(String key, String hash) {10    var saved = jdbc.queryForObject(11        "SELECT request_hash, response FROM idempotency_keys WHERE key = ?",12        (rs, n) -> new Saved(rs.getString(1), rs.getString(2)), key);13    if (2) {14        throw new KeyReuseException(key);   // handled as 42215    }16    return saved.response();17}18 19// PaymentService: the charge and its key must succeed or fail together20321String pay(String key, String body) {22    var hash = sha256(body);23    if (!keys.claim(key, hash)) {24        return keys.replay(key, hash);25    }26    var result = payments.charge(body);27    4;28    return result;29}
0 of 4 gaps filled

๐Ÿ—๏ธ Design it in CloudArch

Build the architecture on a canvas, push load through it and see what breaks.

  • ๐ŸŽŸ๏ธDesign ticket bookingSell every seat exactly once while a million fans hit refresh.practice problem
  • ๐Ÿš•UberStream moving drivers, match riders in seconds and never double-charge.guided design

๐Ÿงช Debug it for real

  • ๐Ÿ’ณBilling charged some customers twiceThe billing reader works through the shared notebook of orders. Some customers were charged twice, and after a restart one order was never charged at all. Find out why and fix it.Java 21Kafka clientJUnit 5intermediate30 min

๐Ÿงฉ Quick quiz

Quick quiz! 5 questions about Idempotency, told the same way as the story.
  1. The lift went but the light didn't come on, so you press again. What does a careless lift do?
  2. How does the smart lift know a press is a repeat?
  3. The post room clerk's "got it" goes missing, and the letter arrives again. What does the clerk do?
  4. Two presses with the same ticket reach the lift at the same moment, and both hear "not gone yet". What stops two trips?
  5. The lift writes the ticket on the list, then loses power before the trip. What goes wrong when you press again?
Answer every question to check.Passing marks Idempotency as done.
Got the hang of Idempotency? Mark it as done, and your paths show how far youโ€™ve got.

Saved in this browser.

๐ŸŽฏ Backend interview prepStep 3 of 9

โ† Previous on the path๐Ÿ›’ Transactions and isolationNext on the path โ†’๐Ÿฌ Rate limiting

๐Ÿ”Œ Designing APIsStep 5 of 5

โ† Previous on the path๐ŸŽง gRPC and Protocol BuffersLast step ๐ŸŽ‰Back to the path

๐Ÿ‘‰ Read next

  • ๐Ÿง‘โ€๐ŸณAWS Lambda and serverlessA kitchen with no cooks waiting around: each order gets a station, and you pay only while it cooks.
  • ๐ŸงบAmazon SQS and SNSA laundrette: baskets wait on a rack until an attendant finishes one, and a copier slips every rack a copy.