Idempotency Keys
Safe retries for paid LLM calls and side-effecting agent actions.
In plain words
An idempotency key is a unique label on a request so that if you accidentally send it twice, the server recognises the repeat and doesn't do the job a second time.
Think of it like…
A numbered cheque or a receipt stub. If you present the same cheque number twice, the bank pays once and shows you the earlier payment, and a cheque number reused for a different amount is flagged as an error.
Where you’ve seen it
A client posts POST /v1/messages with Idempotency-Key: 6f1c... (a random UUID v4, 122 bits of randomness) and a JSON body. The server starts a transaction and inserts a row idempotency(tenant_id, key, request_hash, status, response_code, response_body, created_at) with a unique constraint on (tenant_id, key). If the insert succeeds, it marks the row in_progress, runs the model call, then stores the status, response body and completed in the same commit as the business write; the response is returned. If the insert conflicts, the server loads the row: when completed and the SHA-256 of the new body matches request_hash, it replays the stored response with the same status (and a header Idempotent-Replay: true); when the hash differs it returns 422 (key reused with different parameters); when in_progress it returns 409 with Retry-After: 2 (or waits briefly). The numbers justify the work: with 100,000 requests a day and a 0.5% client-timeout rate, 500 retries happen daily; each duplicate model call costs $0.01195, so $5.98 a day is wasted, plus 500 duplicate side effects such as emails or tickets, which cost far more in trust. Storage is modest: 100,000 records a day × about 3 KB (stored response plus metadata) = 300 MB, kept for a 24-hour retention window and then deleted. A crashed handler leaves a row in_progress, so rows older than the lock timeout (say 5 minutes) can be reclaimed. Downstream calls reuse the key: the payment provider and the email service receive Idempotency-Key: {client key}:{step}, so a replay after a partial failure doesn't double-charge. Because completions vary run to run, the replay returns the *stored* answer rather than regenerating it, and the client SDK generates a key per logical operation, reuses it across retries and never across different operations.
Words you’ll hear
- Idempotent operation
- One whose repeated execution has the same effect as a single execution.
- Request fingerprint
- A hash of the request body stored with the key to detect misuse.
- Replay
- Returning the stored response for a repeated key without redoing the work.
- Retention window
- How long idempotency records are kept, such as 24 hours.
Visual diagram
Theory & deep dive
The protocol and server-side algorithm
The client generates a unique key (a random UUID v4 or a hash of the operation's identity) for each logical operation and sends it with every attempt of that operation. The server scopes keys by tenant (and often endpoint) to prevent cross-customer collisions and stores key, a fingerprint (SHA-256 of the normalised body and relevant parameters), status (in_progress, completed), the response code and body and timestamps. The core step is an atomic insert with a unique constraint (INSERT ... ON CONFLICT DO NOTHING): exactly one concurrent request wins and executes; the others read the existing row. Outcomes: new key runs and stores the response; same key, same fingerprint, completed replays the stored response unchanged; same key, different fingerprint is a client bug and returns 422 (or 409); same key, in progress returns 409 with Retry-After or waits for completion for a short time.
Atomicity is the subtle part. The business effect and the idempotency record should commit together (the same transaction), or you get the duplicate-versus-lost-update problem: if the effect commits but the record doesn't, a retry repeats it; if the record commits first and the effect fails, the retry sees completed with no effect. For effects that live outside your database (a provider call, an email) use the outbox pattern, or pass a derived idempotency key downstream ({key}:charge, {key}:email) so that the external service dedupes as well. Reclaim rows stuck in in_progress after a lock timeout so a crashed worker doesn't block the key forever.
1st request: key K, hash H1 → executes, stores 200 + body. Retry with K, H1 → replays 200 + body, Idempotent-Replay: true. Request with K but body hash H2 → 422 idempotency_key_reused. Retry while the first is still running → 409, Retry-After: 2.
Why it matters for LLMs and agents, and operational details
LLM calls are slow, costly and non-deterministic, which sharpens the need. A retry of a timed-out generation produces a different completion, so without a stored response the user may see two conflicting answers; with a replay they see the one that was produced. The cost is direct: 100,000 requests a day with a 0.5% timeout rate causes 500 retries, and 500 × $0.01195 = $5.98 a day of duplicate generation, plus 500 duplicate side effects (emails, tickets, charges) whose cost is much higher. Agents make this worse by retrying tool calls themselves, so every side-effecting tool should accept an idempotency key derived from the run ID and step number, and tool servers should honour it.
Operational details: keep records for a retention window (24 hours is common) and then delete them (100,000 records a day × 3 KB ≈ 300 MB kept); index the table on the unique key; cap stored body size (store a reference for large responses); and record replays in metrics (a rising replay rate signals client timeouts that are too short). Provide an SDK that generates a key per logical operation, reuses it across automatic retries (with exponential backoff and jitter) and never reuses it for a different operation. Document the semantics (which endpoints support it, retention, error codes) and apply it to POST and PATCH operations that are not naturally idempotent; PUT and DELETE already are. Pair it with timeouts that are longer than typical generation time and with streaming or job patterns so clients aren't forced into retries by long waits.
100,000 requests/day × 0.5% timeouts = 500 retries/day × $0.01195 = $5.98/day in duplicate model calls (≈ $180/month) plus 500 duplicate side effects. Storage: 100,000 × 3 KB = 300 MB per 24-hour window, deleted on expiry.
How it works, step by step
Step 1 of 41. Choose the operations and key format
Require or support an Idempotency-Key on POSTs that create, charge or send, with UUID v4 keys scoped per tenant.
- Document
- retention window
When to use it & trade-offs
What it is
An idempotency key is a unique value a client sends with a request (conventionally in an Idempotency-Key header) so that the server can recognise a repeat of the same logical operation and return the original result instead of doing the work again. The server records the key with a fingerprint of the request and, once finished, the response; a second request with the same key and body is answered from the stored record, a request with the same key but a different body is rejected (409 or 422) and a duplicate that arrives while the first is still running waits or gets 409. Keys make retries of non-idempotent operations (POST that creates, charges or sends) safe, which is essential when each call costs money or triggers a side effect.
Why it matters: Networks fail in the middle: the server finishes a 34-second generation, the client's 30-second timeout fires and the client retries. Without protection you pay for two model calls, send two emails and create two orders. Agents amplify the issue because they retry tool calls automatically and LLM outputs are not deterministic, so regenerating gives a different answer from the one the first attempt already delivered. Idempotency keys convert at-least-once client behaviour into effectively-once server effects.
When to reach for it
- Paid LLM calls and message-creating POSTs
- Agent tool calls with side effects such as email or payments
- Webhook consumers that may receive duplicates
When to avoid or be careful
- Regenerating a completion on retry instead of replaying it
- Reusing a key for a different operation
- Recording the key in a separate transaction from the effect
Ways to make retries safe
Strengths: Works for any operation; replays the original result.
Watch out: Needs storage, retention and client cooperation.
Strengths: No extra table.
Watch out: Not possible for every action.
Strengths: No client changes.
Watch out: Can't tell a retry from an intentional repeat.
Interview signals & numbers to know
When this topic comes up
- “A client timed out and retried. How do you avoid a double charge?”
- Why LLM calls make idempotency harder
- Key scope, fingerprint and retention
- Idempotency versus deduplication
- Downstream key propagation
Benchmarks & rules of thumb
- 500 retries/day
- 0.5% timeouts on 100,000 requests
- $5.98/day
- duplicate model cost from those retries at $0.01195 each
- ≈ 300 MB
- 24 hours of stored responses at 3 KB each
Common mistakes & follow-ups
Common interview mistakes
- Letting clients reuse one key for many operations.
- Not hashing the body, so a reused key with new data silently returns old results.
- Forgetting that in-progress duplicates need a defined response.
Likely interviewer follow-ups
- How would you implement this in PostgreSQL?
- What should happen if the first request crashes mid-way?
- How do agents choose keys for tool calls?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Idempotency Keys with generative AI interview Q&A and hands-on practice.