Lesson 28 of 59API design in depth
Safe Retries with Idempotency Keys
Make POST endpoints safe to retry: the Idempotency-Key header, a race-free Postgres claim, replaying responses, and keys for external side effects.
A customer taps Pay on a slow train. Your API charges the card and commits the order, but the response dies in a tunnel. The app sees a timeout and does what every good client does: it retries. Without protection, the customer now has two orders and two charges, and support has a refund to process. Retries are not rare edge cases. Mobile networks drop responses, HTTP client libraries retry on connection resets, and load balancers and service meshes can retry on your behalf. This lesson builds the standard fix, idempotency keys, properly: the race-free version, the version that survives crashes, and the version that works when the side effect is a payment provider you cannot roll back.
Why retries create duplicates
The client's problem is that a timeout carries no information. It cannot tell these three cases apart:
- The request never reached the server.
- The server received it and crashed before committing.
- The server committed, and only the response was lost.
In cases 1 and 2, retrying is correct. In case 3, retrying creates a duplicate. The client has to retry to cope with 1 and 2, so the server has to make case 3 harmless.
The customer taps Pay once.
HTTP already classifies methods. RFC 9110 defines GET, HEAD, OPTIONS, TRACE, PUT and DELETE as idempotent: sending the same request twice leaves the server in the same state as sending it once. POST and PATCH are not. That is why some clients and proxies will automatically retry a PUT but not a POST. You saw the method table in Designing a CRUD API, so the point here is narrower: idempotency is about state, not about getting the same response. A second DELETE may return 404 and still be idempotent.
So how do you make a POST safe? Sometimes you can avoid the problem with design. If the client generates the resource id (PUT /orders/7c1e... with a client-chosen UUID), the request becomes naturally idempotent, and a natural unique constraint does the rest. When the operation really is "do this action", such as charge, transfer, send, you need an explicit key.
The Idempotency-Key header
The client generates a unique key for each logical operation, usually a UUIDv4, and sends it in an Idempotency-Key header. Every retry of that operation reuses the same key. A new operation, even an identical-looking one, gets a new key.
POST /orders HTTP/1.1
Content-Type: application/json
Idempotency-Key: 7c1e4b2a-0f43-4a8e-9a77-1d2b5c9e6f10
{"sku": "KET-001", "qty": 1}Stripe popularised this, and most payment APIs now copy it. The IETF httpapi working group is standardising the header in draft-ietf-httpapi-idempotency-key-header. It is still an Internet-Draft, not an RFC, so say "the draft" in design docs. It recommends these responses, and they are a good default:
| Situation | Response |
|---|---|
| Key missing on an endpoint that requires one | 400 Bad Request, linking to your docs |
| Same key, same request, first one finished | Replay the stored status and body |
| Same key, first request still running | 409 Conflict (the client retries later) |
| Same key, different request body | 422 Unprocessable Content |
The last row matters. A key reused with a different body is a client bug, for example a key stored per screen instead of per operation. Detecting it requires a fingerprint: a hash of the method, path and a canonical form of the body, stored next to the key.
On the client, the classic bug is generating the key inside the retry loop. Generate it when the user starts the operation (when the checkout form is created, say), keep it with the pending operation, and only throw it away when you get a definite answer.
What does this print?
import uuid
sent = []
def post_order(body, key):
sent.append(key)
if len(sent) < 3:
raise TimeoutError
def place_order(body):
for attempt in range(3):
key = str(uuid.uuid4())
try:
return post_order(body, key)
except TimeoutError:
continue
place_order({"sku": "KET-001"})
print(len(set(sent)))The race: read-then-write is not enough
The obvious implementation looks up the key, and if it is not there, does the work and stores the key. It passes every single-request test. It fails the one case that matters: two copies of the same request arriving at the same moment, which is exactly what aggressive retries produce.
Run this. Each request is a generator, and every yield is a point where another worker could run. The interleaving lets both requests check before either stores.
Press Run (⌘ Enter) to see what happens.Notice that the buggy version has a primary key on the key table. The constraint fires, but only after the second charge has happened. The rule: the unique constraint must be the first thing that touches the key, before any side effect. INSERT ... ON CONFLICT DO NOTHING is an atomic "claim if free". Exactly one request can win it, however many workers you run, because the database's unique index decides, not your Python code.
The server algorithm
Here is the table. Scope the key by the caller: the primary key is (user_id, key), not key alone.
CREATE TABLE idempotency_keys (
user_id bigint NOT NULL,
key text NOT NULL,
fingerprint text NOT NULL,
status text NOT NULL DEFAULT 'in_progress',
response_code int,
response_body text,
locked_at timestamptz NOT NULL DEFAULT now(),
created_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (user_id, key)
);
CREATE INDEX ON idempotency_keys (created_at); -- for the cleanup jobScoping is a security issue, not tidiness. If keys were global, a second customer who happened to reuse a key (or guessed one) would get the first customer's stored response replayed to them, order details and all.
The handler logic, in order:
- Require the header, and compute the fingerprint.
- Try to claim
(user_id, key)withINSERT ... ON CONFLICT DO NOTHING RETURNING. - If the claim fails, load the row. Different fingerprint:
422. Still in progress:409. Done: replay the stored code and body. - If the claim succeeds, do the work, store the response on the row, commit, and return.
This simulation runs the full algorithm, including a request that crashes halfway and a key that expires. The clock is fake so you can see time pass.
Press Run (⌘ Enter) to see what happens.Read the output line by line. The second call sends the same fields in a different order and still replays, because the fingerprint uses canonical JSON (sort_keys=True). The crashed request leaves a row stuck in_progress, so a retry ten seconds later gets 409; after the lock timeout a retry takes over the claim and finishes the job. And a day later the key has expired, so the "retry" creates a fourth order. Your key lifetime must be longer than any client's retry window. Stripe documents 24 hours, which is a sensible default; whatever you choose, publish it.
The key has never been seen. The first request to insert it wins. Everyone else hits the unique constraint.
The FastAPI implementation
Put the mechanics in one module and keep the route readable. A dependency enforces the header (FastAPI's own missing-header error is a 422, and the draft wants 400, so make the parameter optional and raise yourself).
import hashlib
import json
from typing import Annotated
from fastapi import Header, HTTPException
from fastapi.responses import JSONResponse
from sqlalchemy import text
from sqlalchemy.ext.asyncio import AsyncSession
def require_idempotency_key(
idempotency_key: Annotated[str | None, Header(max_length=255)] = None,
) -> str:
if not idempotency_key:
raise HTTPException(400, "This endpoint requires an Idempotency-Key header")
return idempotency_key
def fingerprint(method: str, path: str, payload: dict) -> str:
canonical = json.dumps(payload, sort_keys=True, separators=(",", ":"))
return hashlib.sha256(f"{method} {path} {canonical}".encode()).hexdigest()
async def claim(session: AsyncSession, user_id: int, key: str, fp: str) -> JSONResponse | None:
"""Return a stored response to replay, or None if this request now owns the key."""
params = {"user_id": user_id, "key": key, "fp": fp}
claimed = await session.scalar(
text("""
INSERT INTO idempotency_keys (user_id, key, fingerprint)
VALUES (:user_id, :key, :fp)
ON CONFLICT (user_id, key) DO NOTHING
RETURNING key
"""),
params,
)
if claimed is not None:
return None # first time we have seen this key
row = (
await session.execute(
text("""
SELECT fingerprint, status, response_code, response_body
FROM idempotency_keys WHERE user_id = :user_id AND key = :key
"""),
params,
)
).one()
if row.fingerprint != fp:
raise HTTPException(422, "Idempotency-Key was already used with a different request")
if row.status != "done":
raise HTTPException(409, "A request with this Idempotency-Key is still in progress")
return JSONResponse(
json.loads(row.response_body),
status_code=row.response_code,
headers={"Idempotent-Replayed": "true"},
)
async def complete(session: AsyncSession, user_id: int, key: str, code: int, body: dict) -> None:
await session.execute(
text("""
UPDATE idempotency_keys
SET status = 'done', response_code = :code, response_body = :body
WHERE user_id = :user_id AND key = :key
"""),
{"user_id": user_id, "key": key, "code": code, "body": json.dumps(body)},
)The route claims the key, does the work and stores the response in one transaction:
@router.post("/orders", status_code=201, response_model=OrderOut)
async def place_order(
body: OrderIn,
user: CurrentUser,
session: DbSession,
key: Annotated[str, Depends(require_idempotency_key)],
):
fp = fingerprint("POST", "/orders", body.model_dump(mode="json"))
async with session.begin():
replay = await claim(session, user.id, key, fp)
if replay is not None:
return replay
order = await orders_service.create(session, user.id, body)
out = OrderOut.model_validate(order).model_dump(mode="json")
await complete(session, user.id, key, 201, out)
return outTwo details. response_model=OrderOut goes on the decorator rather than as a return annotation, because the function sometimes returns a JSONResponse (FastAPI passes Response objects through untouched). And the fingerprint uses the parsed body, so formatting differences and defaulted fields do not count as a different request.
Here is the subtle part, and it is a good one to understand. Because the claim and the work share one transaction, a concurrent duplicate never sees in_progress. In PostgreSQL, when a second INSERT ... ON CONFLICT hits a key that another uncommitted transaction has just inserted, it waits for that transaction to finish. If the first commits, the second sees a conflict and replays the stored response. If the first rolls back, the claim disappears with it and the second request does the work instead. Rolling back on errors also means you never store a response for a request that failed halfway. Tested against a real Postgres, two simultaneous requests with one key both got 201 with the same order id, one of them marked Idempotent-Replayed: true, and one row was written.
The cost is that the duplicate holds a database connection while it waits, so this design is right when the work is short and local: rows in your own database. For anything slow or external, use the next pattern.
External side effects and recovery points
A card charge cannot be rolled back with your transaction. If you call the payment provider inside the transaction and then crash, your database forgets the claim while the money has moved. So split the request into phases, each committed separately, and record which phase you reached. Brandur Leach's well-known write-up of Stripe-style keys calls these recovery points.
tx 1: claim key, status = in_progress, recovery_point = 'started', create order row (pending)
COMMIT
call: provider.charge(amount, idempotency_key = f"order-{order_id}-charge")
tx 2: store charge id, order = paid, recovery_point = 'charged'
COMMIT
tx 3: enqueue receipt email (outbox row), store response, status = done
COMMITNow the claim is committed before the slow part, so concurrent duplicates see in_progress and get 409, and nothing holds a connection open across a network call. When a retry reclaims an abandoned key after the lock timeout, it reads recovery_point and resumes from there rather than starting over.
The step in the middle is the one people miss: pass your own idempotency key downstream. Derive it from something stable, such as the order id, never a fresh UUID. If the original worker charged the card and died before transaction 2, the resuming request calls the provider again with the same key, and the provider replays the original charge instead of creating a second one. Stripe and most payment APIs accept a key for exactly this. Idempotency is only as strong as the weakest call in the chain.
For things with no idempotency support at all, such as sending an email through an old SMTP relay, you cannot get exactly-once. Make it at-least-once and rare: write an outbox row in the same transaction as your state change, and let a worker send it and mark it sent. Task Queues with Celery covers why workers must be idempotent too, and Design a Payment System shows the same ideas at the scale of a ledger.
Storage, expiry and other homes for the pattern
Postgres or Redis? Postgres is the default when the side effect lives in Postgres, because the claim can share the transaction. Redis is fast, and SET idem:u1:k1 in_progress NX EX 86400 gives you an atomic claim with a built-in TTL. But the Redis write is not in your database transaction, so a crash between the two leaves them disagreeing, and an asynchronously replicated Redis can lose recent keys on failover, which silently re-opens the duplicate window. Use Redis when the operation is cheap to duplicate occasionally or when it is purely a fast first filter in front of a database constraint.
Cleanup. Delete expired rows with a scheduled job in batches (DELETE ... WHERE created_at < now() - interval '24 hours' with a LIMIT via a subquery), using the index on created_at. Partitioning the table by day and dropping old partitions is the high-volume version.
What to store. Store successes and deterministic business failures, such as "card declined", so a retry gets the same answer. Do not store a response for validation errors (no work started, and the claim should not even be made) or for failures where you rolled back, so the client can retry and succeed.
The same idea elsewhere. A webhook receiver should dedupe on the sender's event id with a unique constraint, because providers deliver at least once. A queue consumer can do the same with an "inbox" table of processed message ids. It is always the same move: let a unique index decide who goes first.
Testing it for real
A single-request test proves nothing about the race. Fire the same request twice at once against a real database, with a connection pool so the two requests really use separate connections.
import asyncio
import httpx
import pytest
from sqlalchemy import text
from app.main import app
@pytest.mark.anyio
async def test_concurrent_duplicates_create_one_order(db_session, auth_headers):
transport = httpx.ASGITransport(app=app)
async with httpx.AsyncClient(transport=transport, base_url="http://test") as client:
headers = auth_headers | {"Idempotency-Key": "7c1e4b2a-0f43-4a8e-9a77-1d2b5c9e6f10"}
body = {"sku": "KET-001", "qty": 1}
first, second = await asyncio.gather(
client.post("/orders", json=body, headers=headers),
client.post("/orders", json=body, headers=headers),
)
assert {first.status_code, second.status_code} <= {201, 409}
assert 201 in (first.status_code, second.status_code)
count = await db_session.scalar(text("SELECT count(*) FROM orders"))
assert count == 1The assertion allows 409 on purpose: with the single-transaction design both get 201, with the phased design the loser may get 409, and either is correct. What is never correct is two orders. Add tests for the 422 (same key, different body), the 400 (missing key), and a crash after the claim (patch the service to raise, then retry and check the order is created exactly once). Testing with Real Databases shows how to give these tests their own Postgres.
Match each request to the response the server should give.
key alone as its primary key. What is the most serious consequence?Order the phases of a request that charges a card through an external provider.
- Tap the steps below in the right order.
INSERT ... ON CONFLICT DO NOTHING do in PostgreSQL?- idempotent
- An operation whose effect on server state is the same whether it runs once or many times. The responses may still differ.
- Idempotency-Key
- A request header carrying a client-generated id for one logical operation, reused on every retry. Standardised in an IETF draft, not yet an RFC.
- request fingerprint
- A hash of the method, path and canonical body stored with the key, used to reject a key reused for a different request.
- atomic claim
- Taking ownership of a key with a single statement that only one caller can win, such as
INSERT ... ON CONFLICT DO NOTHINGor RedisSET NX. - recovery point
- A recorded phase of a multi-step request, so a retry after a crash can resume instead of repeating finished work.
- lock timeout
- How long an in-progress claim is honoured before another request may take it over, so a crashed worker cannot block a key forever.
- outbox
- A table written in the same transaction as a state change, read by a worker that performs the external side effect afterwards.