A client sends "create order", the network drops the response, and the client does not know whether the order was created. If it retries, it might create a second order. If it does not, the customer might have no order at all. Idempotency keys solve this: the client attaches a unique key to the request, and the server guarantees that the same key produces the same result, however many times it arrives.

Which operations need them

GET, PUT and DELETE are idempotent by design when implemented correctly. POST usually is not: "create", "charge", "send" and "enqueue" do new work each time. Any POST that a client may retry, which is every POST over a network, benefits from an idempotency key, and for money-moving operations it is essential.

The flow

  1. The client generates a unique key (a UUID) for the operation and sends it in a header, such as Idempotency-Key: 6f1c....
  2. The server looks up the key.
    • Not seen: record the key as "in progress", do the work, store the response with the key, return it.
    • Seen and completed: return the stored response without doing the work again.
    • Seen and in progress: return 409 Conflict (or wait), so two concurrent retries do not both run.
  3. Keys expire after a period (often 24 hours).

A server implementation

app.post('/v1/orders', async (req, res) => {
  const key = req.header('Idempotency-Key');
  if (!key) return res.status(400).json({ error: 'Idempotency-Key header is required' });
  const scope = `${req.auth.accountId}:${key}`;

  const inserted = await db.query(
    `INSERT INTO idempotency (scope, status, request_hash) VALUES ($1, 'in_progress', $2)
     ON CONFLICT (scope) DO NOTHING RETURNING scope`, [scope, hash(req.body)]);

  if (inserted.rowCount === 0) {
    const prev = await db.one('SELECT status, request_hash, response FROM idempotency WHERE scope = $1', [scope]);
    if (prev.request_hash !== hash(req.body)) return res.status(422).json({ error: 'Key reused with a different request' });
    if (prev.status === 'in_progress') return res.status(409).json({ error: 'Request in progress' });
    return res.status(prev.response.status).json(prev.response.body);
  }

  const order = await createOrder(req.body);
  const response = { status: 201, body: order };
  await db.query("UPDATE idempotency SET status = 'done', response = $2 WHERE scope = $1", [scope, response]);
  return res.status(201).json(order);
});

Details that matter

  • Scope keys per account so one client cannot collide with another.
  • Store a hash of the request and reject reuse of a key with a different body.
  • Do the work and record the result atomically where possible, for example in the same database transaction as the order insert, so a crash cannot leave work done but unrecorded.
  • Decide what to store for failures: replay 4xx validation errors; do not permanently store 5xx errors, so clients can retry after a transient failure.
  • Clean up expired keys with a scheduled job, and watch it with a heartbeat.

The client side

Generate the key once per logical operation, not per attempt, and reuse it on every retry of that operation. Combine with exponential backoff and jitter, and treat 409 as "try again shortly".

Worked example

A mobile app sends "pay invoice" over a flaky connection. The first request reaches the server and the payment succeeds, but the response is lost. The app retries with the same key 2 seconds later. The server finds the completed record, returns the same 201 response with the same payment ID, and the customer is charged exactly once. Without the key, the retry would have created a second charge, followed by a refund, a support ticket and an unhappy customer.

Monitoring

Track how often requests hit an existing key (a high rate means clients retry a lot, which may point to timeouts or network problems), 409 conflicts, and 422 key-reuse errors (client bugs). In traces, add an attribute such as idempotency.replayed=true so replayed requests are easy to find. VitalRix APM can then show replayed requests per endpoint next to latency and errors.

Checklist

  1. Required idempotency keys on every POST that changes state.
  2. Keys scoped per account and stored with a request hash.
  3. Work and key result recorded atomically.
  4. Stored responses replayed; transient errors not stored permanently.
  5. Expiry and cleanup with monitoring.
  6. Clients reuse the key across retries.

Related: API error handling best practices and API monitoring.

Common mistakes

  • Generating a new key for each retry, which defeats the purpose. One key per logical operation.
  • Storing the key only after the work completes, so two concurrent retries both do the work.
  • Keys that are not scoped, letting different clients collide on common values.
  • Permanently storing a 500 response, so a client can never succeed with that key after a transient failure.
  • No expiry, so the idempotency table grows forever and slows down.
How long should idempotency keys be kept?

Long enough to cover any client retry window, commonly 24 hours. Keep them longer for operations clients may retry after outages.

Are idempotency keys only for payments?

No. Any non-idempotent operation that clients retry, such as creating orders, sending messages or enqueueing jobs, benefits.

What if two requests with the same key arrive at once?

Record the key as in progress first; the second request sees it and gets a 409 or waits until the first completes.

Try VitalRix free

Uptime monitoring, APM, logs, real user monitoring and status pages in one place. No credit card needed.