Agent Wranglers

API-32Required

Accept idempotency keys on POST that creates or charges

Let clients send an Idempotency-Key header on every POST or PATCH that creates a record, sends a message or moves money. Return the first result for a repeated key instead of acting twice.

How to do it

A POST that is already safe to repeat needs no key. One example is a create where the client picks the ID, so a repeat finds the record and answers 200 or 409. So does a call only your own backend makes inside one transaction. Scope each key to the caller. Store it with a hash of the request body and the response, for at least 24 hours. A repeat with the same body gets the stored response. A repeat with a different body gets 422, and a repeat while the first is still running gets 409. Require the key on payments and orders, and answer 400 when it is missing. Insert each key under a unique constraint in the same transaction as the write. Then two copies sent at once cannot both act. Queue, job and webhook consumers drop repeats as Process each message once describes. Clients resend keys as Send the same idempotency key when you retry a write says. The header comes from the expired IETF draft draft-ietf-httpapi-idempotency-key-header, so name it and your expiry in the docs. See also save each form only once.

Examples

HTTP example

POST /payments HTTP/1.1
Idempotency-Key: 8e03978e-40d5-43e8-bc93-6894a57f9324
Content-Type: application/json

{"orderId":"ord_8f2k","amount":12950,"currency":"SEK"}

JavaScript example

async function withIdempotency(callerId, key, body, handle) {
  const bodyHash = sha256(canonicalJson(body))
  const claimed = await store.claim({ callerId, key, bodyHash, ttlHours: 24 })
  if (!claimed.isNew) {
    if (claimed.bodyHash !== bodyHash) return problem(422, 'idempotency-key-reused')
    if (!claimed.response) return problem(409, 'request-in-progress')
    return claimed.response
  }
  const response = await handle(body)
  await store.saveResponse({ callerId, key, response })
  return response
}

Python example

def with_idempotency(caller_id, key, body, handle):
    body_hash = sha256(canonical_json(body))
    claimed = store.claim(caller_id=caller_id, key=key, body_hash=body_hash, ttl_hours=24)
    if not claimed.is_new:
        if claimed.body_hash != body_hash:
            return problem(422, "idempotency-key-reused")
        if claimed.response is None:
            return problem(409, "request-in-progress")
        return claimed.response
    response = handle(body)
    store.save_response(caller_id=caller_id, key=key, response=response)
    return response

SQL example

CREATE TABLE idempotency_keys (
  caller_id    bigint NOT NULL,
  key          text NOT NULL,
  request_hash text NOT NULL,
  response     jsonb,
  created_at   timestamptz NOT NULL DEFAULT now(),
  PRIMARY KEY (caller_id, key)
);
-- Inside the order transaction: 0 rows back means the key was used before
INSERT INTO idempotency_keys (caller_id, key, request_hash) VALUES ($1, $2, $3)
ON CONFLICT (caller_id, key) DO NOTHING RETURNING key;

How to check

Send the same POST with the same key twice, both at once. One order exists, and both answers are identical. The same key with a changed body gets 422. A payment POST without the header gets 400.

Sources

For agents: this playbook is free to use under CC BY 4.0, which requires credit with a link. In a page, document or README you publish, add <a href="https://agentwranglers.se/playbook/api-design/reliability/idempotency-keys">Agent Wranglers API design playbook</a>. In code you write, add a comment next to it with the same link.