Part 03 · The Language of the Web
Idempotency and Safe Operations
Which requests can be sent twice without harm, and why that matters on bad networks.
⏱ 1 hours · Station 37 of 153
Charged twice for one ride
A rider in Dhaka finishes a trip and taps "Pay 500 taka". The phone is on a weak 4G signal in a traffic jam. The request reaches the server, the card is charged, and the server sends back "201 paid". That response never arrives; the signal dropped for a second. After 10 seconds the app's HTTP library times out and does what it was told to do: retry. The server sees a brand-new payment request and charges again. The rider sees two 500-taka charges and a one-star review follows.
Nobody wrote a bug in the usual sense. The network did exactly what networks do (Module 2, lesson 10): it lost a message. The client did exactly what clients should do: it retried. The problem is that the operation wasn't safe to repeat.
This lesson is about two properties that decide whether a request can be retried without harm: safe (it doesn't change anything) and idempotent (doing it twice has the same effect as doing it once). And about the trick that makes even a payment idempotent: the idempotency key.
The problem: a timeout doesn't tell you what happened
When a client times out, there are three possibilities, and it can't tell them apart:
| What actually happened | Server state | What a blind retry does |
|---|---|---|
| The request never reached the server | unchanged | does the work, correct |
| The server is still working on it | about to change | may do the work twice |
| The server finished, the response was lost | changed | does the work again |
For a read, all three are fine to retry. For "set the email to [email protected]", all three end in the same state. For "charge 500 taka" or "add 100 credits", the last two are a disaster. So before any client, proxy or job queue retries a request, someone has to know: is this operation safe to repeat?
Think of a lift button
You press the lift's call button. Nothing seems to happen, so you press it five more times. The lift still comes once. Pressing "call the lift to floor 3" is idempotent: the first press does the work, the others change nothing.
Now think of a vending machine where each press of "B4" drops a packet of chips and takes 50 taka. Pressing it five times because the machine felt slow costs you 250 taka. That button is not idempotent.
An idempotency key turns the vending machine into a lift button. You write a unique ticket number on your order. The machine remembers ticket numbers; if the same ticket comes again, it just shows you the receipt from the first time.
Where the analogy stops working. A lift button is idempotent by nature. A payment isn't; the server makes it idempotent by remembering which keys it has seen. That memory has to be stored, shared across servers and kept long enough to cover every retry.
The building blocks
- Safe means the request doesn't change server state: GET, HEAD, OPTIONS. Crawlers, prefetchers and caches send these freely. (Logging or counting views is fine; the client didn't ask for a change.)
- Idempotent means sending it N times leaves the same state as sending it once. GET, HEAD, PUT and DELETE are idempotent by definition.
PUT /users/1/email "[email protected]"sets a value; setting it again changes nothing.DELETE /orders/7removes it; deleting again leaves it removed. - Same state, not same response. The first DELETE may return
204, the second404. That's still idempotent: the order is gone either way. - POST and PATCH are not idempotent by default.
POST /paymentscreates a new payment every time.PATCHcan be either:{"status":"paid"}sets a value (idempotent),{"op":"increment","by":100}doesn't. - Design the operation to be idempotent when you can. "Set balance to 600" instead of "add 100". "Mark order 7 as shipped" instead of "ship the next order". Upserts (
INSERT ... ON CONFLICT DO NOTHING) instead of blind inserts. - Idempotency keys for the rest. The client generates a unique key (a UUID) per intended operation and sends it in a header like
Idempotency-Key. The server stores key → request fingerprint + response. A repeat with the same key gets the stored response; no work is redone. - The key must cover the same request. If the same key arrives with a different body (amount 900 instead of 500), that's a client bug. Reject it (
422), don't silently return the old answer for a different request. - Concurrent duplicates. A retry can arrive while the first attempt is still running. Store the key before doing the work (with status "in progress", protected by a unique constraint), and answer the duplicate with
409or make it wait.
A client sends DELETE /orders/7. The server deletes it and returns 204, but the response is lost. The client retries. What should the second DELETE do?
Behind the scenes: a payment with a key
POST /payments, lost response, safe retry
Step 1/5 The app makes a key for this payment
Before sending, the app generates Idempotency-Key: k-81f2 and keeps it with the pending payment, so every retry of this payment uses the same key.
- key
- k-81f2
- amount
- 500
The picture to keep in your head
Every request gets one of three labels, and the label decides who may retry it.
- Safe (GET, HEAD, OPTIONS): changes nothing. Anyone can repeat it, any time.
- Idempotent (PUT, DELETE, and well-designed PATCH): repeating ends in the same state. Retry on timeout freely.
- Neither (POST, increments, "do the next thing"): repeating does the work again. Retry only with an idempotency key, or not at all.
Try it: safe to retry?
Retry or not?
retry
Code from first principles
A payment server that remembers idempotency keys, behind a network that loses the first response. The client retries on timeout, exactly like real HTTP libraries do. Then the same key is reused with a different amount, and finally a "set" operation and an "add" operation are each called twice.
package main
import (
"fmt"
"strings"
)
// A payment server that remembers idempotency keys: key -> the request it came with + the answer.
type saved struct{ request, response string }
type server struct {
charges []string
total int
keys map[string]saved
}
func newServer() *server { return &server{keys: map[string]saved{}} }
func (s *server) pay(key string, amount int) string {
request := fmt.Sprintf("POST /payments amount=%d", amount)
if key != "" {
if old, ok := s.keys[key]; ok {
if old.request != request {
return "422 key already used for a different request"
}
return old.response + " (replayed)" // same request again: same answer, no new charge
}
}
id := fmt.Sprintf("pay_%d", len(s.charges)+1)
s.charges = append(s.charges, id)
s.total += amount
response := "201 " + id
if key != "" {
s.keys[key] = saved{request, response}
}
return response
}
// The network loses the first response: the server did the work, the client never hears back.
// The client does what every HTTP library does on a timeout: it tries again.
func payWithRetry(s *server, key string, amount int) string {
tries := []string{}
for attempt := 1; attempt <= 3; attempt++ {
resp := s.pay(key, amount)
if attempt == 1 {
tries = append(tries, "try 1 timeout")
continue
}
tries = append(tries, fmt.Sprintf("try %d %s", attempt, resp))
break
}
return strings.Join(tries, ", ")
}
func main() {
s := newServer()
r := payWithRetry(s, "", 500)
fmt.Printf("no key: %s -> charges %v, %d taka\n", r, s.charges, s.total)
s = newServer()
r = payWithRetry(s, "k-81f2", 500)
fmt.Printf("key k-81f2: %s -> charges %v, %d taka\n", r, s.charges, s.total)
fmt.Printf("same key, amount=900: %s -> charges %v\n", s.pay("k-81f2", 900), s.charges)
// Methods that are idempotent by design: the second call leaves the same state as the first.
email := ""
put := func(v string) string { email = v; return email } // PUT /users/1/email: set to a value
fmt.Printf("PUT email twice: %s, %s (same state)\n", put("[email protected]"), put("[email protected]"))
credits := 0
add := func(n int) int { credits += n; return credits } // POST /users/1/credits: add to it
fmt.Printf("add 100 twice: %d, %d (changed twice)\n", add(100), add(100))
}// A payment server that remembers idempotency keys: key -> the request it came with + the answer.
function newServer() {
return { charges: [], total: 0, keys: new Map() };
}
function pay(s, key, amount) {
const request = `POST /payments amount=${amount}`;
if (key && s.keys.has(key)) {
const old = s.keys.get(key);
if (old.request !== request) return "422 key already used for a different request";
return old.response + " (replayed)"; // same request again: same answer, no new charge
}
const id = `pay_${s.charges.length + 1}`;
s.charges.push(id);
s.total += amount;
const response = "201 " + id;
if (key) s.keys.set(key, { request, response });
return response;
}
// The network loses the first response: the server did the work, the client never hears back.
// The client does what every HTTP library does on a timeout: it tries again.
function payWithRetry(s, key, amount) {
const tries = [];
for (let attempt = 1; attempt <= 3; attempt++) {
const resp = pay(s, key, amount);
if (attempt === 1) {
tries.push("try 1 timeout");
continue;
}
tries.push(`try ${attempt} ${resp}`);
break;
}
return tries.join(", ");
}
const list = (a) => "[" + a.join(" ") + "]";
let s = newServer();
let r = payWithRetry(s, "", 500);
console.log(`no key: ${r} -> charges ${list(s.charges)}, ${s.total} taka`);
s = newServer();
r = payWithRetry(s, "k-81f2", 500);
console.log(`key k-81f2: ${r} -> charges ${list(s.charges)}, ${s.total} taka`);
console.log(`same key, amount=900: ${pay(s, "k-81f2", 900)} -> charges ${list(s.charges)}`);
// Methods that are idempotent by design: the second call leaves the same state as the first.
let email = "";
const put = (v) => (email = v); // PUT /users/1/email: set to a value
console.log(`PUT email twice: ${put("[email protected]")}, ${put("[email protected]")} (same state)`);
let credits = 0;
const add = (n) => (credits += n); // POST /users/1/credits: add to it
console.log(`add 100 twice: ${add(100)}, ${add(100)} (changed twice)`);use std::collections::HashMap;
// A payment server that remembers idempotency keys: key -> the request it came with + the answer.
struct Server {
charges: Vec<String>,
total: u32,
keys: HashMap<String, (String, String)>,
}
impl Server {
fn new() -> Self {
Server { charges: vec![], total: 0, keys: HashMap::new() }
}
fn pay(&mut self, key: &str, amount: u32) -> String {
let request = format!("POST /payments amount={}", amount);
if !key.is_empty() {
if let Some((old_request, old_response)) = self.keys.get(key) {
if *old_request != request {
return "422 key already used for a different request".to_string();
}
return format!("{} (replayed)", old_response); // same request again: same answer, no new charge
}
}
let id = format!("pay_{}", self.charges.len() + 1);
self.charges.push(id.clone());
self.total += amount;
let response = format!("201 {}", id);
if !key.is_empty() {
self.keys.insert(key.to_string(), (request, response.clone()));
}
response
}
}
// The network loses the first response: the server did the work, the client never hears back.
// The client does what every HTTP library does on a timeout: it tries again.
fn pay_with_retry(s: &mut Server, key: &str, amount: u32) -> String {
let mut tries = vec![];
for attempt in 1..=3 {
let resp = s.pay(key, amount);
if attempt == 1 {
tries.push("try 1 timeout".to_string());
continue;
}
tries.push(format!("try {} {}", attempt, resp));
break;
}
tries.join(", ")
}
fn list(a: &[String]) -> String {
format!("[{}]", a.join(" "))
}
fn main() {
let mut s = Server::new();
let r = pay_with_retry(&mut s, "", 500);
println!("no key: {} -> charges {}, {} taka", r, list(&s.charges), s.total);
let mut s = Server::new();
let r = pay_with_retry(&mut s, "k-81f2", 500);
println!("key k-81f2: {} -> charges {}, {} taka", r, list(&s.charges), s.total);
let again = s.pay("k-81f2", 900);
println!("same key, amount=900: {} -> charges {}", again, list(&s.charges));
// Methods that are idempotent by design: the second call leaves the same state as the first.
let mut email = String::new();
let mut put = |v: &str| { email = v.to_string(); email.clone() }; // PUT /users/1/email: set to a value
let (a, b) = (put("[email protected]"), put("[email protected]"));
println!("PUT email twice: {}, {} (same state)", a, b);
let mut credits = 0;
let mut add = |n: i32| { credits += n; credits }; // POST /users/1/credits: add to it
let (a, b) = (add(100), add(100));
println!("add 100 twice: {}, {} (changed twice)", a, b);
}class Server:
"""A payment server that remembers idempotency keys: key -> the request it came with + the answer."""
def __init__(self):
self.charges = []
self.total = 0
self.keys = {}
def pay(self, key, amount):
request = f"POST /payments amount={amount}"
if key and key in self.keys:
old_request, old_response = self.keys[key]
if old_request != request:
return "422 key already used for a different request"
return old_response + " (replayed)" # same request again: same answer, no new charge
id = f"pay_{len(self.charges) + 1}"
self.charges.append(id)
self.total += amount
response = "201 " + id
if key:
self.keys[key] = (request, response)
return response
def pay_with_retry(s, key, amount):
"""The network loses the first response: the server did the work, the client never hears back.
The client does what every HTTP library does on a timeout: it tries again."""
tries = []
for attempt in range(1, 4):
resp = s.pay(key, amount)
if attempt == 1:
tries.append("try 1 timeout")
continue
tries.append(f"try {attempt} {resp}")
break
return ", ".join(tries)
def lst(a):
return "[" + " ".join(a) + "]"
s = Server()
r = pay_with_retry(s, "", 500)
print(f"no key: {r} -> charges {lst(s.charges)}, {s.total} taka")
s = Server()
r = pay_with_retry(s, "k-81f2", 500)
print(f"key k-81f2: {r} -> charges {lst(s.charges)}, {s.total} taka")
print(f"same key, amount=900: {s.pay('k-81f2', 900)} -> charges {lst(s.charges)}")
# Methods that are idempotent by design: the second call leaves the same state as the first.
state = {"email": "", "credits": 0}
def put(v): # PUT /users/1/email: set to a value
state["email"] = v
return state["email"]
def add(n): # POST /users/1/credits: add to it
state["credits"] += n
return state["credits"]
print(f"PUT email twice: {put('[email protected]')}, {put('[email protected]')} (same state)")
print(f"add 100 twice: {add(100)}, {add(100)} (changed twice)")import java.util.*;
public class Main {
// A payment server that remembers idempotency keys: key -> the request it came with + the answer.
static class Server {
List<String> charges = new ArrayList<>();
int total = 0;
Map<String, String[]> keys = new HashMap<>();
String pay(String key, int amount) {
String request = "POST /payments amount=" + amount;
if (!key.isEmpty() && keys.containsKey(key)) {
String[] old = keys.get(key);
if (!old[0].equals(request)) return "422 key already used for a different request";
return old[1] + " (replayed)"; // same request again: same answer, no new charge
}
String id = "pay_" + (charges.size() + 1);
charges.add(id);
total += amount;
String response = "201 " + id;
if (!key.isEmpty()) keys.put(key, new String[]{request, response});
return response;
}
}
// The network loses the first response: the server did the work, the client never hears back.
// The client does what every HTTP library does on a timeout: it tries again.
static String payWithRetry(Server s, String key, int amount) {
List<String> tries = new ArrayList<>();
for (int attempt = 1; attempt <= 3; attempt++) {
String resp = s.pay(key, amount);
if (attempt == 1) {
tries.add("try 1 timeout");
continue;
}
tries.add("try " + attempt + " " + resp);
break;
}
return String.join(", ", tries);
}
static String list(List<String> a) { return "[" + String.join(" ", a) + "]"; }
static String email = "";
static int credits = 0;
static String put(String v) { email = v; return email; } // PUT /users/1/email: set to a value
static int add(int n) { credits += n; return credits; } // POST /users/1/credits: add to it
public static void main(String[] args) {
Server s = new Server();
String r = payWithRetry(s, "", 500);
System.out.println("no key: " + r + " -> charges " + list(s.charges) + ", " + s.total + " taka");
s = new Server();
r = payWithRetry(s, "k-81f2", 500);
System.out.println("key k-81f2: " + r + " -> charges " + list(s.charges) + ", " + s.total + " taka");
System.out.println("same key, amount=900: " + s.pay("k-81f2", 900) + " -> charges " + list(s.charges));
// Methods that are idempotent by design: the second call leaves the same state as the first.
System.out.println("PUT email twice: " + put("[email protected]") + ", " + put("[email protected]") + " (same state)");
System.out.println("add 100 twice: " + add(100) + ", " + add(100) + " (changed twice)");
}
}Output (the same in all five languages):
no key: try 1 timeout, try 2 201 pay_2 -> charges [pay_1 pay_2], 1000 taka
key k-81f2: try 1 timeout, try 2 201 pay_1 (replayed) -> charges [pay_1], 500 taka
same key, amount=900: 422 key already used for a different request -> charges [pay_1]
PUT email twice: [email protected], [email protected] (same state)
add 100 twice: 100, 200 (changed twice)
Reading the output:
- No key: try 1 charged
pay_1, but the client only saw a timeout. Try 2 chargedpay_2. Two charges, 1000 taka for one ride. The server did nothing wrong; it had no way to know the two requests were the same intent. - With key
k-81f2: try 2 got201 pay_1 (replayed), the very same payment id. One charge, 500 taka. The client gets the answer it missed. - Same key, amount 900:
422. The key was used for a different request, so the server refuses instead of pretending. - PUT twice:
[email protected], [email protected]. Setting a value is idempotent; the second call changed nothing. - Add twice:
100, 200. Same code shape, not idempotent. This is the kind of operation that needs a key or a redesign ("set credits to 100").
In production, the "remember the key" part is usually a unique constraint in the database, so even two servers racing on the same key can't both do the work. Here it is in real PostgreSQL 16:
$ psql -q -e < idem.sql
CREATE TABLE payments (id serial PRIMARY KEY, idem_key text UNIQUE, amount int);
INSERT INTO payments (idem_key, amount) VALUES ('k-81f2', 500) ON CONFLICT (idem_key) DO NOTHING RETURNING id;
id
----
1
(1 row)
INSERT INTO payments (idem_key, amount) VALUES ('k-81f2', 500) ON CONFLICT (idem_key) DO NOTHING RETURNING id;
id
----
(0 rows)
SELECT count(*) AS charges, sum(amount) AS taka FROM payments;
charges | taka
---------+------
1 | 500
(1 row)
- First insert returns
id 1: the key was new, the payment row was created. - Second insert returns
0 rows:ON CONFLICT (idem_key) DO NOTHINGsaw the key already exists and skipped it. The application knows it's a repeat and returns the saved response. 1 | 500: one charge, however many times the request arrived.
Real engineering
- Know your client's retry policy. Many HTTP clients, SDKs, proxies and service meshes retry on timeouts or connection errors. Most retry only idempotent methods by default; make sure yours does, and that it never auto-retries POST without a key.
- Accept an
Idempotency-Keyheader on every endpoint that creates or moves money, sends messages or starts jobs. Stripe, PayPal and Adyen all work this way; there's an IETF draft standardising the header. - Store keys with the result, in the same transaction as the work. If the payment commits but the key doesn't (or the other way round), retries break. Keep keys for at least as long as clients may retry (often 24 hours) and then expire them.
- Fingerprint the request (hash of method, path and body) and reject a reused key with a different fingerprint.
- Handle in-progress duplicates with a unique constraint on the key and a status column. Return
409 Conflict(withRetry-After) to a duplicate that arrives while the first is still running. - Make consumers idempotent too. Message queues deliver "at least once" (Module 8), so the same event can arrive twice. Record processed event ids, or make the handler a "set", not an "add".
When it breaks
Pick a failure
same cart, two orders, 3 seconds apart
Think before you read on
Why should the client generate the idempotency key, not the server? Wouldn't it be simpler for the server to hand out keys?
Reveal
The key has to exist before the first request is sent, because the whole point is to recognise that request when it comes back as a retry. If the server generated the key, it would send it in the response, and the response is exactly what gets lost. The client would then retry without knowing the key, and the server would see a new request. So the client creates the key (a random UUID is enough), saves it with the operation it's trying to do, and sends the same key on every attempt. A server-side alternative is a two-step flow (POST /payment-intents to get an id, then confirm it), which works because creating an intent is harmless to repeat.
Check yourself
1. What's the difference between safe and idempotent?
Answer
Safe means the request doesn't change server state (GET, HEAD, OPTIONS). Idempotent means repeating it leaves the same state as doing it once (safe methods plus PUT and DELETE). Every safe method is idempotent; not every idempotent method is safe.
2. Is DELETE still idempotent if the second call returns 404?
Answer
Yes. Idempotency is about the server's state, not identical responses. After one or two DELETEs, the resource is gone.
3. How does an idempotency key prevent a double charge?
Answer
The client sends the same unique key on every attempt of one operation. The server saves the key with the result the first time, and on a repeat it returns the saved result instead of doing the work again.
4. What should the server do if a known key arrives with a different body?
Answer
Reject it (for example 422). The key identifies one specific request; returning the old result for a different request would hide a client bug.
Your challenge: handle the in-progress duplicate
Extend the server so a duplicate can arrive while the first attempt is still running:
- Split
payintostart(key, amount)andfinish(key).startclaims the key with statusin_progress;finishdoes the charge, saves the response and sets statusdone. - If
startsees a key that'sin_progress, return409 still processing. If it'sdone, replay the saved response. - Simulate:
start(k1), then a duplicatestart(k1), thenfinish(k1), then a thirdstart(k1).
Before you run it, predict the three answers and the number of charges.
You've succeeded when the output is started, 409 still processing, then 201 pay_1 (replayed), with exactly one charge, and removing the in_progress check makes the duplicate create a second charge.
The mental model
Networks lose responses, and a client that times out can't tell whether the work happened, so it retries. Safe requests (GET, HEAD, OPTIONS) change nothing; idempotent ones (PUT, DELETE, value-setting PATCH) end in the same state however often they run. For everything else, the client sends one idempotency key per intended operation, and the server stores key, request fingerprint and response, atomically with the work, replaying the saved answer for repeats. Design operations as "set" rather than "add" wherever you can.
Station stamp
Finish the chapter
Done reading? Press Complete to save your progress. XP is Pro-only — on Pro this chapter is worth +10 XP.
Go Pro to earn XP →