Idempotency

Idempotency keys, storing the first response, the race between two identical requests, and the retry that must not charge twice.

10 min read🔗 REST API Engineering

A client sends a POST /charges, the connection times out at four seconds, and the client retries. The first request arrived. The customer is charged twice.

This is not a rare failure. It is the normal behaviour of an unreliable network meeting a method that HTTP says is not idempotent, and the fix is a protocol you have to build.

The failure, in two requests

plaintext
$ curl -X POST /charges -d '{"amount":2000}'
{"chargeId":"ch_1","amount":2000,"totalChargesSoFar":1}
 
$ curl -X POST /charges -d '{"amount":2000}'
{"chargeId":"ch_2","amount":2000,"totalChargesSoFar":2}

Two charges, two thousand each. The server has no way to tell that the second request was a retry of the first rather than a customer deliberately paying twice — because nothing in it says so. Same method, same path, same body: those are equally consistent with both stories.

The client is the only party that knows. It knows it sent one logical request and is now sending it again. So the client must say it, and the mechanism is a header.

The Idempotency-Key header

The client generates a unique key per logical operation — not per HTTP attempt — and sends it with every retry of that operation:

plaintext
POST /charges
Idempotency-Key: 4f1c-9ab2
Content-Type: application/json
 
{"amount": 2000}

The server keeps a record of keys it has completed, along with the response it sent:

plaintext
$ curl -i -X POST /idempotent-charges -H 'Idempotency-Key: 4f1c-9ab2' -d '{"amount":2000}'
HTTP/1.1 201
{"chargeId":"ch_3","amount":2000,"totalChargesSoFar":3}
 
$ curl -i -X POST /idempotent-charges -H 'Idempotency-Key: 4f1c-9ab2' -d '{"amount":2000}'
HTTP/1.1 200
Idempotent-Replay: true
{"chargeId":"ch_3","amount":2000,"totalChargesSoFar":3}

One charge. The second request got the first request's response, byte for byte, and totalChargesSoFar did not move.

Three details in that exchange are deliberate:

  • The replay returns the stored response, not a fresh computation. The client gets the same chargeId and can proceed exactly as if its first attempt had succeeded — which, from the server's point of view, it did.
  • The status differs — 201 then 200 — because the resource was created once. Some APIs return 201 both times to keep the client simple. Either is defensible; say which in your documentation.
  • Idempotent-Replay: true is not required by anything. It is a courtesy that makes debugging and support far easier, and it costs one header.

Storing the response is the hard half

The key alone is not enough. A record has to hold what happened, because the point is to replay it:

ColumnWhy
keythe client's key, unique
endpoint + methodso one key cannot be reused across operations
request_fingerprinta hash of the body
statusIN_PROGRESS / COMPLETED
response_status, response_bodywhat to replay
created_atfor expiry

The request fingerprint is what stops a real bug. If a client reuses a key with a different body, that is not a retry — it is a mistake, and replaying the old response would hide it. The correct answer is 422 (or 409) saying the key was used with different parameters. Silently returning the old response there is worse than not having idempotency at all, because it looks like success.

The race nobody tests

Two identical requests arriving at the same moment, on two instances, is the case that makes naive implementations wrong:

plaintext
instance A: look up key 4f1c  -> not found
instance B: look up key 4f1c  -> not found      <- both saw nothing
instance A: charge, insert record
instance B: charge, insert record               <- two charges again

Checking then acting is a race, and load is exactly when retries are most common. Two fixes, and the first is the one to reach for:

Let the database decide. A unique index on key, and insert the record before doing the work, in state IN_PROGRESS. The second instance's insert fails on the constraint, and that failure is the signal — it means somebody else owns this key. This is the same principle as the validation lesson's note about uniqueness: the index is the only thing that actually decides.

Then handle the in-flight case. If the record exists and is still IN_PROGRESS, the first request has not finished. Return 409 Conflict — "this operation is already running, retry shortly" — rather than waiting, which turns one slow request into two.

Expiry, and what the key is for

Records cannot live forever. Twenty-four hours is the common window and the reasoning is simple: it must be longer than any client will plausibly retry, and short enough that the table stays small. Stripe uses 24 hours; matching a convention clients already know is worth something.

After expiry, the same key is a new operation. That is correct — nobody retries yesterday's request — but it means the key must be genuinely unique per operation, which is why the client generates it fresh for each new intent, typically a UUID. A key derived from the request body is a trap: two customers deliberately buying the same item for the same amount would collide.

Which endpoints need this

Not all of them, and knowing which is most of the design:

  • GET, HEAD, PUT, DELETE are already idempotent by HTTP's definition. PUT /orders/42 with the same body twice leaves the same state.
  • POST that creates something — an order, a charge, a message — needs a key.
  • POST that is really a search does not.

And there is a design answer that removes the problem instead of solving it: let the client choose the id. PUT /orders/{clientGeneratedId} is idempotent for free, with no key table and no expiry policy. It does not suit every domain — you are trusting the client with your identifier space — but where it fits it is less machinery than everything above.

Under the hood: why a unique index arbitrates a race that a transaction alone cannot

The "let the database decide" fix earlier in this lesson deserves the mechanism behind it, because the natural first instinct — "wrap the check and the insert in a transaction" — does not actually fix the race, and it is worth being precise about why.

Two concurrent transactions, both at the default READ COMMITTED isolation level, can each run SELECT ... WHERE key = ?, both see no row (because neither has committed yet — that is what "concurrent" means here), and both proceed to INSERT. A transaction boundary only guarantees that this transaction's own reads and writes are consistent with each other; it says nothing about what another, simultaneously-running transaction is doing. That is exactly the check-then-act race this lesson already names, and putting it inside BEGIN/COMMIT does not close the window between the SELECT and the INSERT — it just makes the window feel safer than it is.

A unique index closes it for a completely different reason: enforcing uniqueness is not application logic running against a snapshot, it is a property the storage engine checks as part of the write itself, at the point the new index entry would be inserted into the B-tree. Concretely, when two transactions both attempt to insert a row with the same key, the second one to actually reach the index-insert step finds the entry already there (or, in engines like PostgreSQL, blocks briefly on the first transaction's insert and then re-checks once it commits) and fails with a uniqueness violation — PostgreSQL raises SQLSTATE 23505, which the application catches as DataIntegrityViolationException. There is no gap for two transactions to both "win", because the check happens at the one place — the physical insert — where the two transactions are forced to serialize against each other, not at a SELECT that ran before either committed. This is the same principle the validation lesson already named for uniqueness of an email address: the index is the only thing that actually decides, and it decides here for the identical reason.

INSERT ... ON CONFLICT DO NOTHING (PostgreSQL's upsert syntax) expresses the same guarantee without the try/catch: the conflict check and the insert are one atomic statement, and the application reads whether zero or one row was affected to know which of the two transactions won.

Try it yourself

Trace an atomic insert-as-lock against the race it prevents

ConcurrentHashMap.putIfAbsent is a close, runnable analogue of what a unique index does: it atomically checks-and-inserts in one operation, returning the value that was already there (or null if this call was the one that inserted).

java
Map<String, String> store = new java.util.concurrent.ConcurrentHashMap<>();
String key = "4f1c-9ab2";
 
String prev1 = store.putIfAbsent(key, "IN_PROGRESS");
System.out.println("attempt1 winner=" + (prev1 == null));
 
String prev2 = store.putIfAbsent(key, "IN_PROGRESS");
System.out.println("attempt2 winner=" + (prev2 == null) + " sawStatus=" + prev2);
 
store.put(key, "COMPLETED:ch_3");
System.out.println("final=" + store.get(key));

Before running it: two "requests" call putIfAbsent with the same key. Which one actually stores its value, and what does the loser learn from the call's return value?

Misconceptions

  • "Wrapping the check-then-insert in a database transaction fixes the race." It does not, at the default isolation level most services run at — a transaction guarantees consistency within itself, not against another transaction running at the same moment. The unique index fixes the race because the uniqueness check happens at the physical write, which is the one point the two transactions are actually forced to serialize against each other.
  • "Idempotency-Key and an ETag/If-Match pair solve the same problem." They protect against different failures. An idempotency key protects a creation from being repeated by a retry the client itself sent. ETag/If-Match (optimistic concurrency) protects an update from clobbering a concurrent edit by a different actor. A service can need both, for different endpoints, and reaching for one where the other is needed leaves the actual failure it doesn't cover unguarded.

Sources

  • Stripe API documentation, "Idempotent Requests" — the Idempotency-Key pattern this lesson follows.
  • PostgreSQL documentation — unique constraints, INSERT ... ON CONFLICT, and error code 23505.
  • RFC 7231, HTTP/1.1: Semantics and Content, §4.2.2 — the idempotent-methods definition this whole mechanism exists to extend to POST.
Progress is saved on this device and to your account when signed in.