Your Order API Needs More Than an Idempotency Key
An order API can accept an Idempotency-Key header on every request and still create a second order for the same intended purchase. Generate a fresh key after a timeout, and a server that deduplicates by key has no way to connect the retry to the first attempt. There is a separate server-side problem too. A lookup followed by an insert leaves a race if competing requests can both observe that the…
A server handling order API requests demonstrated how an idempotency key alone cannot guarantee a single order. Generating a new key after a timeout does not connect retries to the first attempt when using a server-side deduplication method. The SQLite database schema includes a unique constraint on the idempotency key, ensuring its durability alongside the order record.
The Python script maintains a single transaction for both the lookup and insertion of the order data. The test server's CREATE TABLE statement defines the orders table with columns for id, request_key, sku, and amount. The create_order function checks the idempotency key's format and whether the provided body contains a SKU present in the CATALOG.
If the key is valid and the SKU is known, the function attempts to fetch an existing order with the same key. If found, the transaction is committed, and a 200 status is returned with the same order details. Otherwise, a new order is inserted and a 201 status is returned with the generated order ID. The server returns distinct status codes to differentiate between creating a new order (201) and recovering an existing one (200).
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.