Add idempotency to an order-processing endpoint
In this article (3 sections)
A client may not know whether a timed-out request completed. An idempotency key lets it retry without creating a second order.
Compare replay and mismatch
The integration lab submits one key three times.
from integration_cases import order_idempotency_case
result = order_idempotency_case()
assert [x["status"] for x in result["responses"]] == [201, 200, 409]
assert result["records"] == 1
assert result["replay_same"] is True
assert result["changed_conflict"] is TrueExact replay returns ORD-1; the same key with changed quantity conflicts.
Scope keys to caller/tenant and operation. Compute a canonical request digest, reserve the key atomically, execute once and store status/result. Concurrent duplicates should wait or return an in-progress state. Define expiry longer than realistic retry windows.
Do not cache authorization blindly: revalidate caller access to the stored result. Decide how failed and partial attempts are represented. Propagate the key downstream where supported and reconcile ambiguous writes.
The FDE for Freshers course applies idempotency to APIs, webhooks and background jobs.
Exercise
Implement the ledger in SQLite with a unique constraint. Race two identical requests and prove one business record plus deterministic responses.
Continue learning
This article is part of the FDE integration and deployment foundations sequence. Use the neighbouring tasks when you need the prerequisite or the next application.
- Review the prerequisite or neighbouring task in Implement bounded retries with backoff and jitter.
- Continue with Build a local integration sandbox with synthetic data.
Reference: HTTP Semantics RFC 9110.
Pankit Kumar has 10 years in Data Science & AI, building and shipping production systems in regulated pharma and clinical environments. He is a freelance trainer at Boston Institute of Analytics, AnalytixLabs and Scaler, and has taught this material to thousands of working professionals.
This article is part of our FDE for Freshers programme — 6–7 months. Build your engineering foundations, then take AI from discovery to delivery.
Explore FDE for Freshers