7 min readRishi

Idempotency Keys for Write APIs

Idempotency Keys for Write APIs

A client times out. It retries the POST. The first request actually committed. The second creates another charge, another order, another email. The fix is an idempotency key: the client sends a unique key with the write, and the server promises that a second request with the same key returns the original result and does not do the work again.

The key is chosen by the client, not the server. A server-generated id arrives too late — the client that timed out does not have it. A UUID per user action, stored by the client until it gets a definite response, is enough. Reuse that same key for every retry of that action. A new key means a new action.

POST /orders HTTP/1.1
Idempotency-Key: 7c9e6679-7425-40de-944b-e07fc1f90ae7
Content-Type: application/json

{"cartId":"c_19","shippingAddressId":"a_4"}

Generate the key when the user confirms, not when the app boots. A key created at page load will collapse two intentional orders into one.

Insert the key before the side effect

On the first request, persist the key and the outcome in the same transaction as the business write, or in an order that cannot leave a committed write without the key.

Stored with the keyWhy
Request hashA reused key with a different body is a client bug. Reject it. Do not silently run a different operation
Response status and bodyThe retry must see the same answer, including a 400 that was the real result
State: in-progress or finalTwo retries in flight need a single winner

The race is two requests with the same key passing the "have I seen this" check together. A unique constraint on the key is the lock. The loser waits, or gets a 409 while the winner is in progress, and retries after a short delay. When the winner commits, the loser reads the stored response and returns it.

Do not run the business logic twice and then notice the key. The unique insert comes first.

CREATE TABLE idempotency_keys (
  key            TEXT PRIMARY KEY,
  request_hash   TEXT NOT NULL,
  status         TEXT NOT NULL, -- in_progress | completed | failed
  response_code  INT NULL,
  response_body  JSONB NULL,
  created_at     TIMESTAMPTZ NOT NULL DEFAULT now()
);
async function postOrder(key: string, body: OrderRequest) {
  const hash = sha256(canonicalJson(body));
  const inserted = await db.tryInsertKey(key, hash);
  if (!inserted) {
    const existing = await db.getKey(key);
    if (existing.request_hash !== hash) {
      throw http(422, "idempotency key reused with a different body");
    }
    if (existing.status === "in_progress") {
      throw http(409, "request with this key is still running");
    }
    return http(existing.response_code, existing.response_body);
  }

  try {
    const order = await createOrder(body); // the side effect
    await db.completeKey(key, 201, order);
    return http(201, order);
  } catch (err) {
    await db.failOrDeleteKey(key, err);
    throw err;
  }
}

tryInsertKey is INSERT ... ON CONFLICT DO NOTHING returning whether the row is new. The 409 on in_progress is deliberate: the loser retries shortly and reads the stored body instead of tying up a worker.

The 500 you did not persist is a duplicate

A 500 that you did not persist is not idempotent. If you return 500 before storing the key, the client will retry and you will do the work twice. Persist the key in the in-progress state before the side effect that can fail halfway — the charge, the email, the message publish. If that side effect fails, store the failure on the key or delete the in-progress row inside the same recovery path. "Maybe" is how duplicates happen.

If the charge succeeded and the completeKey write failed, the next retry must not charge again. That is why the payment call itself should also take the same key, or a key derived from it, on the processor's API. Your table is the application-level lock. The processor is the money-level lock. You want both. The ledger shape for that money movement is in double-entry payments. Checkout is the usual caller; the cart side of the same POST is in price snapshots and cart merge.

Hash the canonical body, not the raw bytes. {"a":1,"b":2} and {"b":2,"a":1} are the same order. If your hash is sensitive to key order, a client that re-serializes on retry will get a 422 for a request you already ran. Canonicalize, then hash.

Expiry that forgets too soon

Keys cannot live forever or the table becomes every write you have ever accepted. They also cannot expire while a client might still retry. A client timeout plus a few retries is minutes. A mobile client that backgrounds and resumes might be hours. Twenty-four hours is a common window for payment-style APIs. Document it. After expiry, the same key is a new request, and a late retry can double-apply. Clients must stop retrying before that, or send a new key only when the user explicitly tries again.

Sweep completed rows past the window. Do not sweep in_progress rows that are thirty seconds old; a slow processor looks like a leak. Give in-progress a longer TTL. A stuck in_progress row is a 409 forever.

What not to use as the key

The user id is not an idempotency key. The user will place two orders. A hash of the entire cart is fragile: two intentional identical carts become one, and a cart that changed by a cent becomes two. The key is "this click," generated when the user confirmed, held across retries, discarded when the UI starts a new confirmation.

Do not derive the key from the current timestamp. Two retries in the same millisecond are still two retries; two clicks a millisecond apart are two clicks. The clock cannot tell them apart.

Do not accept a missing key and generate one on the server. The client that timed out still does not have it, so the retry is a new key and a second write. If the client cannot send a header, require a clientRequestId in the JSON body. Same contract, different field.

When you do not need a key

GET and PUT of a full resource are already safe to repeat if PUT replaces state. POST and PATCH that append or increment are the ones that need the key. A POST that creates a resource whose natural key the client already knows — PUT /orders/{id} with a client-chosen id — can be made idempotent by uniqueness on that id. That is the same idea with a different name. Use it when the client can name the resource. Use an idempotency key when it cannot.

Skip the machinery for a write whose duplicate is cheap and visible: attaching a tag, setting a flag the user can toggle. Spend it on money, inventory, email that goes to a customer, and anything a support queue cannot unwind.

A test that actually fails when the code is wrong

Send two parallel POSTs with the same key and the same body. One side effect, two identical responses, is the passing test. Then send the same key with a different body and expect 422. Then kill the handler after the side effect and before completeKey, retry, and expect the original result rather than a second charge. Then wait past expiry and confirm a late retry is either rejected or documented as a new request.

If you only test "call it twice in sequence in one thread," you have not tested the race the unique constraint is there for. The bug is two in-flight requests. Write that test first.

Keep reading

7 min read

FOR UPDATE: No Row, No Lock

SELECT … FOR UPDATE locks tuples that exist. An empty scan is not a lock on the key. Two sessions both insert; a unique violation is the lucky case.

8 min read

SKIP LOCKED: Due Jobs, Empty Batch

SKIP LOCKED does not mean the next free job. It skips rows that currently have a conflicting lock. A forgotten transaction can make a full queue claim nothing until that session ends.

Newsletter

New posts, straight to your inbox

One email when a new post goes up. Double opt-in, unsubscribe anytime. Not a daily digest.

Comments

  • No comments yet. Be the first.