- Subject
- Software
- Date
- Read
- 11 min
Idempotency: your request will arrive twice
Why duplicate requests are normal in distributed systems, what breaks when you don't plan for them, and the three patterns that stop it.
Contents
Idempotency is the property that makes an operation safe to repeat: doing it once has the same effect as doing it ten times.
The definition is one line. The interesting part is that in a distributed system, the same request will arrive more than once. That isn’t a rare edge case. It’s the normal behavior of networks, retries, and queues, and if your system’s answer to “the same request twice” is “write it twice,” every one of those normal events becomes a bug.
I’ll use one example throughout: a small online store. A customer clicks Place order. The app calls an API, which saves the order, charges the card, and puts an “order placed” message on a queue so another service can ship it and send the confirmation email. Every one of those steps can happen twice.
Where duplicates come from
- A retry after a timeout. The client sends a request, the response is lost or slow, and the client assumes it failed and sends it again. The first one may have succeeded.
- A double-submit. Someone taps the button twice before it disables, or a slow network makes them think the first tap didn’t register.
- At-least-once delivery. SQS standard queues guarantee a message is delivered at least once, not exactly once. If a consumer doesn’t acknowledge it in time, it comes back, even if it was already fully processed. AWS’s Lambda docs say it plainly: duplicate processing can occur, so make your function idempotent.
- Automatic retries. When an asynchronously invoked Lambda fails, Lambda runs it two more times by default. If it failed after doing its write, the write happens again.
- Re-syncing a source. A job that pulls from another system, such as a bank, a ticket tracker, or an API, will see records it already imported. Usually on purpose, since re-pulling an overlapping window is how you catch late updates.
Which operations need it
Not everything:
- Reads have no side effect. Reading twice is fine.
- Naturally idempotent writes, like
SET status = 'active', end in the same state whether they run once or ten times.
But any write that can be triggered more than once for the same intent, such as an
INSERT, “increment this counter,” “create this record,” or “send this email,” is not
idempotent by default. In a distributed system that’s most write paths. The safe default
is to assume a write needs protection unless it’s a read or provably idempotent already.
What goes wrong without it
The easiest case to see is duplicate rows. The checkout API gives every request a new
orderId = crypto.randomUUID(). The customer’s connection hiccups, the app retries a few
times, and the orders table now has four orders for one checkout. That’s worse than
clutter:
- Every total is wrong. Counts and sums over that table are inflated, and nothing tells you so.
- Cleanup is guesswork. To dedupe after the fact, you have to decide which fields define “the same thing,” which is exactly the decision that should have been made before the write.
- It compounds. A flaky connection that causes one retry can cause many, and an aggressive retry loop turns one submission into dozens.
The same root cause, treating a retry as a brand-new request, shows up in worse places:
- Duplicate notifications. A send job times out without knowing the first email went out, and the user gets it three times. Users see this one directly, and it reads as a broken product.
- Double charges. A checkout times out, the client retries, and the first charge had already gone through. This is the textbook reason payment APIs require an idempotency key.
- Double fulfillment. A redelivered “order placed” event ships the order twice. A duplicate row can be deleted; a package can’t be un-shipped.
- Inflated counters. A billing pipeline adds one per event received. A redelivered event adds one again, and a customer gets billed for usage that never happened.
None of these look like a bug in the code that runs. It does the right thing every time it runs. The bug is the missing check for “have I already handled this exact request?”
Pattern 1: a client-supplied idempotency key
The client generates a unique token for each logical operation, usually a UUID, and sends it with the request. The server checks whether it’s seen that token; if it has, it returns the original result instead of doing the work again.
POST /orders
Idempotency-Key: 3f29c1a0-8e7b-4b1a-9c3e-1a2b3c4d5e6f
{ "item": "...", "quantity": 1 }
Stripe uses exactly this, and prunes keys once they’re at least 24 hours old.
Where the key lives: if the request creates one record, the key can just be a
unique column on that table. A separate idempotency_keys table, mapping key to status
and result with an expiry, is only worth it when the operation has no single row that
represents “this happened,” like “charge the card and email a receipt.” Then the work and
the bookkeeping are two writes, which is its own race condition unless they happen in one
transaction.
The catch: the client has to reuse the same key on every retry of the same operation. A client that generates a fresh key per attempt gets zero protection.
Pattern 2: a deterministic key
Instead of a separate token, compute the record’s ID from the fields that define its identity. A retry of the same request always produces the same ID, so identity and idempotency become one thing. There’s nothing for the client to generate or remember.
For the store, the app already has a stable identity for a checkout: the cart. The cart gets an ID when it’s created, every retry of Place order sends the same one, and once it’s been ordered the cart is closed, so the next purchase gets a new cart and a new order.
The tradeoff is choosing the fields. Too few and two genuinely different records collide: key an order on customer and items alone, and someone who buys the same thing again next week gets told it’s a duplicate. Too many, especially free text, and trivial differences like whitespace or capitalization make the same record look new.
Only hash fields that are stable across retries
This is the mistake that’s easy to make, because the field looks reasonable:
// Wrong: Date.now() reads the clock on every attempt, so a
// retry of the same request produces a different key.
// It's the randomUUID bug in disguise.
const orderId = sha256(`${customerId}|${cartId}|${Date.now()}`);
// Right: cartId comes from the request. It's the same on
// every retry of the same checkout.
const orderId = sha256(`${customerId}|${cartId}`);
The test for any field: if the client retries this exact request 30 seconds from now,
does this value change? Fields from the request, like a cart ID, a date the user picked,
or a source system’s ID, pass. Date.now(), crypto.randomUUID(), or a server-assigned
createdAt fail.
Which hash?
Any deterministic hash works; the only requirement is same input, same output. SHA-256 is a fine default because it’s built into every standard library, not because this needs cryptographic strength. A collision between two different records isn’t a realistic concern.
One caution: hashing doesn’t hide a value. If an identity field is something guessable, like an email address, anyone can hash candidates and compare. Stripe’s docs specifically say not to put emails or personal identifiers in idempotency keys. Keep sensitive values out of keys that end up in logs or URLs.
When two records really are identical
Deterministic keys have one hard case: two records that are genuinely the same. I hit it
in my personal finance tool, a small app that pulls in my bank transactions. It keys each
transaction on a hash of the account, date, amount, and description, so re-syncing a bank
never duplicates anything. But two $10 charges at the same place on the same day hash
identically and would merge into one. The fix is to add which copy it is to the key:
hash:0, hash:1. Identical transactions are interchangeable, so it doesn’t matter which
gets which number, and every re-sync produces the same two IDs.
Pattern 3: enforce it with a conditional write
Whichever key you use, the check has to be atomic. “Look it up, and insert if it’s not there” is a race: two concurrent requests can both see nothing, and both insert.
The fix is to make the check and the write a single operation, so the database, the only thing that sees every concurrent write, decides.
DynamoDB, with a condition expression:
await client.send(new PutCommand({
TableName: "orders",
Item: order,
ConditionExpression: "attribute_not_exists(PK)",
}));
// A duplicate throws ConditionalCheckFailedException. Catch it and
// return the original result: to the caller, a duplicate is a success.
SQL, with
ON CONFLICT:
INSERT INTO orders (order_id, ...)
VALUES ($1, ...)
ON CONFLICT (order_id) DO NOTHING; -- or DO UPDATE to upsert
This doesn’t work against a GSI
This trips people up. A condition expression only checks the item at the key you’re writing to in the base table. A global secondary index is a read-only copy, and you can’t write to it or put a condition on it.
So if your rule is “one open order per customer,” and customerId is only a GSI key, a
conditional put on orderId can’t see it. Two ways to enforce it:
- Make the uniqueness the key. Put
customerIdin the base table’s key. - Write a guard item. In one
TransactWriteItemscall, write the order and an item keyed onOPEN_ORDER#<customerId>withattribute_not_exists. If the guard already exists, the whole transaction fails, and neither write happens.
Transactions can be made idempotent too: pass a ClientRequestToken, and repeating the
same call within 10 minutes returns success without applying it again.
Queues make it mandatory
A queue doesn’t solve idempotency. It makes it required. With at-least-once delivery, a consumer has to treat every message as a possible redelivery, because that’s how the guarantee works when nothing has gone wrong.
SQS FIFO queues help on the sending side: within a 5-minute deduplication window, retrying a send doesn’t add a second copy. That protects the queue, not your side effects. If your consumer writes to the database and then crashes before acknowledging, the message comes back and the write runs again. The consumer still needs one of the patterns above.
Idempotency isn’t ordering
Standard SQS queues also don’t guarantee order, so an old message can show up after a newer one. Deduping doesn’t help: a stale “order confirmed” arriving after “order canceled” isn’t a duplicate of anything. It has its own ID and looks like a legitimate new write. That’s an ordering problem, and it needs its own fix: a version or sequence number on the record, and a write that only applies if the incoming version is newer.
Choosing a pattern
| Client-supplied key | Deterministic key | |
|---|---|---|
| Extra table | Only when there’s no single row to attach the key to | No, it’s the primary key |
| Client’s job | Generate the key and reuse it on every retry | Nothing; the server derives it |
| Risk of false collision | Low; the key is random | Depends on which fields you hash |
| Fits | Payments, anywhere the client controls retries | Records with a natural identity: source system + source ID, user + action + date |
Rule of thumb: if a record has a natural identity you can derive from a few stable fields, use a deterministic key; it removes a whole class of client bugs. If the operation doesn’t have one, like “run this batch job,” use a client-supplied key. Either way, enforce it with a conditional write.
On Lambda, you don’t have to build the bookkeeping yourself. Powertools for AWS Lambda has an idempotency utility that stores keys and results in DynamoDB for you.
The takeaway
- Duplicate requests are normal. Retries, double-taps, and at-least-once queues guarantee it. Design for it before the incident, not after.
- Assume writes need protection. Reads and
SET-style writes are the exceptions. Inserts, counters, and notifications aren’t idempotent unless you make them so. - Pick a key strategy: a client-supplied key, or a deterministic key built only from fields that don’t change on retry.
- Enforce it atomically with
attribute_not_existsorON CONFLICT, never check-then-write. - Deduping isn’t ordering. Those are separate problems with separate fixes.
Test yourself
1. A consumer adds 1 to a "signups this week" counter for every "user signed up" event. The queue redelivers one event. What happens, and whose bug is it?
The counter is off by one. “Add 1” isn’t idempotent; running it twice isn’t the same as running it once. The redelivery isn’t the bug, since that’s normal at-least-once behavior. The bug is that the handler can’t recognize an event it already counted. Record each processed event ID with a conditional write, and only increment when that write succeeds, in the same transaction.
2. You're building a deterministic key for a "meeting booked" record. Candidates: organizerId, roomId, startTime (from the request), and createdAt (set by the server at write time). Which belong?
organizerId, roomId, and startTime belong. They come from the request, so every retry
carries the same values. createdAt doesn’t: the server sets it fresh on every attempt, so
each retry would produce a new key, which is exactly the bug the key was supposed to
prevent.
3. A DynamoDB table is keyed on orderId, with a GSI on customerId. Can a condition expression enforce "one open order per customer"?
Not directly. A condition only checks the item at the base-table key you’re writing to,
and a GSI can’t be written to or conditioned on. Either make customerId part of the base
table’s key, or write a guard item keyed on the customer in the same TransactWriteItems
call, conditioned on attribute_not_exists.
4. A stale "order confirmed" message arrives after "order canceled" was already processed. Your consumer dedupes correctly. Is the order safe?
No. The stale message isn’t a duplicate. It has its own ID, so deduping lets it through and the order comes back as confirmed. That’s ordering, not idempotency. Store a version on the order and only apply writes with a newer version.
Further reading
- Stripe: Idempotent requests, the client-supplied key pattern in production
- Amazon SQS standard queues, on at-least-once delivery
- DynamoDB condition expressions
- Powertools for AWS Lambda: Idempotency
- SQL vs NoSQL on AWS, for how keys and indexes work in DynamoDB