Idempotent Order Intake at the Edge
A retried POST should never place a second order. The client timed out, a proxy replayed the request, the phone flipped from Wi-Fi to cellular mid-flight — none of that is the trading desk’s problem. The fix is an idempotency key: the caller stamps each logical order with a unique value and repeats it on every retry, and the server promises to act on that key at most once.
Here it runs at the edge as a single Cloudflare Worker over one Workers KV namespace — no origin round-trip, no database to operate. This page is the working code; drop it into a Worker project and it runs.
The Worker #
The request lifecycle is three KV touches: check for a finished result, claim the key, then write the result and release the claim. A replay short-circuits on the first check; a concurrent retry that arrives mid-flight hits the pending marker and is told to back off instead of racing a duplicate through.
| |
The two TTLs do the real work. result: lives for 24 hours so retries stay idempotent across a realistic client window, while pending: expires in 30 seconds so a Worker evicted mid-request can’t wedge a key forever — the marker self-heals and the next retry succeeds. Validation runs after the claim so a malformed body releases the key rather than poisoning it.
Binding the namespace #
One KV namespace holds both the pending markers and the response cache. The binding name ORDERS is what the Worker reads as env.ORDERS.
| |
Create the namespace with wrangler kv namespace create ORDERS, paste the returned id, and wrangler deploy.
Proving it #
The contract is visible from the command line: submit once, retry under the same key, and compare. The first call returns 201 with a fresh orderId; the replay returns 200 with the identical body and an Idempotent-Replay: true header.
| |
Same key in, same receipt out — the second request never reaches the order-management gateway. That is the whole point: the edge absorbs the duplicate so the system of record never sees it.