Technology

Idempotency keys: how to make API retries safe

A timeout does not tell the client whether a request failed. Idempotency keys let it retry without charging a card twice or creating a duplicate order.

  • By Systronium Team, Engineering & Delivery
  • October 26, 2026
A client retrying a payment request with the same idempotency key and receiving the stored result

A customer taps "Pay". The request reaches your server, the payment goes through, and then the phone's connection drops before the response arrives. From the app's point of view, the request timed out. Did it fail? Did it succeed? The app has no way to know.

If it retries, the customer might be charged twice. If it does not, the customer might assume the payment failed and try again by hand, with the same result. This is one of the most common sources of duplicate orders, double charges and repeated emails, and it is entirely predictable. Networks drop responses. Load balancers time out. Phones go through tunnels.

The fix is to make the operation idempotent: performing it twice has the same effect as performing it once.

Which requests are already safe

HTTP defines GET, HEAD, PUT and DELETE as idempotent. Sending PUT /users/42 with the same body ten times leaves the user in the same state as sending it once. Deleting something that is already deleted changes nothing.

POST is the problem. POST /payments means "create a new payment", so every request creates another one. PATCH is not guaranteed to be idempotent either, and an operation like "add 10 to the balance" clearly is not. Those are the requests that need extra design.

How idempotency keys work

The client generates a unique key for each logical operation and sends it with the request, usually in a header:

POST /payments HTTP/1.1
Content-Type: application/json
Idempotency-Key: 5f2b9c3e-8d41-4a7e-9b0f-2c6d1e8a7f30

{"order_id": "ord_1042", "amount": 4900, "currency": "EUR"}

If the client has to retry, it sends exactly the same key. The server remembers which keys it has already processed and what it answered. A repeated key gets the stored response back instead of running the operation a second time.

There is an IETF draft that standardises the Idempotency-Key header, and large payment APIs have used the pattern for years. You do not need a library for it. It is a table, a unique constraint and some careful ordering.

The server side, step by step

Start with a table that records keys:

CREATE TABLE idempotency_keys (
  account_id    BIGINT       NOT NULL,
  idem_key      VARCHAR(64)  NOT NULL,
  request_hash  CHAR(64)     NOT NULL,
  status        VARCHAR(16)  NOT NULL,
  response_code INT          NULL,
  response_body JSON         NULL,
  created_at    DATETIME     NOT NULL,
  PRIMARY KEY (account_id, idem_key)
);

Scope keys to the caller. Two customers who happen to send the same key must never see each other's responses.

Then, for every request that carries a key:

  1. Try to claim the key by inserting a row with status processing. The primary key makes this atomic: if two copies of the same request arrive at the same moment, only one insert succeeds.
  2. If the key already exists, load the row and decide:
    • Status completed: return the stored status code and body, and do nothing else.
    • Status processing: the first attempt is still running. Return 409 Conflict so the client tries again shortly.
    • A different request_hash: the client reused a key for a different request. Reject it with 422. That is a client bug, and quietly returning the old response would hide it.
  3. If the claim succeeded, do the real work, store the response and mark the key completed.

In TypeScript, the core of it looks like this:

async function withIdempotency(
  accountId: string,
  key: string | undefined,
  body: unknown,
  run: () => Promise<Result>,
): Promise<Result> {
  if (!key) return run();

  const requestHash = sha256(canonicalJson(body));
  const claimed = await keys.tryInsert({ accountId, key, requestHash, status: 'processing' });

  if (!claimed) {
    const existing = await keys.find(accountId, key);
    if (existing.requestHash !== requestHash) {
      return { status: 422, body: { error: 'idempotency_key_reused' } };
    }
    if (existing.status === 'processing') {
      return { status: 409, body: { error: 'request_in_progress' } };
    }
    return { status: existing.responseCode, body: existing.responseBody };
  }

  const result = await run();
  await keys.complete(accountId, key, result.status, result.body);
  return result;
}

The part that is easy to get wrong

The sketch above has a gap. If the process crashes after run() finishes but before complete() saves the response, the key stays in processing forever, and the work has already happened.

There are two ways to close it.

Keep it in one transaction. If the operation only writes to your own database, claim the key, do the business writes and store the response in the same transaction. Either everything commits or nothing does. A concurrent duplicate waits on the row lock and then sees the completed result. This is the simplest and strongest option.

Recover stale claims. If the work calls something outside your database, such as a payment provider, a transaction cannot cover it. Record when each key was claimed and treat a processing row older than a few minutes as abandoned. The retry then has to find out what actually happened, which is far easier if you passed a key on to the provider as well. Most payment providers accept an idempotency key of their own for exactly this reason.

Side effects like emails and webhooks deserve the same care. Instead of sending them inline, write them to an outbox table in the same transaction and let a separate worker deliver them. A retried request then cannot send the confirmation email twice.

What the client has to do

The server side only works if clients play their part:

  • Generate the key once per user action, not once per HTTP attempt. A UUID created when the user taps "Pay" and reused for every retry of that payment is right. A fresh UUID on each retry defeats the whole mechanism.
  • Retry with exponential backoff and jitter. Wait roughly 1, 2, 4 and then 8 seconds, with some randomness added, so a short outage does not turn into a synchronised wave of retries.
  • Only retry what is worth retrying. Timeouts, connection errors, 409, 429 and 5xx responses are candidates. A 400 or 422 will fail the same way every time.

How long to keep keys

Keys only need to live as long as a client might reasonably retry. Twenty four hours is a common choice, and it covers app restarts and overnight retry queues. Remove older rows with a scheduled job so the table does not grow forever.

When you do not need a key

Some operations can be made naturally idempotent, which is even better. If an order can only be paid once, a unique constraint on payments.order_id stops a second payment row from ever being created, and checking it before calling the provider stops the second charge too. An upsert keyed on a client-supplied ID turns "create" into "create, or return the one that already exists".

Use idempotency keys where there is no natural unique field to lean on, and use them on every endpoint where a duplicate would cost money, stock or trust. Retries will happen whether you design for them or not.

How we use idempotency keys in our own products

In Smart POS, checkout carries a client-generated idempotency key backed by a unique index, so a retried request replays the original order instead of selling the same stock twice. In the OCPP Management Platform, each session cost is written to a ledger row keyed uniquely by company and transaction, so a retried StopTransaction from a charger cannot bill a driver twice.

Retries are normal on real networks, and designing for them is part of every systems integration project we deliver.

Let's build something reliable

Practical software. Reliable systems. Built to scale.

Tell us what you are building and where delivery is slowing down. We will map the shortest practical path to a working product.

A remote-first software studio building web platforms, desktop software, and scalable systems that keep working after launch.

  • Web platforms
  • Desktop software
  • Cloud & DevOps
info@systronium.com