Idempotency keys for safe retries
Build an idempotent payment endpoint on PostgreSQL step by step: scope and fingerprint each key, claim it atomically before charging, replay the stored response, handle concurrent duplicates, settle unknown outcomes without a second charge and expire old keys.
Contentsand lesson path
On this page
- The problem
- Step 1: A table for keys
- Step 2: Claim the key before the side effect
- Step 3: Settle unknown outcomes
- Step 4: Run the retry cases
- Step 5: Inspect the table and expire old keys
- Check your understanding
- Apply it
- Review prompt
Lessons of Resilience Patterns
- How cascading failures happen Concept · 20 min
- Timeouts, retries, backoff and jitter Concept · 20 min
- Idempotency keys for safe retries Worked example · 25 min
- Circuit breakers, bulkheads and load shedding Concept · 20 min
- Injecting latency and failures into a call chain Lab · 30 min
- Resilience check Knowledge check · 8 questions
What you will learn
- Make write operations safe to retry with idempotency keys and server-side deduplication.
01. The problem
A payment API exposes POST /payments. Shops call it from their own servers, and sometimes the call times out. A timeout does not say whether the payment happened: the request may never have arrived, or the card may have been charged and only the reply lost. The shop's retry policy from lesson 2 wants to try again, and the customer must not pay twice. The endpoint therefore has to meet six requirements:
- A retry of the same payment returns the original answer and never charges again.
- A key reused with a different request is rejected, not treated as new or silently replayed.
- Two copies that arrive at the same moment do not both charge.
- When the outcome is unknown, the server finds out what really happened before it answers.
- Keys belong to one client, so two shops can pick the same key text safely.
- Keys expire on a published schedule, and the schedule is longer than any client keeps retrying.
The client's part is simple: create one random key per logical payment, store it with the payment, and send it in an Idempotency-Key header on the first try and on every retry. That header is being standardised by the IETF HTTPAPI working group as draft-ietf-httpapi-idempotency-key-header. In November 2026 it is still an Internet-Draft (version 08, published 22 October 2026 and aimed at the Standards Track), not an RFC, so treat it as a strong convention rather than a finished standard. It suggests 400 when a required key is missing, 422 when a key is reused with a different payload, and 409 while a request with the same key is still being processed, and it asks each API to publish its key expiry policy. Stripe's API, a widely copied example, keeps keys for at least 24 hours in its v1 API and compares the parameters of a retry with the original.
You need Docker, Python 3.10 or newer and the psycopg 3 driver. The example was run with PostgreSQL 18.6 and psycopg 3.3.9.
02. Step 1: A table for keys
Each column answers one requirement. The primary key is (client_id, key), so keys are scoped per client. request_hash is a fingerprint of the request body, computed from canonical JSON (sorted keys, no spaces) so that re-serialising the same body does not change it; it detects a reused key. status moves from started to done, or to unknown when the provider did not answer. payment_ref is the reference sent to the card provider. response_body is text, not jsonb, because jsonb does not keep key order or whitespace, and a replay should return the bytes the client would have received the first time. created_at drives expiry.
CREATE TABLE idempotency_keys (
client_id text NOT NULL, -- who sent the key: keys are scoped per client
key text NOT NULL, -- the Idempotency-Key header value
request_hash text NOT NULL, -- fingerprint of the request body
status text NOT NULL -- started | done | unknown
CHECK (status IN ('started', 'done', 'unknown')),
payment_ref text NOT NULL, -- our reference, also sent to the provider
response_code int,
response_body text, -- the exact bytes we answered with
created_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (client_id, key)
);docker run -d --name idem-pg -e POSTGRES_PASSWORD=lab \
-p 127.0.0.1:18361:5432 --tmpfs /var/lib/postgresql postgres:18-alpine
sleep 5
docker exec -i idem-pg psql -U postgres < schema.sql
python3 -m venv .venv && source .venv/bin/activate
python -m pip install -q --disable-pip-version-check "psycopg[binary]"
docker exec idem-pg psql -U postgres -tAc "SHOW server_version"
python -c "import psycopg; print(psycopg.__version__)"CREATE TABLE
18.6
3.3.903. Step 2: Claim the key before the side effect
A fake card provider stands in for the real one. Real card APIs offer duplicate protection through an idempotency key you send with each charge, honoured for a limited time (Stripe's v1 API keeps keys for at least 24 hours); a plain reference field is often not deduplicated, so check your provider's documentation. The fake provider treats our reference as such a key and charges at most once per reference. Its fault setting lets the demo lose a reply after charging, or time out before charging.
"""A fake card processor that charges at most once per reference we send."""
import threading
import time
class FakeProvider:
def __init__(self) -> None:
self.charges: dict[str, int] = {}
self.lock = threading.Lock()
self.delay = 0.0
self.fault = None # None, "lose_reply" or "timeout_before_charge"
def charge(self, ref: str, amount: int) -> None:
time.sleep(self.delay)
with self.lock:
fault, self.fault = self.fault, None
if fault == "timeout_before_charge":
raise TimeoutError("timed out before the charge was made")
self.charges.setdefault(ref, amount) # same ref again: no new charge
if fault == "lose_reply":
raise TimeoutError("the charge was made, but the reply was lost")
def lookup(self, ref: str) -> int | None:
return self.charges.get(ref)The handler does three things in order, and every database step borrows a connection for one short statement and gives it back at once (sql; a real service would use a pool). First it claims the key with INSERT ... ON CONFLICT DO NOTHING. The primary key makes the claim atomic: if two inserts race, exactly one creates the row and the other inserts nothing, which rowcount reports as 0. Autocommit means the claim is committed before any money moves. Then it calls the provider with no transaction, lock or connection held, so a slow provider cannot drain the database connections, which is the exhaustion from lesson 1. Finally it stores the exact response on a fresh connection. The provider reference is 128 bits of a hash of the client and the key, so a re-sent charge carries the same reference and different payments practically never share one.
"""An idempotent 'create payment' handler over PostgreSQL (psycopg 3)."""
import base64
import hashlib
import json
import psycopg
DSN = "postgresql://postgres:[email protected]:18361/postgres"
WHERE = "WHERE client_id = %s AND key = %s"
def sql(query: str, params: tuple) -> tuple[int, list]:
"""Run one statement on a short-lived connection (a real service would
borrow one from a pool) and give the connection back at once."""
with psycopg.connect(DSN, autocommit=True) as conn:
cur = conn.execute(query, params)
return cur.rowcount, cur.fetchall() if cur.description else []
def dumps(data: dict) -> str:
return json.dumps(data, separators=(",", ":"))
def fingerprint(body: dict) -> str:
canonical = json.dumps(body, sort_keys=True, separators=(",", ":"))
return hashlib.sha256(canonical.encode()).hexdigest()
def provider_ref(client_id: str, key: str) -> str:
# Same client and key -> same reference. 128 bits of the hash, so two
# different payments practically never share one; do not shorten it.
digest = hashlib.sha256(f"{client_id}:{key}".encode()).digest()[:16]
return "pay_" + base64.urlsafe_b64encode(digest).decode().rstrip("=")
def create_payment(provider, client_id: str, key: str | None, body: dict):
if not key:
return 400, '{"error":"Idempotency-Key header required"}'
digest, ref = fingerprint(body), provider_ref(client_id, key)
# 1. Claim the key. The INSERT commits at once (autocommit), before any
# side effect, and the primary key makes the claim atomic.
claimed, _ = sql(
"INSERT INTO idempotency_keys"
" (client_id, key, request_hash, status, payment_ref)"
" VALUES (%s, %s, %s, 'started', %s) ON CONFLICT DO NOTHING",
(client_id, key, digest, ref),
)
if not claimed:
return existing(client_id, key, digest)
# 2. The side effect, with no transaction, lock or connection held.
try:
provider.charge(ref, body["amount"])
except TimeoutError:
sql(f"UPDATE idempotency_keys SET status = 'unknown' {WHERE}", (client_id, key))
return 503, '{"error":"outcome unknown, retry with same key"}'
# 3. Save the exact response, so a retry gets the same bytes back.
reply = dumps({"id": ref, "amount": body["amount"]})
sql("UPDATE idempotency_keys SET status = 'done', response_code = 201,"
f" response_body = %s {WHERE}", (reply, client_id, key))
return 201, reply
def existing(client_id: str, key: str, digest: str):
_, rows = sql("SELECT request_hash, status, response_code, response_body"
f" FROM idempotency_keys {WHERE}", (client_id, key))
if not rows: # released by the reconciler a moment ago
return 409, '{"error":"key in use (released), retry now"}'
request_hash, status, code, reply = rows[0]
if request_hash != digest:
return 422, '{"error":"key reused with a different body"}'
if status == "done":
return code, reply
state = "in progress" if status == "started" else "being confirmed"
return 409, f'{{"error":"key in use ({state}), retry later"}}'When the claim fails, existing decides what the duplicate gets. A different fingerprint means a different request under the same key, which is a client bug: 422. A done row is replayed exactly, status and body. A started or unknown row means nobody knows the answer yet, so the duplicate gets 409 and retries later, instead of charging again or receiving an empty success.
04. Step 3: Settle unknown outcomes
A row stays unknown after a provider timeout, and stays started if the process died mid-request. Neither may be treated as failed, because the card may have been charged. A reconciler reads those rows, then, with no connection held, asks the provider about each one by its reference. If the charge exists, it stores the successful response, so the next retry gets it. If no charge exists, it deletes the row so that a retry can run again. That release is safe here only because a later retry sends the same reference, so a charge that arrives late and the retry cannot both succeed. Real payment systems also compare their records with the provider's settlement reports; the payment system design skill covers that.
"""Settle payments whose outcome is unknown by asking the provider."""
from payments import WHERE, dumps, sql
def reconcile(provider) -> None:
_, rows = sql(
"SELECT client_id, key, payment_ref FROM idempotency_keys"
" WHERE status = 'unknown'"
" OR (status = 'started' AND created_at < now() - interval '5 minutes')",
(),
)
for client_id, key, ref in rows: # no connection is held while we ask
amount = provider.lookup(ref)
if amount is None: # never charged: free the key so a retry can run
sql(f"DELETE FROM idempotency_keys {WHERE} AND status <> 'done'",
(client_id, key))
print(f" reconcile {key}: no charge found, key released")
continue
reply = dumps({"id": ref, "amount": amount})
sql("UPDATE idempotency_keys SET status = 'done', response_code = 201,"
f" response_body = %s {WHERE}", (reply, client_id, key))
print(f" reconcile {key}: charge found, stored as done")05. Step 4: Run the retry cases
The demo drives the handler through six cases. In case 3, two threads wait at a barrier and send the same request at once, while the provider takes 300 ms, so the second copy always arrives while the first is still in flight. Halfway through that call, the demo also counts the open client connections in PostgreSQL.
"""Drive the handler through the retry cases that matter."""
import threading
import time
from payments import create_payment, sql
from provider import FakeProvider
from reconcile import reconcile
provider = FakeProvider()
def send(label: str, key: str | None, amount: int, client: str = "shop-1") -> None:
code, body = create_payment(provider, client, key, {"amount": amount})
print(f"{label:<26} {code} {body}")
print("Case 1: the response is lost, the client retries")
send("first try (reply lost)", "k-100", 2500)
send("retry, same key and body", "k-100", 2500)
print("Case 2: the same key with a different body")
send("retry, amount changed", "k-100", 9900)
send("no key at all", None, 2500)
print("Case 3: two copies arrive at the same moment")
provider.delay = 0.3 # a slow provider widens the race window
results: list[tuple[int, str]] = []
gate = threading.Barrier(2)
def racer() -> None:
gate.wait()
results.append(create_payment(provider, "shop-1", "k-200", {"amount": 4000}))
threads = [threading.Thread(target=racer) for _ in range(2)]
for t in threads:
t.start()
time.sleep(0.15) # halfway through the provider call: count open connections
_, rows = sql("SELECT count(*) FROM pg_stat_activity WHERE backend_type ="
" 'client backend' AND pid <> pg_backend_pid()", ())
print(f"{'connections held mid-call':<26} {rows[0][0]}")
for t in threads:
t.join()
provider.delay = 0.0
for code, body in sorted(results):
print(f"{'concurrent copy':<26} {code} {body}")
send("retry after both finished", "k-200", 4000)
print("Case 4: the provider charged, but its reply was lost")
provider.fault = "lose_reply"
send("first try", "k-300", 1200)
send("retry before reconciling", "k-300", 1200)
reconcile(provider)
send("retry after reconciling", "k-300", 1200)
print("Case 5: the provider timed out before charging")
provider.fault = "timeout_before_charge"
send("first try", "k-400", 700)
reconcile(provider)
send("retry after reconciling", "k-400", 700)
print("Case 6: another client uses the same key text")
send("shop-2, key k-100", "k-100", 2500, client="shop-2")
print(f"charges at the provider: {len(provider.charges)}")
print(f"money taken: {sum(provider.charges.values())}")python demo.pyCase 1: the response is lost, the client retries
first try (reply lost) 201 {"id":"pay_GD2Qi3hGXDzSdMJhfnQ_CA","amount":2500}
retry, same key and body 201 {"id":"pay_GD2Qi3hGXDzSdMJhfnQ_CA","amount":2500}
Case 2: the same key with a different body
retry, amount changed 422 {"error":"key reused with a different body"}
no key at all 400 {"error":"Idempotency-Key header required"}
Case 3: two copies arrive at the same moment
connections held mid-call 0
concurrent copy 201 {"id":"pay_898gs0kwKxj6rjCdQRF8kQ","amount":4000}
concurrent copy 409 {"error":"key in use (in progress), retry later"}
retry after both finished 201 {"id":"pay_898gs0kwKxj6rjCdQRF8kQ","amount":4000}
Case 4: the provider charged, but its reply was lost
first try 503 {"error":"outcome unknown, retry with same key"}
retry before reconciling 409 {"error":"key in use (being confirmed), retry later"}
reconcile k-300: charge found, stored as done
retry after reconciling 201 {"id":"pay_P0KXO0X1S_esPxkEgPtdhA","amount":1200}
Case 5: the provider timed out before charging
first try 503 {"error":"outcome unknown, retry with same key"}
reconcile k-400: no charge found, key released
retry after reconciling 201 {"id":"pay_TQ5fpTQYm4vV5MKQ1jM-TQ","amount":700}
Case 6: another client uses the same key text
shop-2, key k-100 201 {"id":"pay_BO876vBbN7HKiI8D5OVO8w","amount":2500}
charges at the provider: 5
money taken: 10900Read the output against the requirements. Case 1 replays the same 201 body, so the shop that lost the first reply learns the payment ID it missed. Case 2 rejects the changed amount and the missing key. In case 3 no connection is open during the provider call, one copy charges and the other gets 409, and the later retry gets the stored result. In case 4 the provider charged but the handler never heard, so the first answer is 503 and the next is 409, until the reconciler finds the charge. In case 5 the provider never charged; the reconciler releases the key and the retry charges once. Case 6 shows scoping: shop-2 may use the text k-100 too. The last two lines are the real test: five payments, five charges, 10,900 taken.
06. Step 5: Inspect the table and expire old keys
Every key has ended in done. Expiry is a scheduled delete of finished keys older than the published retention period; here nothing is old enough yet. Never expire started or unknown rows this way, because they still need the reconciler.
docker exec -i idem-pg psql -U postgres <<'SQL'
SELECT client_id, key, status, response_code FROM idempotency_keys ORDER BY 1, 2;
DELETE FROM idempotency_keys
WHERE status = 'done' AND created_at < now() - interval '24 hours';
SQL client_id | key | status | response_code
-----------+-------+--------+---------------
shop-1 | k-100 | done | 201
shop-1 | k-200 | done | 201
shop-1 | k-300 | done | 201
shop-1 | k-400 | done | 201
shop-2 | k-100 | done | 201
(5 rows)
DELETE 0If psql cannot connect in step 1, the database is still starting: wait a few seconds and run the command again. To run the demo a second time, empty the table first with docker exec idem-pg psql -U postgres -c "TRUNCATE idempotency_keys". When you are done, remove the container with docker rm -f idem-pg.
07. Check your understanding
08. Apply it
The skill's practice project asks for an idempotent payment endpoint behind the three-service chain. Reuse this design and prove it with tests: drop the response after a successful mock payment and retry with the same key; retry with a changed amount and expect a rejection; make the provider time out after charging and show that reconciliation completes the payment with exactly one charge. Write down your key retention and the longest retry window of your clients, and check that the first is longer.
09. Review prompt
Without looking back, list the columns an idempotency-key table needs and the requirement behind each one. Explain why the claim is committed before the side effect, why no connection is held during it, what a duplicate should receive in each state (started, unknown, done, different fingerprint), and when it is safe to release a key whose outcome was unknown.
References
- Making retries safe with idempotent APIs (Amazon Builders' Library)
- The Idempotency-Key HTTP Header Field (IETF Internet-Draft, httpapi working group)
- Idempotent requests (Stripe API reference)
- INSERT, including ON CONFLICT (PostgreSQL documentation)
- JSON types: json and jsonb (PostgreSQL documentation)
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.