← Back to FastAPI, page 3

fastapi-0047 · Hard senior

How do you make a POST endpoint such as a payment idempotent in FastAPI using an Idempotency-Key header?

Clients send a unique Idempotency-Key header with each logical operation. The server stores the key with a hash of the request and the resulting response; a repeat with the same key and same body returns the stored response without redoing the work, the same key with a different body is rejected (422 or 409), and concurrent duplicates are blocked with an atomic insert or lock. Keys expire after a retention window, and storage must be shared and durable (database unique constraint or Redis SET NX).

Full answer

Networks fail between "server did the work" and "client got the answer". Clients then retry. Without protection, a retry of POST /payments charges twice. Idempotency means repeating the same request has the same effect as sending it once.

Protocol (popularised by Stripe, drafted at the IETF):

  1. Client generates a unique key (UUID) per logical operation and sends Idempotency-Key: <key>. Retries reuse the same key.
  2. Server, before doing work, tries to record the key atomically: INSERT ... ON CONFLICT DO NOTHING on a table with a unique key, or Redis SET key value NX EX 86400.
  3. If it created the record, it runs the operation, then stores status code and body under the key.
  4. If the key exists and the stored request fingerprint matches: return the stored response (or 409 if the first attempt is still in progress).
  5. If the key exists but the body differs: reject (the client reused a key by mistake).

Details that matter

  • Atomic claim. A check-then-insert race lets two simultaneous retries both pass. The unique constraint or NX is what makes it safe.
  • Fingerprint the request (hash of method, path, body) so key reuse with different data is detected.
  • Store failures too, or define which errors may be retried with the same key (e.g. 5xx before side effects may be safe to re-run).
  • Same transaction: record the result in the same database transaction as the business change when possible, so "paid but no record" cannot happen. External side effects (a call to a payment gateway) need the gateway's own idempotency key passed through.
  • Retention: keep keys long enough for retries (24 hours is common).
  • Scope keys per user or API client so keys from different tenants never collide.
  • GET, PUT and DELETE are idempotent by definition; the key is for POST and PATCH.

In FastAPI this fits a dependency that reads the header and returns a helper object, or a small decorator around the endpoint.

python
import hashlib
import threading
from typing import Annotated

from fastapi import Depends, FastAPI, Header, HTTPException
from fastapi.testclient import TestClient
from pydantic import BaseModel, Field

app = FastAPI()
STORE: dict[str, dict] = {}              # in production: a table with a UNIQUE key, or Redis SET NX
LOCK = threading.Lock()
charges: list[int] = []


class PaymentIn(BaseModel):
    roll_no: str
    amount: int = Field(gt=0)


def idempotency(body: PaymentIn, key: Annotated[str, Header(alias="Idempotency-Key", min_length=8)]):
    fingerprint = hashlib.sha256(body.model_dump_json().encode()).hexdigest()
    with LOCK:                                                   # atomic claim
        record = STORE.get(key)
        if record is None:
            STORE[key] = {"fingerprint": fingerprint, "response": None}
            return {"key": key, "replay": None}
    if record["fingerprint"] != fingerprint:
        raise HTTPException(status_code=422, detail="Idempotency-Key reused with a different request")
    if record["response"] is None:
        raise HTTPException(status_code=409, detail="A request with this key is still in progress")
    return {"key": key, "replay": record["response"]}


@app.post("/payments", status_code=201)
def pay(body: PaymentIn, idem: Annotated[dict, Depends(idempotency)]):
    if idem["replay"] is not None:
        return idem["replay"]
    charges.append(body.amount)                                  # the side effect, done once
    response = {"payment_id": len(charges), "amount": body.amount, "status": "paid"}
    STORE[idem["key"]]["response"] = response
    return response


c = TestClient(app)
h = {"Idempotency-Key": "9f1c2b7e-0001"}
data = {"roll_no": "BCA-17", "amount": 1500}
print(c.post("/payments", json=data, headers=h).json())
print(c.post("/payments", json=data, headers=h).json())        # retry after a lost response
print("charges made:", charges)
r = c.post("/payments", json={**data, "amount": 9999}, headers=h)
print(r.status_code, r.json())
print(c.post("/payments", json=data, headers={"Idempotency-Key": "9f1c2b7e-0002"}).json()["payment_id"])

Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. A dict and a lock stand in for the database unique constraint; with several workers the claim must be an atomic insert or Redis SET NX. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): {'payment_id': 1, 'amount': 1500, 'status': 'paid'} {'payment_id': 1, 'amount': 1500, 'status': 'paid'} charges made: [1500] 422 {'detail': 'Idempotency-Key reused with a different request'} 2

Key points

  • Same key + same request returns the stored response
  • Claim the key atomically (unique constraint or Redis NX)
  • Fingerprint the body; reject key reuse with different data
  • Commit result and business change together; pass keys to gateways
  • Scope per client and expire after a retention window

Common mistakes

  • Checking for the key and inserting it in two separate steps, leaving a race
  • Not comparing the request body, so a reused key silently returns the wrong result
  • Keeping keys in process memory with several workers
  • Treating the key as an authentication token
  • Forgetting to pass an idempotency key on to the payment gateway

Follow-ups

  • What should happen if the first attempt crashed halfway?
  • How long should you keep idempotency records?
  • How is this different from deduplicating in a message queue consumer?

Tips

  • Explain the lost-response scenario first
  • Highlight the atomic claim
  • Cover fingerprinting, scope and retention