Skip to content
envexa

Backend Engineering

Idempotency keys: designing APIs that are safe to retry

Networks fail and clients retry. How idempotency keys prevent duplicate charges and orders, with implementation, edge cases and storage design.

By Envexa Engineering6 min read

A client sends a payment request and the connection drops. Did the server process it? The client cannot know, so it retries, and if the server is not designed for this, the customer is charged twice. The same problem hits order creation, email sending, webhooks and background jobs. The solution is idempotency: performing the same operation more than once has the same effect as performing it once.

What is already idempotent

In HTTP, GET, PUT and DELETE are defined as idempotent: setting a resource to a state, or deleting it, can be repeated safely. POST is not, and it is where duplicates come from. Even PUT and DELETE implementations can break the guarantee if they have side effects such as sending a notification each time.

The idempotency key pattern

  1. The client generates a unique key (a UUID) for each logical operation and sends it in an Idempotency-Key header, reusing the same key when it retries.
  2. The server stores the key with the request fingerprint and the result.
  3. If the key has been seen and finished, the server returns the stored response without redoing the work.
  4. If the key is currently being processed, the server returns a conflict, or waits, rather than starting a second run.
  5. If the key is reused with a different payload, the server rejects it as a client error.

A storage design that works

CREATE TABLE idempotency_keys (
  key          text        NOT NULL,
  tenant_id    uuid        NOT NULL,
  request_hash text        NOT NULL,
  status       text        NOT NULL,  -- 'in_progress' | 'completed'
  response     jsonb,
  created_at   timestamptz NOT NULL DEFAULT now(),
  PRIMARY KEY (tenant_id, key)
);

-- claim the key atomically; zero rows inserted means it already exists
INSERT INTO idempotency_keys (key, tenant_id, request_hash, status)
VALUES ($1, $2, $3, 'in_progress')
ON CONFLICT DO NOTHING;

The primary key makes claiming a key atomic: two concurrent requests with the same key cannot both insert. Scope keys per tenant or user so one customer cannot collide with, or probe, another's. Expire old keys after a sensible window such as 24 hours.

Do the work and the record in one transaction

Where the operation is entirely in your database, write the business change and mark the key completed in the same transaction, so they succeed or fail together. For operations that call an external service, such as a payment provider, pass your own idempotency key through to them too, and record the outcome durably so a retry after a crash can resume or return the result.

Edge cases to decide up front

  • Crash mid-request. An in_progress key with no live worker should become retryable after a timeout.
  • Failed requests. Decide whether errors are stored and replayed, or whether a failed attempt releases the key. Replay client errors; release on transient server errors.
  • Same key, different body. Return an explicit error. Silently accepting it hides client bugs.
  • Response consistency. Return the original status code and body, including identifiers, so the client cannot tell it was a replay.

Inbound webhooks and queues

The same idea applies when you are the receiver. Webhook providers and queues deliver at least once, so record each event ID and ignore ones you have already processed. Use a unique constraint so that concurrent duplicates cannot both succeed.

Idempotency is cheap to build at the start and painful to retrofit after the first duplicate charge. Treat every operation with a side effect as something that will be sent twice, and design it so that is fine.

API designIdempotencyReliabilityPostgreSQL

Building something like this?

We are happy to review your architecture or help you build it.