Idempotency keys for a payment or order creation endpoint
Adds idempotency to an endpoint that creates payments or orders, so a double click, a mobile retry or a network timeout never charges twice or creates a duplicate order. Returns the key storage table, the request handling code, concurrency handling and tests. Use it on any checkout, wallet top-up or booking endpoint.
The output this prompt produced, unedited.
The prompt
Constraints first
The same key with the same request body returns the stored response and never runs the action twice.
The same key with a different request body returns 422 and runs nothing.
Two simultaneous requests with one key: exactly one runs; the other waits or gets 409, never a second charge.
Keys expire after a set time, and expiry never deletes a key whose request is still running.
No card or bank details are stored in the idempotency record.
Inputs
Language, framework and database: [e.g. Node.js with Fastify and PostgreSQL]
Endpoint: [e.g. POST /orders, which reserves stock, calls the payment provider and writes an order]
Current code: [paste the handler]
How clients will send the key: [e.g. an Idempotency-Key header, a UUID generated per checkout attempt]
Key lifetime: [e.g. 24 hours]
Build
A table for keys: key, user or account ID, request hash, status (in progress, done, failed), response code, response body, created and expiry times, with a unique index on key plus user.
Handler flow: validate the key format, insert the key as in progress inside a transaction, run the action, store the response, return it.
On a duplicate insert: compare request hashes, then return the stored response, a 409 if still in progress, or 422 if the body differs.
What happens when the action fails half way, such as the payment succeeding but the order write failing, and how a retry recovers.
Pass the same key on to the payment provider if it supports one.
A clean-up job for expired keys.
Output format
Schema and migration.
Middleware or wrapper code, then the updated handler.
A sequence of steps for the double-click case and the timeout-retry case.
Tests: first call, replay, body mismatch, two parallel calls, failure part way, expired key.
idempotency keyduplicate payment preventionapi retriesorder creation endpointconcurrency controlsafe api design
How to run this
Copy the prompt and paste it into Gemini, then set the aspect ratio to 3:4. No reference photo is needed for this one.
The prompt is written in Markdown with each part under its own heading, which is what the copy action hands over. Change one section at a time, keeping the rest intact, so you can tell which change did the work.