Full answer
Why it matters
Networks fail in the middle. A student pays a course fee, the request reaches the server, the payment is recorded, and then the response is lost. The app shows "Something went wrong". The student taps Pay again. Without protection, they are charged twice.
Retries are unavoidable (clients, load balancers and SDKs all retry), so the server must make retries harmless.
HTTP methods
GET,HEAD: read only, safe and idempotent.PUT /users/7/emailwith a full value: repeating it sets the same value. Idempotent.DELETE /cart/items/3: after the first call it is gone; later calls change nothing (they may return 404, but the state is the same). Idempotent.POST /payments: creates a new payment each time. Not idempotent.
Idempotency keys
- The client generates a unique key per user action (a UUID) and sends it in a header:
Idempotency-Key: 5f1c.... - The server, in one transaction, checks if the key exists. If not, it performs the action and stores the key, a hash of the request body, and the response.
- A retry with the same key returns the stored response without repeating the action.
- The same key with a different body is rejected, because it signals a client bug.
A runnable sketch with SQLite (Python 3.13, output identical on two runs):
import json
import sqlite3
db = sqlite3.connect(":memory:")
db.execute("""CREATE TABLE idempotency_keys (
key TEXT PRIMARY KEY, request_hash TEXT, response TEXT)""")
db.execute("CREATE TABLE payments (id INTEGER PRIMARY KEY, student TEXT, amount INTEGER)")
def pay_fee(key, student, amount):
req_hash = f"{student}:{amount}"
with db: # one transaction
row = db.execute("SELECT request_hash, response FROM idempotency_keys WHERE key = ?",
(key,)).fetchone()
if row:
if row[0] != req_hash:
return {"error": "key reused with different body"}
return json.loads(row[1]) # replay the saved response
cur = db.execute("INSERT INTO payments (student, amount) VALUES (?, ?)", (student, amount))
response = {"payment_id": cur.lastrowid, "status": "paid"}
db.execute("INSERT INTO idempotency_keys VALUES (?, ?, ?)",
(key, req_hash, json.dumps(response)))
return response
print(pay_fee("k-123", "asha", 1500))
print(pay_fee("k-123", "asha", 1500)) # client retry after a timeout
print(pay_fee("k-123", "asha", 9999))
print(db.execute("SELECT COUNT(*) FROM payments").fetchone()[0], "payment row(s)")Output:
{'payment_id': 1, 'status': 'paid'}
{'payment_id': 1, 'status': 'paid'}
{'error': 'key reused with different body'}
1 payment row(s)
Production details
- Concurrent duplicates: two retries can arrive at the same moment. The primary key on
keymakes the second insert fail and roll back; return 409 or wait and replay. Some systems first insert the key with statusin_progress. - External calls: if the payment goes to a provider, pass your key on to the provider's own idempotency key so the provider deduplicates too.
- Expiry: keep keys for a fixed window (for example 24 hours) and document it.
- Scope keys per user or API client so different clients cannot collide.
By level
Fresher: Define idempotency, explain the double-charge problem caused by retries, and describe the key-in-a-header idea. Classifying GET, PUT, DELETE and POST correctly is expected.
Mid: Implement the key table with transactional semantics, handle body mismatch and expiry, and classify HTTP methods. Expect the key, request hash and response to be stored together.
Senior: Handle concurrent duplicates, in-progress states, propagation to external providers, multi-region key storage and how idempotency interacts with sagas and message consumers. Expect a plan for two identical requests arriving at the same moment.
Key points
- Idempotent means repeating the call has the same effect as one call
- GET, PUT and DELETE are idempotent by definition; POST is not
- Client sends a unique key per action; server stores key, request hash and response
- Same key returns the saved result; different body with the same key is rejected
- Handle concurrent duplicates with a unique constraint and expire keys after a window
Common mistakes
- Generating a new key on every retry, which defeats the purpose
- Storing the key outside the transaction that performs the action
- Treating DELETE returning 404 on repeat as not idempotent
- Forgetting to pass the key to downstream payment providers
Follow-ups
- How would you handle two identical requests arriving at the same millisecond?
- How long should idempotency keys live?
- How do you make a message consumer idempotent?
Tips
- Open with the lost-response payment story in two sentences
- Classify HTTP methods correctly
- Mention the concurrent-request race
Evaluation rubric
- Precise definition
- Correct HTTP method classification
- Complete key flow including body mismatch and storage in the same transaction
- Handles concurrency and expiry