PK!3idempotent-orders.ts/** * Idempotent order intake at the edge. * * A Cloudflare Worker that accepts order submissions over HTTP and guarantees * at-most-once processing per client-supplied Idempotency-Key. A retried POST * — the client timed out, the network blipped, a proxy replayed it — returns * the original response instead of placing a second order. * * Storage is a single Workers KV namespace. The first request for a key writes * a short-lived "pending" marker, processes the order, then overwrites it with * the final response. Concurrent retries that arrive mid-flight see the marker * and are told to back off rather than racing a duplicate through. */ interface Env { ORDERS: KVNamespace; } interface OrderRequest { symbol: string; side: "buy" | "sell"; quantity: number; } interface OrderResult { orderId: string; status: "accepted"; symbol: string; side: "buy" | "sell"; quantity: number; acceptedAt: string; } // Keep a completed response addressable by its key for 24h of retries. const RESULT_TTL_SECONDS = 60 * 60 * 24; // A pending marker should outlive a single request but expire quickly if the // Worker is evicted mid-flight, so a stuck key self-heals. const PENDING_TTL_SECONDS = 30; const json = (body: unknown, status = 200): Response => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" }, }); function validate(body: unknown): OrderRequest | null { if (typeof body !== "object" || body === null) return null; const { symbol, side, quantity } = body as Record; if (typeof symbol !== "string" || symbol.length === 0) return null; if (side !== "buy" && side !== "sell") return null; if (typeof quantity !== "number" || !Number.isInteger(quantity) || quantity <= 0) return null; return { symbol, side, quantity }; } async function placeOrder(order: OrderRequest): Promise { // Stand-in for the real order-management call. In production this is where the // FIX session or OMS gateway lives; here we just mint a deterministic receipt. return { orderId: crypto.randomUUID(), status: "accepted", symbol: order.symbol, side: order.side, quantity: order.quantity, acceptedAt: new Date().toISOString(), }; } export default { async fetch(request: Request, env: Env): Promise { if (request.method !== "POST") { return json({ error: "method_not_allowed" }, 405); } const key = request.headers.get("Idempotency-Key"); if (!key) { return json({ error: "missing_idempotency_key" }, 400); } // Replay path: a finished result already exists for this key. const cached = await env.ORDERS.get(`result:${key}`); if (cached) { return new Response(cached, { status: 200, headers: { "content-type": "application/json", "Idempotent-Replay": "true" }, }); } // Claim the key. If another in-flight request already claimed it, ask the // caller to retry once the first one settles. const pending = await env.ORDERS.get(`pending:${key}`); if (pending) { return json({ error: "in_progress", retryAfter: PENDING_TTL_SECONDS }, 409); } await env.ORDERS.put(`pending:${key}`, "1", { expirationTtl: PENDING_TTL_SECONDS }); const order = validate(await request.json().catch(() => null)); if (!order) { await env.ORDERS.delete(`pending:${key}`); return json({ error: "invalid_order" }, 422); } const result = await placeOrder(order); const body = JSON.stringify(result); await env.ORDERS.put(`result:${key}`, body, { expirationTtl: RESULT_TTL_SECONDS }); await env.ORDERS.delete(`pending:${key}`); return new Response(body, { status: 201, headers: { "content-type": "application/json" } }); }, }; PK!wWW readme.json{ "schemaVersion": 1, "title": "Idempotent Order Intake at the Edge", "description": "A Cloudflare Worker that guarantees at-most-once order processing per Idempotency-Key, backed by a single Workers KV namespace.", "url": "https://george.tsiokos.com/code/2026/idempotent-orders/", "copyright": "© 2026 George Tsiokos. All rights reserved.", "author": "George Tsiokos", "siteUrl": "https://george.tsiokos.com", "commit": "cbe0089821a5c507cde517d7105b18da6c53ad98", "created": "2026-06-11T00:00:00Z", "lastModified": "2026-07-01T17:00:22Z", "generatedAt": "2026-07-01T17:00:55Z", "fileCount": 3, "totalBytes": 4838, "files": [ { "name": "idempotent-orders.ts", "bytes": 3813, "sha256": "663bca9649da740a4fe4cb9ab0296c3e964c955e935f66c254d031ee6195bbe7" }, { "name": "submit-order.sh", "bytes": 654, "sha256": "f485503412e44ecad14b8431b85c52d22f72639bafdc0ab7545a949faaddca6f" }, { "name": "wrangler.toml", "bytes": 371, "sha256": "6fd82c00fa6fd1a9f165868fd8a2de86d9dfb66a8cc3f1989a5cbfeb33150e3e" } ] } PK!e~submit-order.sh#!/usr/bin/env bash # Submit the same order twice under one Idempotency-Key. # The first call returns 201 with a fresh orderId; the replay returns 200 with # the identical body and an "Idempotent-Replay: true" response header. set -euo pipefail ENDPOINT="${1:-https://idempotent-orders.example.workers.dev}" KEY="$(uuidgen)" submit() { curl -sS -D - -o /tmp/order-body.json \ -X POST "$ENDPOINT" \ -H "Idempotency-Key: $KEY" \ -H "content-type: application/json" \ -d '{"symbol":"MSFT","side":"buy","quantity":100}' echo cat /tmp/order-body.json echo } echo "# First submission" submit echo "# Retry with the same key" submit PK!F@ss wrangler.tomlname = "idempotent-orders" main = "idempotent-orders.ts" compatibility_date = "2026-01-01" # A single KV namespace holds both the short-lived "pending" markers and the # 24h response cache. Create it once, then paste the id below: # wrangler kv namespace create ORDERS [[kv_namespaces]] binding = "ORDERS" id = "" [observability] enabled = true PK!3idempotent-orders.tsPK!wWW readme.jsonPK!e~submit-order.shPK!F@ss Rwrangler.tomlPK