Skip to lesson

Idempotency keys for safe retries

Meena taps Place order, the network drops, and her app sends the request again. If ShopLite is not ready for that, she gets two orders and pays twice. How do you make a retry safe?

Your turn: design a safe retry

ShopLite is popular now, and many customers order on slow phone networks. Meena taps Place order. The server saves the order, but the answer never reaches her phone, so the app sends the same request again.

Before you read on, think about these questions and write your design in two or three lines.

  • How many orders does ShopLite have now, and what does Meena pay?
  • What could the server compare to know the second request is a retry and not a new order?
  • How long must the server remember that, and where should it keep it?

The double-charge problem

Idempotent means that doing an operation twice leaves the system in the same state as doing it once. A request that is idempotent can be repeated safely, so a lost answer is no longer dangerous.

On a mobile network, a request can succeed on the server while the answer is lost on the way back. The app sees a timeout and sends the same request again. Watch what that does to a plain POST /orders.

Example 1 · A lost response and a retry create two orders

DoubleOrderDemo.javaJava
import java.util.ArrayList;import java.util.List;
class OrderServer {    final List<Integer> orders = new ArrayList<>();    private int nextId = 501;    int calls = 0;
    // POST /orders: the server does the work, but the 1st response is lost on a bad network    Integer createOrder(String customer, int total) {        calls++;        int id = nextId++;        orders.add(id);        System.out.println("  server: created order " + id + " for " + customer + ", charged Rs " + total);        if (calls == 1) {            System.out.println("  network: response lost, client sees a timeout");            return null;        }        return id;    }}
public class DoubleOrderDemo {    public static void main(String[] args) {        OrderServer server = new OrderServer();
        Integer id = null;        for (int attempt = 1; id == null; attempt++) {            System.out.println("client: attempt " + attempt + " POST /orders");            id = server.createOrder("meena", 20597);        }        System.out.println("client: got order " + id);        System.out.println("orders in database: " + server.orders + " -> charged twice");    }}
Output
client: attempt 1 POST /orders
  server: created order 501 for meena, charged Rs 20597
  network: response lost, client sees a timeout
client: attempt 2 POST /orders
  server: created order 502 for meena, charged Rs 20597
client: got order 502
orders in database: [501, 502] -> charged twice

What this code does

  • The server creates order 501, but the response is lost, so the client sees a timeout and sends the same request again.
  • The retry creates order 502 and charges again. Both requests were correct on their own; together they double-charge Meena.

A timeout means no answer arrived within the time limit. It does not mean the work failed, and the app cannot tell the difference, so it retries.

Telling users "do not press the button twice" does not help, because apps, browsers and proxies also retry on their own. The server itself must make a repeat harmless.

Common mistake: treating a timeout as a failure. You can spot it in the data: two orders for the same customer with the same total, a few seconds apart.

Which HTTP methods are idempotent

By the HTTP standard, GET, HEAD, PUT, DELETE and OPTIONS are idempotent, and POST is not. The example sends each kind of request twice and prints the state afterwards.

Example 2 · PUT and DELETE twice vs POST twice

MethodsDemo.javaJava
import java.util.Map;import java.util.TreeMap;
public class MethodsDemo {    static Map<Integer, Integer> prices = new TreeMap<>(Map.of(1, 17999, 6, 1299));    static int nextId = 7;
    static String put(int id, int price) {         // PUT /products/{id}: "set it to this"        prices.put(id, price);        return "200";    }
    static String delete(int id) {                  // DELETE /products/{id}        return prices.remove(id) != null ? "204" : "404";    }
    static String post(int price) {                 // POST /products: "create a new one"        prices.put(nextId++, price);        return "201";    }
    public static void main(String[] args) {        System.out.println("PUT twice:    " + put(1, 18999) + ", " + put(1, 18999) + "  -> " + prices);        System.out.println("DELETE twice: " + delete(6) + ", " + delete(6) + "  -> " + prices);        System.out.println("POST twice:   " + post(499) + ", " + post(499) + "  -> " + prices);    }}
Output
PUT twice:    200, 200  -> {1=18999, 6=1299}
DELETE twice: 204, 404  -> {1=18999}
POST twice:   201, 201  -> {1=18999, 7=499, 8=499}

What this code does

  • PUT twice leaves price 18999 either way. DELETE twice answers 204 then 404, but the state is the same: product 6 is gone. Both are idempotent.
  • POST twice adds two products, 7 and 8. Each POST changes the state again, which is why a retried POST needs protection.

PUT /products/1 says "set product 1 to this", so sending it twice leaves the same product. DELETE twice leaves it deleted, even though the second call answers 404: idempotency is about the server's state, not the response.

POST means "create a new one" or "do this action", so each call can add something new. PATCH is not idempotent in general ("add 1 to stock" twice adds 2). These are the requests that need an idempotency key when retries are possible.

Predict the output

Same request twice

Predict the stock after the same request is sent twice.

Round 1 of 2

PATCH "add 5 to stock", sent twice. Stock starts at 10.

Map<Integer, Integer> stock = new HashMap<>();
stock.put(1, 10);
stock.merge(1, 5, Integer::sum);
stock.merge(1, 5, Integer::sum);
System.out.println(stock.get(1));

The Idempotency-Key header: store the first response, replay it

An idempotency key is a unique id that the client creates once per user action and sends with the request and with every retry. The server uses it to recognise a retry and return the first result instead of doing the work again.

The client makes one unique key (a UUID) per checkout and sends it in an Idempotency-Key header on the first try and on every retry. Here is such a request.

Text
POST /api/v1/orders HTTP/1.1Idempotency-Key: 7c1e9a52-0f4b-4b8e-9a51-2d6f3c1e8b90Content-Type: application/json{"customerId": 2, "addressId": 3, "items": [{"productId": 1, "quantity": 1}]}
One checkout with key K1. Step 1: the server sees K1 for the first time, creates order 501 and saves K1 with the answer. Step 2: the answer is lost and the client times out. Step 3: the retry carries K1, so the server replays the saved answer. One order, one charge.

Example 3 · OrderApi with a key map: the retry gets the same order id

IdempotentOrderApi.javaJava
import java.util.ArrayList;import java.util.List;import java.util.Map;import java.util.concurrent.ConcurrentHashMap;
record StoredResponse(int status, String body) {}
class OrderApi {    private final Map<String, StoredResponse> responsesByKey = new ConcurrentHashMap<>();    final List<Integer> orders = new ArrayList<>();    private int nextId = 501;
    // POST /api/v1/orders with header Idempotency-Key: <key>    StoredResponse createOrder(String idempotencyKey, String customer, int total) {        StoredResponse earlier = responsesByKey.get(idempotencyKey);        if (earlier != null) {            System.out.println("  server: key " + idempotencyKey + " seen before, replaying the stored response");            return earlier;        }        int id = nextId++;        orders.add(id);        StoredResponse response = new StoredResponse(201, "{\"id\":" + id + ",\"total\":" + total + ".00}");        responsesByKey.put(idempotencyKey, response);        System.out.println("  server: created order " + id + " for " + customer);        return response;    }}
public class IdempotentOrderApi {    public static void main(String[] args) {        OrderApi api = new OrderApi();        String key = "7c1e9a52-meena-checkout-1";   // made once per checkout, reused on every retry
        System.out.println("attempt 1 (response lost):");        api.createOrder(key, "meena", 20597);        System.out.println("attempt 2 (retry with the same key):");        StoredResponse r = api.createOrder(key, "meena", 20597);        System.out.println("client got: " + r.status() + " " + r.body());
        System.out.println("a new checkout (new key):");        api.createOrder("0b44d1f3-meena-checkout-2", "meena", 1299);        System.out.println("orders in database: " + api.orders);    }}
Output
attempt 1 (response lost):
  server: created order 501 for meena
attempt 2 (retry with the same key):
  server: key 7c1e9a52-meena-checkout-1 seen before, replaying the stored response
client got: 201 {"id":501,"total":20597.00}
a new checkout (new key):
  server: created order 502 for meena
orders in database: [501, 502]

What this code does

  • responsesByKey maps each idempotency key to the stored response. The retry finds the key and replays 201 with order 501; no second order is made.
  • A new checkout uses a new key, so it creates order 502 as it should. The key belongs to one user action, not to one customer.

The server stores the key together with the response of the first successful attempt. When the same key arrives again, it does no new work and returns the stored response, so the retry gets the same order id.

Payment providers such as Stripe and Razorpay use this pattern, and an IETF draft describes the header.

Order of execution

Order one safe checkout

Put the steps of one checkout with an idempotency key in order.

Edge cases: expiry and a reused key with a different body

A fingerprint is a hash of the request body, stored next to the key. It lets the server tell a real retry (same fingerprint) from a different request that reuses the key by mistake (different fingerprint).

Keys cannot be kept forever, and a client can reuse a key by mistake. The example shows a replay, a rejected body and an expired key at different hours.

Example 4 · Expiry and a key reused with a different body

KeyEdgeCasesDemo.javaJava
import java.util.HashMap;import java.util.Map;
record Entry(String bodyFingerprint, String response, long expiresAt) {}
class IdempotencyStore {    static final long TTL_HOURS = 24;    private final Map<String, Entry> entries = new HashMap<>();    private int nextId = 501;
    String handle(String key, String body, long nowHours) {        Entry e = entries.get(key);        if (e != null && nowHours >= e.expiresAt()) {            entries.remove(key);                       // expired: forget it            e = null;        }        if (e != null) {            if (!e.bodyFingerprint().equals(body)) {                return "422 key already used with a different request body";            }            return e.response() + " (replayed)";        }        String response = "201 order " + nextId++;        entries.put(key, new Entry(body, response, nowHours + TTL_HOURS));        return response;    }}
public class KeyEdgeCasesDemo {    public static void main(String[] args) {        IdempotencyStore store = new IdempotencyStore();        String body = "{\"items\":[{\"productId\":1,\"quantity\":1}]}";        String otherBody = "{\"items\":[{\"productId\":6,\"quantity\":3}]}";
        System.out.println("hour 0,  key A:            " + store.handle("A", body, 0));        System.out.println("hour 2,  key A again:      " + store.handle("A", body, 2));        System.out.println("hour 3,  key A, new body:  " + store.handle("A", otherBody, 3));        System.out.println("hour 30, key A again:      " + store.handle("A", body, 30));    }}
Output
hour 0,  key A:            201 order 501
hour 2,  key A again:      201 order 501 (replayed)
hour 3,  key A, new body:  422 key already used with a different request body
hour 30, key A again:      201 order 502

What this code does

  • Within 24 hours the same key and body replay order 501. The same key with a different body is rejected with 422 instead of being replayed or run.
  • At hour 30 the key has expired, so it is treated as a brand new request and creates order 502. Choose the expiry longer than any client would keep retrying.

Each key gets an expiry, often 24 hours: long enough for any retry, short enough to keep the table small. After expiry the same key is treated as new.

A known key with a different body (a different cart) is a client bug, not a retry. Replaying the old response would be wrong and running the new request would defeat the key, so the server rejects it; the IETF draft suggests 422. The example compares the body text itself; a real server compares the stored fingerprint.

Concurrent duplicates: claim the key atomically

A check-then-act race is a bug where two threads both pass a check before either one acts on it, so both act. It is fixed by making the check and the act one atomic step.

A double tap can send two requests with the same key at the same moment. This example starts eight threads, all with one key.

Example 5 · Eight simultaneous requests, one order

ConcurrentDuplicatesDemo.javaJava
import java.util.Set;import java.util.TreeSet;import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.CountDownLatch;import java.util.concurrent.atomic.AtomicInteger;
public class ConcurrentDuplicatesDemo {    static ConcurrentHashMap<String, Integer> orderIdByKey = new ConcurrentHashMap<>();    static AtomicInteger nextId = new AtomicInteger(501);    static AtomicInteger ordersCreated = new AtomicInteger();
    static int createOrder(String key) {        // computeIfAbsent runs the function at most once per key, even when threads race        return orderIdByKey.computeIfAbsent(key, k -> {            ordersCreated.incrementAndGet();            return nextId.getAndIncrement();        });    }
    public static void main(String[] args) throws InterruptedException {        int threads = 8;                                  // a double-tap plus 6 quick retries        CountDownLatch start = new CountDownLatch(1);        CountDownLatch done = new CountDownLatch(threads);        Set<Integer> idsReturned = new TreeSet<>();
        for (int i = 0; i < threads; i++) {            new Thread(() -> {                try {                    start.await();                         // all threads start together                    int id = createOrder("key-meena-42");                    synchronized (idsReturned) {                        idsReturned.add(id);                    }                } catch (InterruptedException e) {                    Thread.currentThread().interrupt();                } finally {                    done.countDown();                }            }).start();        }        start.countDown();        done.await();
        System.out.println("requests with the same key: " + threads);        System.out.println("orders created:             " + ordersCreated.get());        System.out.println("order ids returned:         " + idsReturned);    }}
Output
requests with the same key: 8
orders created:             1
order ids returned:         [501]

What this code does

  • A CountDownLatch starts eight threads at the same moment, all with the same key.
  • computeIfAbsent runs the create function at most once per key, so exactly one order is created and every thread gets order 501. A UNIQUE key column gives the same guarantee in a database.

If the code checks "is the key there?" and saves it later, both requests can pass the check before either saves, and two orders are created.

The fix is to claim the key in one atomic step. In Java, ConcurrentHashMap.putIfAbsent or computeIfAbsent does that; in a database, a UNIQUE constraint on the key column makes the second insert fail. A request that finds the key still being processed gets 409 and retries later.

Find the bug

Find the retry bug

Click the line that breaks idempotency.

The app retries a timed-out checkout. Which line is the bug?

Round 1 of 3

Next step

Check your understanding

11 quick questions