Part 03 · The Language of the Web

Idempotency and Safe Operations

Idempotency

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 happenedServer stateWhat a blind retry does
The request never reached the serverunchangeddoes the work, correct
The server is still working on itabout to changemay do the work twice
The server finished, the response was lostchangeddoes 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.

POST /payments Idempotency-Key: k-81f2clienttimeout, retryservercharges oncesaved keysk-81f2 → pay_1POST k-81f2charge pay_1, save key + answer201 pay_1answer lost on the way backPOST k-81f2key seen: replay, no new charge201 pay_1one charge, same answer twice
The client sends POST /payments with Idempotency-Key k-81f2. The server charges pay_1 and saves the key with its answer. The answer, 201 pay_1, is lost on the way back. The client times out and sends the same request with the same key. The server finds the key, replays 201 pay_1 and charges nothing new: one charge, the same answer twice.

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

  1. 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.)
  2. 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/7 removes it; deleting again leaves it removed.
  3. Same state, not same response. The first DELETE may return 204, the second 404. That's still idempotent: the order is gone either way.
  4. POST and PATCH are not idempotent by default. POST /payments creates a new payment every time. PATCH can be either: {"status":"paid"} sets a value (idempotent), {"op":"increment","by":100} doesn't.
  5. 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.
  6. 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.
  7. 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.
  8. 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 409 or make it wait.
Predict first

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

Step through it

POST /payments, lost response, safe retry

AppNetworkPayment APIKey store

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?

Try each case

Retry or not?

retry
works: Safe and idempotent. Retrying can't change anything.

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))
}

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 charged pay_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 got 201 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 NOTHING saw 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-Key header 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 (with Retry-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

Try each case

Pick a failure

same cart, two orders, 3 seconds apart
breaks: The client or a proxy retried POST /orders after a timeout. Add an idempotency key per checkout attempt.

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 pay into start(key, amount) and finish(key). start claims the key with status in_progress; finish does the charge, saves the response and sets status done.
  • If start sees a key that's in_progress, return 409 still processing. If it's done, replay the saved response.
  • Simulate: start(k1), then a duplicate start(k1), then finish(k1), then a third start(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 →