What this prompt does
This prompt makes the AI act as a senior backend engineer that implements idempotency keys for a specific endpoint, returning working code instead of pseudocode. You provide the [api_name], your [stack], the key [ttl], and the [duplication_risk] - what actually breaks if a request runs twice - and it produces the migration, the middleware or handler, and the test file, each fenced and copy-ready.
The six deliverables are ordered to cover the full lifecycle of a key: accept and validate the Idempotency-Key header, persist the key with a hash of the request body and the stored response, enforce a [ttl] cleanup so old keys do not grow unbounded, handle races via a DB unique constraint so two concurrent requests cannot both execute, replay the stored response with its original status code, and test first call, exact replay, in-flight collision, and body-mismatch rejection. The structure works because it pushes the correctness into the database, not the application layer - the unique constraint is what actually stops the double-write under load.
When to use it
- You are shipping a POST or PUT with real side effects - charges, emails, provisioning - where a retry must not run twice.
- A flaky network is turning a single client request into duplicate operations.
- You need safe client retries on a payments or checkout endpoint.
- You want race handling that survives concurrent requests, not just a naive existence check.
- You need a test suite that proves replay, collision, and body-mismatch behaviour before launch.
Example output
You get three fenced code blocks: a database migration creating the idempotency table with a unique constraint on the key, the middleware or handler that validates the Idempotency-Key header, hashes the body, stores and replays responses, and applies the [ttl] cleanup, plus a test file covering the first call, an exact replay, an in-flight collision, and a body-mismatch rejection.
Pro tips
- Set
[duplication_risk]concretely - "the customer is charged twice" tells the model the stakes and pushes it toward stronger guarantees. - Put your effort into deliverable four: insist on a DB unique constraint, not an application-level check, because only the constraint stops the double-write under concurrency.
- Pick a
[ttl]that matches how long clients realistically retry; 24 hours is a safe default for payments, shorter for low-stakes calls. - Match
[stack]to your real database so the migration and constraint syntax are usable as written. - Make sure the stored response includes the original status code, or replays will look different from the first call.
- If the body-mismatch test is missing, ask for it - reusing a key with a different payload should be rejected, not silently replayed.