Writing Idempotency Key Code for Your API With LLMs in November 2026: Claim the Key Before You Do the Work, Replay the Saved Response, and Reject a Reused Key With a Different Body
A customer taps "Pay" on a slow mobile connection. The request reaches your server, the charge goes through, and then the response is lost on the way back. The app retries. Without protection, you have just charged that customer twice. Idempotency keys are the standard fix: the client sends a unique key with each logical operation, and the server makes sure that operation happens at most once no matter how many times the request arrives.
Ask an LLM to "add idempotency keys to this endpoint" and you will usually get something that looks right: read the header, check a table, do the work, save the result. The bugs hide in the order of those steps and in what happens when two copies of the same request arrive at the same moment. This guide covers how to prompt for idempotency key code, what to check in the draft, and the tests that prove it actually works. Examples use Node.js and PostgreSQL, but the design carries over to any stack.
Pressing an elevator button five times still calls one elevator. An idempotent API endpoint should behave the same way when a request is retried. Image: Elevator buttons Norwegian by Peter Fiskerstrand, CC BY-SA 4.0, via Wikimedia Commons.
What an idempotency key has to guarantee
An operation is idempotent when doing it twice has the same effect as doing it once. GET, PUT, and DELETE are meant to be idempotent by design. POST is not: "create an order" twice creates two orders. An idempotency key turns a POST into something safe to retry by giving the server a way to recognize "I have seen this exact operation before."
A correct implementation has to cover four cases:
- First request: no record of the key exists. Do the work once and store the result.
- Retry after success: the key exists with a saved response. Return that saved response without doing the work again.
- Retry while the first is still running: the key exists but has no result yet. Do not start a second copy. Tell the client to wait and retry.
- Same key, different request: the client reused a key for a different operation, usually a bug. Reject it instead of returning an unrelated old response.
Most first drafts from a model handle the first two cases and quietly get the last two wrong.
Write the prompt around the failure cases
The model fills gaps with the simplest pattern it has seen, which is often "SELECT, then if missing, INSERT." Give it the details that force a safer design. A prompt that works well:
Add Idempotency-Key support to POST /orders in this Express + PostgreSQL app.
Requirements:
- Header name: Idempotency-Key. Required on this endpoint; return 400 if missing.
Accept only 1-255 chars of [A-Za-z0-9_-].
- Scope keys per authenticated account: the same key from two accounts is two keys.
- Claim the key atomically BEFORE doing any work, using INSERT ... ON CONFLICT
DO NOTHING on a unique (account_id, key) constraint. No SELECT-then-INSERT.
- Store a SHA-256 hash of the canonical request (method, path, body).
Same key + different hash: return 422.
- Same key, still in progress: return 409 with Retry-After: 1. Do not run the work.
- Same key, completed: return the stored status code and body exactly.
- Save the response in the same database transaction as the order insert.
- Do not cache 5xx responses; release the key so the client can retry.
- Keys expire after 24 hours (cleanup job).
- Write tests for: first call, retry, concurrent duplicate, key reuse with a
different body, failure then retry.
Here is the current handler and schema: [paste them]
Pasting the real handler and schema matters. Without them the model invents table names, an ORM you do not use, and an error format that does not match the rest of your API.
Claim the key before you do the work
The most common bug in generated code is a race condition that looks like this:
// Looks fine, is not safe
const existing = await db.query(
'SELECT * FROM idempotency_keys WHERE account_id = $1 AND key = $2',
[accountId, key]);
if (existing.rows.length === 0) {
const order = await createOrder(req.body); // two concurrent requests both get here
await db.query('INSERT INTO idempotency_keys ...');
}
Two identical requests that arrive a few milliseconds apart both see "no row" and both create an order. This is exactly the retry scenario idempotency keys exist for, because clients and proxies often retry quickly. The fix is to let the database decide who wins with a unique constraint and an atomic insert:
CREATE TABLE idempotency_keys (
account_id bigint NOT NULL,
key text NOT NULL,
request_hash text NOT NULL,
status text NOT NULL DEFAULT 'in_progress', -- or 'completed'
response_code int,
response_body jsonb,
created_at timestamptz NOT NULL DEFAULT now(),
locked_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (account_id, key)
);
const claim = await db.query(
`INSERT INTO idempotency_keys (account_id, key, request_hash)
VALUES ($1, $2, $3)
ON CONFLICT (account_id, key) DO NOTHING
RETURNING key`,
[accountId, key, requestHash]);
if (claim.rowCount === 1) {
// We own this key: do the work
} else {
// Someone already claimed it: look at the existing row and decide
}
Exactly one request gets rowCount === 1. Every other copy falls into the second branch, where you read the row and handle the in-progress, completed, and mismatch cases. When you review the model's draft, search for any SELECT that happens before the claim and decides whether to do the work. If you find one, the race is still there.
Bind the key to the request it was first used with
If a client sends key abc123 to create a $20 order and later sends abc123 again with a $500 order, the naive implementation returns the saved $20 response. The client thinks the $500 order went through when nothing happened. Store a hash of the request when you claim the key and compare it on every repeat:
import { createHash } from 'node:crypto';
function canonicalHash(method, path, body) {
// Sort keys so {"a":1,"b":2} and {"b":2,"a":1} hash the same
const stable = JSON.stringify(sortKeysDeep(body ?? {}));
return createHash('sha256').update(`${method}\n${path}\n${stable}`).digest('hex');
}
// In the "already claimed" branch:
const row = existing.rows[0];
if (row.request_hash !== requestHash) {
return res.status(422).json({ error: 'idempotency_key_reused',
message: 'This Idempotency-Key was already used with a different request.' });
}
Check that the model's draft hashes the parsed body with a stable key order, not the raw bytes from one client library and a re-serialized object from another. Either approach can work, but it must be the same on every request. Leave out headers that change between retries, such as tracing IDs or timestamps, or every retry will look like a mismatch.
Replay the saved response, exactly
When the existing row is completed, return what you returned the first time: the same status code and the same body, including the same order ID. Generated code sometimes returns a generic 200 {"ok": true} or re-fetches the current state of the order. Both break clients that parse the response the first time and expect the retry to look identical.
if (row.status === 'completed') {
res.set('Idempotent-Replayed', 'true'); // optional, helps debugging
return res.status(row.response_code).json(row.response_body);
}
if (row.status === 'in_progress') {
res.set('Retry-After', '1');
return res.status(409).json({ error: 'request_in_progress' });
}
The Idempotent-Replayed header is not standard, just a useful convention for your own logs and support work. The 409 and 422 choices match what several public APIs do and what the IETF's draft specification for an Idempotency-Key header suggests. Whatever codes you choose, document them so client developers know which errors are safe to retry.
Ask for a copy of a receipt and you get the same receipt, not a second meal. Replay the saved response the same way. Image: ReceiptSwiss by Audrius Meskauskas (Audriusa), CC BY-SA 3.0, via Wikimedia Commons.
Save the result in the same transaction as the work
If the order is inserted and committed, and then the process crashes before the idempotency row is marked completed, a retry finds an in-progress key forever, or worse, a stale lock that eventually expires and lets the work run twice. When the side effect lives in the same database, wrap it and the response update in one transaction:
await db.query('BEGIN');
try {
const order = await insertOrder(db, accountId, req.body);
const body = { id: order.id, status: order.status, total: order.total };
await db.query(
`UPDATE idempotency_keys
SET status = 'completed', response_code = 201, response_body = $3
WHERE account_id = $1 AND key = $2`,
[accountId, key, body]);
await db.query('COMMIT');
return res.status(201).json(body);
} catch (err) {
await db.query('ROLLBACK');
throw err;
}
Now the order and the saved response either both exist or neither does.
When the side effect is outside your database
Charging a card through a payment provider or sending an email cannot join your database transaction. You have two practical options, and you should tell the model which one you want:
- Pass the idempotency through. Many payment APIs accept their own idempotency key. Derive it from yours (for example
order-create:${accountId}:${key}) so a retry of your endpoint becomes a safe retry of their call too. - Record progress in steps. Store a recovery point on the key row (for example
charged, thenorder_created) and have retries resume from the last completed step instead of starting over.
A model left to itself often calls the payment API with no idempotency key at all. Check for that specifically.
Decide which failures to remember
Not every response should be saved forever:
- Success (2xx): save it and replay it.
- Client errors that will never change (400 validation failure, 422): saving them is reasonable, because the same request will fail the same way.
- Server errors and timeouts (5xx): do not save them. Roll back, delete the key row or reset it, and let the client retry. Otherwise a brief database outage turns into a permanently failed operation.
Also handle the crashed-worker case. If a process dies while holding a key, the row stays in_progress. Use the locked_at column: if a lock is older than your longest reasonable request time (say 60 seconds), a retry may take it over. Only do this when the work is in the same transaction, or when it resumes from recovery points, so a takeover cannot repeat a side effect that already happened.
Clean up old keys
Keys need an expiry, or the table grows forever. 24 hours is a common window and matches how long realistic client retries last. Stripe, for example, documents that its keys can be pruned after they are at least 24 hours old. A scheduled job is enough:
DELETE FROM idempotency_keys
WHERE created_at < now() - interval '24 hours'
AND status = 'completed';
Run it in batches if the table is large, and add an index on created_at. Leave abandoned in-progress rows to the stale-lock rule above, or clean them up on a longer window after checking they are safe to remove.
Tell clients how to generate keys
The server side is only half of it. Your docs and SDK should say:
- Generate a new random key (a UUID v4 is fine) once per user action, such as one tap of "Pay."
- Store it with the pending operation and reuse the same key for every retry of that action.
- Generate a new key for a new action, even if the body looks the same. Two identical $10 orders on purpose are two orders.
- Retry on network errors, 409, and 5xx with backoff. Do not retry 422; fix the bug.
A frequent client-side mistake, and one models reproduce, is generating the key inside the retry loop. That gives every attempt a fresh key and defeats the whole mechanism.
Tests that prove it works
Ask the model for these tests explicitly, then run them yourself:
- First call: returns 201 and creates exactly one order.
- Sequential retry: the same key and body twice. Both return the same status and order ID, and the database still holds one order.
- Concurrent duplicates: fire 10 identical requests at once with
Promise.all. Exactly one order exists afterward. Every response is either the 201 or a 409. This is the test that catches SELECT-then-INSERT. - Key reuse with a different body: returns 422 and creates nothing.
- Different accounts, same key: both succeed independently.
- Failure then retry: make the order insert throw once (inject a fault), then retry with the same key. The retry succeeds and creates one order.
- Missing or malformed key: returns 400.
test('concurrent duplicates create one order', async () => {
const key = crypto.randomUUID();
const send = () => request(app).post('/orders')
.set('Authorization', token).set('Idempotency-Key', key)
.send({ sku: 'A1', qty: 1 });
const results = await Promise.all(Array.from({ length: 10 }, send));
const codes = results.map(r => r.status);
expect(codes.filter(c => c === 201).length).toBeGreaterThanOrEqual(1);
expect(codes.every(c => c === 201 || c === 409)).toBe(true);
expect(await countOrders()).toBe(1);
});
Run the concurrency test against a real PostgreSQL instance, not an in-memory mock. Mocks rarely enforce unique constraints the way the database does, so the race can pass in tests and fail in production.
Review checklist for generated idempotency code
- Is the key claimed with an atomic insert on a unique constraint before any work starts?
- Are keys scoped to the authenticated account?
- Is a request hash stored and compared, with a clear error on mismatch?
- Does an in-progress duplicate get a retryable error instead of running the work again?
- Is the saved response replayed exactly, with the original status code and IDs?
- Is the response saved in the same transaction as the work, or are external calls protected by their own idempotency keys?
- Are 5xx failures left unsaved so clients can retry?
- Is there an expiry job and a rule for stale locks?
- Do the docs tell clients to reuse one key across retries of one action?
- Does a concurrent-duplicate test pass against a real database?
Idempotency keys are a small amount of code with a big payoff: retries stop being dangerous, and "the customer was charged twice" stops being a support ticket. The model can write the boilerplate quickly. Your job is to make sure the key is claimed first, tied to one request, and backed by a test that sends the same request ten times at once.
Comments
Post a Comment