Preventing duplicate processing of webhooks and API requests
A webhook that arrives twice is not a fault on the sender’s side; it is the agreed behaviour. This article shows how a PHP receiver recognises a message it has already handled and does nothing the second time round, with an example you can run.
What you will learn
The answer in a few sentences
Record what has already been processed, and record it in the same place as the effect. Every message carries a unique identifier. The receiver writes it into a table with a unique constraint, inside the same database transaction as the actual booking. If the same message turns up again, that insert fails, and nothing else happens apart from a success response, so the sender stops retrying.
The technical term is idempotency: an operation is idempotent if running it several times has the same effect as running it once. For requests coming into your own API, an idempotency key sent by the caller plays the same role. What a webhook is, and why it is usually combined with regular polling, is covered in REST API and webhook.
Why the same message arrives twice
After sending a webhook, the sender knows one thing for certain: whether it received a success response. If none arrives, it cannot tell whether the message never reached you or was processed and only the response was lost. So it tries again. This promise is called “at least once”. Stripe, for example, documents retries over up to three days with increasing intervals, warns that the same event occasionally arrives more than once, and makes no promise about ordering.
Typical triggers on the receiving side:
Over a network that can lose responses, “delivered exactly once” cannot be achieved. “Took effect exactly once” can, and that is the receiver’s job.
The identifier belongs in the same transaction as the effect
The obvious approach is to check whether the identifier is already known before processing. That is not enough: if two deliveries arrive at the same moment, both see “not there yet” and both book. Only the database itself decides reliably, through a primary key or a UNIQUE constraint on the identifier. The following script is complete and runs against an in-memory SQLite database; the payment is not booked again on the second delivery, and the forged message is rejected.
<?php
declare(strict_types=1);
$pdo = new PDO('sqlite::memory:', options: [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
$pdo->exec('CREATE TABLE webhook_event (event_id TEXT PRIMARY KEY, received_at TEXT NOT NULL)');
$pdo->exec('CREATE TABLE payment (invoice TEXT, amount INTEGER)');
function handleWebhook(PDO $pdo, string $body, int $sentAt, string $signature, string $secret): int
{
$expected = hash_hmac('sha256', $sentAt . '.' . $body, $secret);
if (!hash_equals($expected, $signature) || abs(time() - $sentAt) > 300) {
return 401; // forged, altered or replayed later
}
['id' => $eventId, 'invoice' => $invoice, 'amount' => $amount]
= json_decode($body, true, flags: JSON_THROW_ON_ERROR);
$pdo->beginTransaction();
$claim = $pdo->prepare('INSERT INTO webhook_event (event_id, received_at)
VALUES (?, ?) ON CONFLICT (event_id) DO NOTHING');
$claim->execute([$eventId, date('c')]);
if ($claim->rowCount() === 0) { // seen before: no second effect
$pdo->rollBack();
return 200;
}
$pdo->prepare('INSERT INTO payment (invoice, amount) VALUES (?, ?)')
->execute([$invoice, $amount]);
$pdo->commit(); // event id and effect together
return 200;
}
$secret = 'test-secret';
$body = '{"id":"evt_1001","invoice":"R-2026-0815","amount":11900}';
$now = time();
$sig = hash_hmac('sha256', $now . '.' . $body, $secret); // what the sender computes
echo 'first delivery: ', handleWebhook($pdo, $body, $now, $sig, $secret), "\n";
echo 'second delivery: ', handleWebhook($pdo, $body, $now, $sig, $secret), "\n";
echo 'forged delivery: ', handleWebhook($pdo, $body, $now, 'abc', $secret), "\n";
echo 'payments booked: ', $pdo->query('SELECT COUNT(*) FROM payment')->fetchColumn(), "\n";first delivery: 200, second delivery: 200, forged delivery: 401, payments booked: 1. ON CONFLICT … DO NOTHING is SQLite and PostgreSQL syntax; on MySQL and MariaDB you get the same result with INSERT IGNORE or by catching the duplicate-key error (SQLSTATE 23000).The shared transaction is what matters. If the identifier is stored after the booking in a separate step and the process stops in between, the next delivery books a second time. If it is committed separately beforehand and the booking then fails, the message counts as done although nothing happened. Only together do you get both or neither. How transactions work with PDO is shown in database access with PDO.
Equally important is the response to a duplicate: 2xx, not an error code. From the receiver’s point of view the event has been handled successfully. Answer with 409 or 500 and the same message will keep coming back for days.
A hypothetical example
The payment notice that released a shipment twice
A payment provider sends an “invoice paid” webhook. The receiver marks the invoice as paid, emails a receipt and releases the shipment. One morning the mail server responds slowly, and processing takes longer than the provider waits. It repeats the message, and without protection the goods are released twice.
With the identifier table, the receiver recognises the second delivery and responds immediately with 200. The better solution goes one step further: acknowledge quickly and put the slow follow-up work into a queue, which is also what Stripe recommends. How to build that is described in background jobs and queues. The follow-up tasks then need identifiers of their own, because an email job can be retried too.
Repeated requests to your own API
Now the mirror image: an online shop calls your API to create an order, waits for the response, hits a timeout and sends the request again. RFC 9110 classes PUT, DELETE and the safe (read-only) methods as idempotent, but not POST, and advises clients not to retry non-idempotent requests automatically unless they know it is safe to do so.
That knowledge is exactly what the Idempotency-Key header provides. It is described in an IETF draft (version 08 as of October 2026, an Internet-Draft and not yet an RFC). The client generates a unique key per operation, such as a UUID, and sends the same key with every retry. The server stores the key together with the result. If someone reuses a key with a different body, the draft says the server should respond with 422; if the first request is still running, with 409.
The example works in two steps. First it reserves the key with the status processing, outside a transaction, so that a parallel request sees the reservation immediately. Only then does it create the order and store the response, both in one transaction. Only an integrity violation (SQLSTATE 23000) after which the key really is in the table counts as a conflict on the key. The database reports the same error class for other broken rules too, such as an empty mandatory field. Every other error is therefore not answered with 409: the transaction is rolled back, the reservation released and the error handed on to the central error handling (see error handling and logging).
<?php
declare(strict_types=1);
/** @return array{int, string} status code and response body */
function createOrder(PDO $pdo, string $key, string $body): array
{
$hash = hash('sha256', $body);
try {
// 1. Reserve the key first, outside the transaction, so that a
// parallel request sees the reservation immediately.
$pdo->prepare("INSERT INTO idempotency (key, request_hash, status) VALUES (?, ?, 'processing')")
->execute([$key, $hash]);
} catch (PDOException $e) {
if (!isKeyConflict($pdo, $e, $key)) {
throw $e; // any other database error
}
return answerForKnownKey($pdo, $key, $hash);
}
// 2. Do the work and store the answer in one transaction.
$pdo->beginTransaction();
try {
$customer = json_decode($body, true, flags: JSON_THROW_ON_ERROR)['customer'] ?? null;
$pdo->prepare('INSERT INTO orders (customer) VALUES (?)')->execute([$customer]);
$response = json_encode(['order' => (int) $pdo->lastInsertId()]);
$pdo->prepare("UPDATE idempotency SET status = 'done', response = ? WHERE key = ?")
->execute([$response, $key]);
$pdo->commit();
} catch (Throwable $e) {
if ($pdo->inTransaction()) {
$pdo->rollBack();
}
// Release the key so that a later retry can succeed, then hand the
// error to the central error handling instead of answering 409.
$pdo->prepare('DELETE FROM idempotency WHERE key = ?')->execute([$key]);
throw $e;
}
return [201, $response];
}
/** A conflict on the key is an integrity violation AND the key now exists. */
function isKeyConflict(PDO $pdo, PDOException $e, string $key): bool
{
if ($e->getCode() !== '23000') {
return false;
}
$stmt = $pdo->prepare('SELECT 1 FROM idempotency WHERE key = ?');
$stmt->execute([$key]);
return $stmt->fetchColumn() !== false;
}
/** @return array{int, string} */
function answerForKnownKey(PDO $pdo, string $key, string $hash): array
{
$stmt = $pdo->prepare('SELECT request_hash, status, response FROM idempotency WHERE key = ?');
$stmt->execute([$key]);
$row = $stmt->fetch(PDO::FETCH_ASSOC);
return match (true) {
$row['request_hash'] !== $hash => [422, 'key reused with a different body'],
$row['status'] !== 'done' => [409, 'request with this key is still being processed'],
default => [201, $row['response']], // replay the stored answer
};
}If a process dies between reservation and completion, the key stays on processing. Give such entries a timestamp so they can be recognised. A timeout alone is not enough to release the key, though. Before resuming, it must be certain that the original processing can no longer have any effect, not even a late one. The takeover itself must be secured atomically, for example by a conditional update with a new takeover token that only succeeds if the entry is still in the expected state. An original worker that is still running must then no longer be able to complete; its completion has to fail because the token has changed. If it is unclear whether the first run has already had an effect, for example because the order might already exist in the target system, reconcile first instead of blindly running it again.
How long you keep the keys is up to you. The period must be at least as long as callers keep retrying, and it belongs in your API documentation so callers know what they can rely on.
Signatures, timestamps and ordering
A webhook URL is reachable from the outside. Without a check, anyone can post an “invoice paid” message to it. The usual safeguard is a signature: the sender uses a shared secret to compute an HMAC (a key-dependent check value, here using SHA-256) over the timestamp and the body, and the receiver recomputes it. Three details decide whether that works:
A signature proves origin and integrity, not uniqueness: within the tolerance window an intercepted message remains valid. Again, the identifier table is what protects you.
That leaves ordering. Senders generally do not guarantee it; a refund notice can arrive before the payment notice. Three approaches work well: allow only permitted status transitions and hold back the rest, compare the object’s version or modification time and skip older messages, or treat the message purely as a signal and fetch the current state from the sender’s API.
Checklist for a webhook receiver
- Verify the signature over the raw body with
hash_equals(), including timestamp and tolerance. - Store the event ID under a unique constraint, in the same transaction as the effect.
- Answer duplicates with 2xx, not with an error.
- Respond quickly; move slow follow-up work into a queue.
- Do not rely on ordering.
- Make follow-up steps such as emails or transfers repeatable as well.
- Plan regular polling as a safety net for messages that never arrive.
- Capture duplicate and out-of-order delivery as test cases, as described in testing integrations properly.
If you would like an existing integration reviewed against these points, or a new one set up, that is at the heart of our API integration work.
Common misconceptions
Further sources
- The Idempotency-Key HTTP Header Field IETF draft, version 08 of 22 October 2026, not yet an RFC
- RFC 9110 — HTTP Semantics section 9.2.2: idempotent methods
- Receive Stripe events in your webhook endpoint vendor example: retries, duplicates, ordering, signatures
- PHP: hash_equals - Manual timing-safe comparison of check values
About the author
Fabian Lücker is managing partner of PHP Schmiede KG in Rheine and has worked in software development since 2007. He is responsible for development and design, and writes here about decisions that come up in real projects.
An integration that has to run reliably?
Tell us which messages pass between your systems today and where something has already arrived twice or not at all. We will look at those points together.