Direct Answers
Component that generates and validates the idempotency key: The client (or API gateway) generates the key before the first request, typically as a UUID or a hash of the business intent (e.g., user ID + action + timestamp bucket). The serverless function handler validates it on every invocation by checking the persistent store before performing the write.
Where completed-key state is stored: In an external, durable store that survives function instance turnover—relational database (PostgreSQL, MySQL), DynamoDB, Redis with persistence, or a dedicated key-value service. The function instance itself is stateless and cannot retain the key across retries.
Distinguishing a platform retry from a legitimate repeat request: A platform retry carries the same idempotency key (often via an Idempotency-Key header) that the client sent on the original call. A legitimate repeat request either lacks the key or presents a different key, signaling a new business intent.
Minimal Implementation Pattern
- Client side: Generate a UUIDv4 (or deterministic hash) for each user-initiated action. Send it as
Idempotency-Key header on the initial request and on any client-side retry.
- Function entry: Extract the header. If missing, reject with
400 or treat as a new request (accepting duplication risk).
- Atomic check-and-set: In the persistent store, attempt to insert a row with the key as primary key and a status column (
pending, completed, failed). Use a conditional write (e.g., INSERT ... ON CONFLICT DO NOTHING or DynamoDB ConditionExpression).
- Branch:
- Insert succeeded → this is the first execution. Perform the business write, then update the row to
completed with the result payload.
- Insert failed (key exists) → read the row. If
completed, return the stored result. If pending, another invocation is in progress; wait briefly and re-read, or return 409.
- Response: Always return the same HTTP status and body for a given key so the client sees exactly-once semantics.
Verification Steps
- Deploy the function and invoke it once with a fresh key. Confirm the resource is created and the key row shows
completed.
- Re-invoke with the same key (simulate platform retry). Verify no new resource appears and the original result is returned.
- Invoke with a different key. Verify a new resource is created.
- Check provider logs: ensure the
Idempotency-Key header arrives on retries (some platforms strip or rename it).
One Diagnostic Detail Needed
What is your hosting platform (Vercel, Netlify, AWS Lambda@Edge, Cloudflare Workers, etc.)? Provider-specific retry limits, timeout values, and whether the Idempotency-Key header is preserved on retry change the exact implementation and whether you need a fallback (e.g., deriving a key from request body hash when the header is missing).