Idempotency
Doing an operation N times has the same effect as doing it once. It's what makes retries and at-least-once delivery safe; get it with upserts, conditional writes or client-supplied idempotency keys.
Analogy: Pressing an elevator call button five times summons one elevator. Pressing a thermostat's '+1°' button five times raises it five degrees: that's the retry you can't afford.
How it works
- Calls fail after the work is done: the charge succeeded, the response was lost, and the client retries.
- PUT and DELETE set state, so repeats are harmless; POST and
count += 1are not. - Upserts on a unique id make duplicates a no-op; conditional writes compare-and-set on a version.
- With idempotency keys, the client resends one key per logical operation; repeats get the stored response.
- Record the key in the same transaction as the effect, or a crash between them reopens the gap.
Check yourself
Answer to mark it learned; your answers aren't scored.
Your refund handler runs SELECT on the idempotency key; if it's not found, it issues the refund, then INSERTs the key. Under load, a few customers still get refunded twice. Both duplicate requests carry the same key and arrive milliseconds apart. Cause?
Go deeper
Full explanation
An operation is idempotent if doing it N times has the same effect as doing it once. It matters because calls fail after the work is done: the charge succeeded, the response was lost, the client retries. Without idempotency, every retry policy (Retries, backoff & circuit breakers) and every at-least-once queue (Queues vs streams (Kafka)) is a duplicate generator.
Ways to get it, cheapest first:
- Natural idempotency:
PUT /orders/7 {status: shipped}andDELETEset state, so repeats are harmless.POST /chargesandcount += 1are not. - Unique constraints and upserts:
INSERT … ON CONFLICT (event_id) DO NOTHING; the second copy is a no-op. - Conditional writes: compare-and-set on a version (
UPDATE … WHERE version = 7, DynamoDB condition expressions). - Idempotency keys (the Stripe pattern): the client generates one unique key per logical operation and resends it on every retry. The server stores
key → (request hash, status, response). The first call executes and records; a repeat gets the stored response, a concurrent repeat gets409, and a reused key with a different body is rejected.
The key must be recorded atomically with the effect (same transaction), or a crash between them reopens the gap. When the effect is an external call, pass the key downstream.
For agents: every side-effecting tool call needs a key, so a retried step never refunds twice.
Code Idempotency-key handler (FastAPI + Postgres)
import hashlib, json
from fastapi import FastAPI, Header, HTTPException
from fastapi.responses import JSONResponse
app = FastAPI()
@app.post("/refunds")
def create_refund(body: dict, idempotency_key: str = Header()):
req_hash = hashlib.sha256(json.dumps(body, sort_keys=True).encode()).hexdigest()
# Claim the key: the primary key makes concurrent duplicates lose the race
claimed = db.execute(
"INSERT INTO idem_keys (key, req_hash, status) VALUES (%s, %s, 'started') "
"ON CONFLICT (key) DO NOTHING RETURNING key", (idempotency_key, req_hash)).fetchone()
if not claimed:
row = db.execute("SELECT req_hash, status, code, response FROM idem_keys "
"WHERE key = %s", (idempotency_key,)).fetchone()
if row.req_hash != req_hash:
raise HTTPException(422, "Idempotency key reused with a different body")
if row.status == "started":
raise HTTPException(409, "Original request still in progress")
return JSONResponse(row.response, status_code=row.code) # replay, no new refund
# Same key downstream: the provider dedupes if we crash and retry
refund = payments.refund(body["charge_id"], body["amount"], idempotency_key=idempotency_key)
db.execute("UPDATE idem_keys SET status = 'done', code = 201, response = %s "
"WHERE key = %s", (json.dumps(refund), idempotency_key))
return JSONResponse(refund, status_code=201)Real example
A support agent calls issue_refund(order_id=812, amount=40). The payment API succeeds but answers in 31 s; the tool client times out at 30 s and the framework retries. Then the LLM, seeing a timeout error, calls the tool again on its next turn. Without idempotency the customer gets $120 back. Two keys close both holes: the framework retry reuses the key run_id:step_id, and the refund service also enforces a business key, one refund per order_id, because the model's second call is a new step with a new step id. Both duplicates return the original result, and the tool tells the model refund already issued.
Trade-offs +3 · −3
+ You gain
- Makes retries, timeouts and at-least-once delivery safe: the base of every reliability pattern.
- Clients can retry blindly on timeouts and 5xx without asking 'did it happen?'.
- Cheap: one table or unique constraint and one lookup per write.
− You pay
- Keys need storage and expiry (Stripe keeps them at least 24 h); a retry after expiry is a new request.
- Hard across systems: the key must commit atomically with the effect or travel downstream.
- Doesn't serialize different concurrent requests; you still need locks or versions for that.
Use it when
Every non-read operation a retry can reach: payments, orders, emails, provisioning, queue consumers, webhook handlers, and every agent tool that changes the world.
Avoid it when
Pure reads, or writes that are already naturally idempotent (full-state PUT, set membership, upsert by natural key): don't bolt a key table onto those.
Numbers to know 4
- Stripe keeps idempotency keys for at least 24 hours; reusing a key with different parameters returns an error.
- HTTP (RFC 9110): GET, HEAD, OPTIONS, TRACE, PUT and DELETE are idempotent; POST is not, and PATCH isn't guaranteed to be.
- SQS FIFO deduplicates by
MessageDeduplicationIdwithin a 5-minute window: dedup windows are always bounded. - A UUIDv4 key has 122 random bits: collisions are not a practical concern.
Common pitfalls 4
- Generating a new key per attempt (or on the server): each retry looks new and nothing is deduplicated.
- Check-then-act without a unique constraint: two concurrent retries both see 'not found' and both execute.
- Recording the key in a separate transaction after the effect: a crash in between re-runs the effect on retry.
- No recovery for keys stuck in
startedafter a crash: give them a lock timeout, then resume or fail them.
Interview questions 2
Answer out loud first, then reveal.
A client times out calling your payments API. Should it retry?Show answer
Only if the endpoint is idempotent; otherwise a timeout is ambiguous, since the charge may have gone through. So I make it safe: the client sends an Idempotency-Key per logical payment, generated once and reused on every retry. The server claims the key with a unique insert, executes, stores the response in the same transaction as the effect, and replays it on duplicates. It returns 409 while the original is in flight and rejects a reused key with a different body. With that in place, clients retry with backoff and jitter.
How do you stop an LLM agent from executing a side-effecting tool twice?Show answer
I separate two sources of duplicates. Infrastructure retries and durable-execution replays reuse the same step, so a key derived from run id plus step id dedupes them. The model re-deciding is different: its second call is a new step, so the tool itself must enforce a business-level key, like one refund per order, or check state first. The tool then returns 'already done' with the original result, so the model doesn't loop. For irreversible actions above a threshold, I add human approval.