Skip to content
Sandeep Kumar
Updated 5 min read

Idempotent APIs and webhooks: making retries safe

Retries are not optional, so duplicate requests are not either. Idempotency keys, natural keys and upserts that make a replayed request cost nothing.

Sandeep Kumar, Full-stack EngineerSandeep KumarFull-stack Engineer
On this page
  1. Retries are not optional, so duplicates are not either
  2. When the payload already has a key
  3. When there is no natural key
  4. Consuming webhooks, where you are the one being retried
  5. Watch the duplicate rate, not the error rate
  6. It is not a hardening task

Every network call can fail in a way that leaves the caller unsure whether it worked. A timeout. A dropped connection. A 502 from a proxy sitting in front of a request that actually completed. The client has one reasonable response, which is to try again.

So every write endpoint will eventually receive the same request twice, whether or not anyone designed it to. The only question is whether the second one is harmless or produces a duplicate charge, a duplicate lead, a duplicate order.

Retries are not optional, so duplicates are not either

The instinct is to make retries rarer. Longer timeouts, better error handling, fewer moving parts. That treats the symptom, and it does not work, because retries come from clients you do not control: mobile apps on bad connections, third-party webhook senders, job queues, load balancers, users double-clicking a button that looked stuck.

The framing I find useful is to make a repeated request cost nothing, and then retry freely. In that order, aggressive retries are a reliability feature. In the other order they are a data-corruption feature with a reliability story attached.

When the payload already has a key

Most of the time something in the request identifies the operation uniquely. A provider's record id, an order number, a transaction reference. That is a natural key and the database can enforce it.

sql
CREATE TABLE lead (
  id           BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
  source       VARCHAR(32)  NOT NULL,
  source_ref   VARCHAR(64)  NOT NULL,   -- the sender's own id
  payload      JSON         NOT NULL,
  status       VARCHAR(24)  NOT NULL DEFAULT 'new',
  created_at   DATETIME     NOT NULL,
  UNIQUE KEY uniq_source_ref (source, source_ref)
);

Then write through an upsert rather than an insert:

php
public function store(string $source, array $record): void
{
    Yii::$app->db->createCommand()->upsert('lead', [
        'source'     => $source,
        'source_ref' => $record['id'],
        'payload'    => json_encode($record, JSON_UNESCAPED_UNICODE),
        'created_at' => $record['created_at'],
    ], [
        // Refresh only what the sender owns. Never reset status — a human may have worked it.
        // VALUES(payload) is deprecated from MySQL 8.0.20; on 8.0.19+ prefer the row alias
        // form: INSERT … AS new ON DUPLICATE KEY UPDATE payload = new.payload
        'payload' => new Expression('VALUES(payload)'),
    ])->execute();
}

Two details matter more than they look.

Enforce it in the database, not the application. The select-check-insert version has a race window between the check and the insert, and two concurrent deliveries will find it. Under load they will find it often. A unique constraint is atomic and no interleaving defeats it.

And be careful what the update clause touches. The second delivery may arrive after a human has already worked the record, so an upsert that overwrites status drags closed work back into the queue. That is the same bug the idempotency was meant to prevent, wearing a different costume and harder to spot.

When there is no natural key

Some operations genuinely contain nothing unique. "Charge this card ₹2,000" is byte-identical whether it is a retry or a second, deliberate purchase. Only the client knows which one it is.

So the client supplies the distinction: an idempotency key, generated once per logical operation and resent on every retry.

http
POST /api/payments
Idempotency-Key: 6a1f0c7e-2b43-4f9a-9d1c-0e2f5a7b8c90

The server records the key alongside the outcome:

sql
CREATE TABLE idempotency (
  id            VARCHAR(64) PRIMARY KEY,     -- the key
  request_hash  CHAR(64)    NOT NULL,        -- fingerprint of the payload
  status_code   SMALLINT    NULL,
  response      JSON        NULL,
  state         ENUM('in_progress','done') NOT NULL,
  created_at    DATETIME    NOT NULL
);

And the handler becomes:

php
public function handle(string $key, array $payload): Response
{
    $hash = hash('sha256', json_encode($payload));

    // Claim the key. A duplicate request loses this race by design.
    $claimed = $this->db->createCommand(
        'INSERT IGNORE INTO idempotency (id, request_hash, state, created_at)
         VALUES (:id, :hash, "in_progress", NOW())'
    )->bindValues([':id' => $key, ':hash' => $hash])->execute();

    if (!$claimed) {
        $row = $this->findKey($key);
        if ($row['request_hash'] !== $hash) {
            // Same key, different body — a client bug worth surfacing loudly.
            return new Response(422, ['error' => 'idempotency key reused with a different payload']);
        }
        if ($row['state'] === 'in_progress') {
            return new Response(409, ['error' => 'request already in progress']);
        }
        return new Response($row['status_code'], json_decode($row['response'], true));
    }

    $result = $this->performWork($payload);
    $this->completeKey($key, $result);
    return $result;
}

Three behaviours fall out of that, and all three earn their complexity.

A retry after success replays the stored response, so the work happens once and the client still gets its answer. A retry arriving while the first is still running gets a 409 instead of racing it, which is what the in_progress state is for, and without it two concurrent retries both proceed and you are back where you started. And a key reused with a different payload is rejected outright, because that is a client bug and silently returning the old response hides it for months.

Consuming webhooks, where you are the one being retried

Everything above assumes you are the server deciding policy. When you consume webhooks you are on the receiving end of someone else's, and senders retry generously, including after your endpoint returned 200 but the connection dropped before they saw it.

Store the sender's id with a unique constraint, which is the first case again, so a replayed delivery converges on one row.

Acknowledge fast and process afterwards. Write the raw payload, return 200, do the real work in a queue. A handler that calls three services before responding will eventually exceed the sender's timeout and get retried while it is still working, which is how one delivery becomes four.

And verify the signature before trusting any of it, because an endpoint that accepts unsigned payloads is an endpoint anyone can write to.

php
// Constant-time comparison: a plain === leaks timing information.
if (!hash_equals($expected, $provided)) {
    return new Response(401);
}

Then assume delivery fails sometimes regardless, because a webhook is a delivery attempt and not a guarantee. If the records matter, pair it with a scheduled reconcile that pulls from the sender's API and writes through the same idempotent path. Because the write is idempotent, the reconciler costs nothing on the days the webhook worked.

This is the foundation a lead pipeline rests on, and the reason custom CRM development treats it as a day-one concern rather than hardening.

Watch the duplicate rate, not the error rate

A correctly idempotent system produces very few errors, which is the problem. Errors are no longer the signal.

Watch how often a request arrives whose key or natural key already exists. A steady background level is healthy and means retries are happening and being absorbed exactly as designed. A sudden spike means something upstream is failing and retrying hard, which is precisely the moment you want to know and precisely the moment nothing is throwing an exception anywhere.

It is not a hardening task

Idempotency is the property that makes every other reliability measure safe to add. Retries, queues and reconcilers are all actively dangerous without it, and all three are things you will add.

The implementation is nearly always one of two things. A unique constraint on a key the payload already carries, or a key the client supplies with the stored response sitting behind it.

Both are about a day of work. Both are considerably cheaper than deduplicating a production table by hand while someone asks for an ETA.

Frequently asked

What does idempotent mean for an API?

An endpoint is idempotent when making the same request twice leaves the system in the same state as making it once. GET and DELETE are naturally idempotent; POST usually is not, which is why payment and lead endpoints need an explicit mechanism such as an idempotency key or a unique natural key.

What is an idempotency key?

A unique string the client generates per logical operation and sends with the request, commonly in an Idempotency-Key header. The server stores the key with the result of the first request, and any later request carrying the same key returns that stored result instead of performing the work again. It is how payment APIs make a retried charge safe.

Should idempotency be handled in code or in the database?

In the database wherever a natural key exists. A check-then-insert in application code has a race window that two concurrent requests will eventually hit, and under load they will. A unique constraint is evaluated atomically, so the second write fails or converges no matter how the requests interleave.

How long should idempotency keys be kept?

Long enough to cover the retry behaviour of every client, which typically means 24 hours to a few days. Keep them too briefly and a delayed retry duplicates the work; keep them forever and the table grows without bound. Store an expiry and prune on a schedule.

Found this useful?Share on XShare on LinkedIn

Related reading