Idempotency
medium 26 minAn idempotent operation has the same effect whether it runs once or many times.
See it run
How a request can be sent many times and still take effect once, even when answers get lost and servers crash.
Operations
The double charge
A payment without a key: the answer is lost, the customer tries again, and the card is charged twice.
Step 1 of 4
Pay $99.99
Charged
$99.99
The customer clicks once. The request reaches the API and the card is charged.
Step 1: Pay $99.99
def create_payment(body): return card.charge(body) # every call charges- Effect
- $199.98
- Extra work
- None
- With a key
- $99.99
A timeout does not mean it failed. It means you do not know. That sentence is the whole reason for this topic.
In the real world
The same idempotency doing real jobs. Pick one and step through it.
The old payment simulator as a story: one new key, then retries with the same key, then a new purchase.
Step 1 of 3
First click, key 8f14
| Key | Status | Charged | |
|---|---|---|---|
| Click 1 | 8f14 | 201 new | $99.99 |
| Click 2 | |||
| Click 3 | |||
| Purchase 2 |
New key: processed, 201. Total charged $99.99, duplicates blocked 0.
Step 1: First click, key 8f14
Common mistakes
The bugs interviewers watch for, with the fix beside each.
A new key for every attempt
criticalThe server sees a new intention each time, so retries charge again. The key belongs to the click, not to the HTTP call.
Wrongdef attempt(): post(body, key=uuid4())Rightkey = uuid4() # onceretry(lambda: post(body, key=key))Read, then write
criticalTwo requests can both read nothing and both go on. Only a unique insert decides a winner.
Wrongif not db.find(key): db.insert(key); charge()Rightif db.insert_if_absent(key): # UNIQUE charge()A key that is unique for everyone
majorIf keys are not scoped to the user, one user's key can return another user's stored answer.
WrongUNIQUE (key)RightUNIQUE (user_id, endpoint, key)Marking any error as final
majorA timeout to the card network is not a failure: the charge may exist. Keep the key open and look it up before trying again.
Wrongexcept Exception: db.set(key, "failed")Rightexcept Timeout: leave_processing(key) # recovery asks first
Interview tips
How to explain it
- Doing it twice leaves the same state as doing it once.
- Retries are normal, so every write must survive them.
- GET, PUT and DELETE are idempotent by definition. POST needs a key.
Memory trick: SAKE
- S: same result, however many calls.
- A: atomic store of the key before the work.
- K: key from the client.
- E: expiry after the retry window.
Reach for a key when
- Payments and refunds.
- Orders and bookings.
- Transfers between accounts.
- Any POST a client may retry.
Simpler choices first
- A natural key: one checkout per cart.
- A unique constraint on the business row.
- A PUT to an id the client chose.
- A set instead of an add.