Preventing duplicate webhook processing in PHP
Webhook providers retry, so the same event can arrive twice. Verify the signature, record the event ID with a unique key, answer fast and process in a queue: a pattern that works in plain PHP, Laravel and Symfony.
On this page
Payment providers, Git hosts and email services deliver webhooks at least once. If your endpoint is slow, times out or returns an error, they send the same event again. Without protection you charge twice, send two emails or create duplicate orders.
The pattern
- Verify the signature on the raw request body.
- Record the provider’s event ID in a table with a unique index. If the insert fails, you have seen it already: return 200 and stop.
- Queue the work and return a 2xx response immediately.
- Process in the job, inside a transaction, and mark the event as processed.
1. Verify the signature on the raw body
Most providers sign the exact bytes they sent with HMAC-SHA256. Read the raw body before any framework parses it, and compare in constant time:
$payload = file_get_contents('php://input');
$signature = $_SERVER['HTTP_X_SIGNATURE'] ?? '';
$expected = hash_hmac('sha256', $payload, $secret);
if (!hash_equals($expected, $signature)) {
http_response_code(401);
exit;
}
Many providers also sign a timestamp; reject events older than a few minutes to stop replays. Use the provider’s SDK helper when one exists, because header formats differ.
2. Make the event ID unique in the database
CREATE TABLE webhook_events (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
provider VARCHAR(32) NOT NULL,
event_id VARCHAR(191) NOT NULL,
received_at DATETIME NOT NULL,
processed_at DATETIME NULL,
UNIQUE KEY uniq_event (provider, event_id)
);
try {
$pdo->prepare('INSERT INTO webhook_events (provider, event_id, received_at) VALUES (?, ?, NOW())')
->execute(['acmepay', $event['id']]);
} catch (PDOException $e) {
if ($e->getCode() === '23000') { // duplicate key: already received
http_response_code(200);
exit;
}
throw $e;
}
The unique index is what makes this safe under concurrency. A “select, then insert if missing” check has a race: two deliveries arriving at the same moment both see nothing and both insert. In Laravel, WebhookEvent::firstOrCreate() has the same race unless the unique index is there to back it.
3. Answer fast, work later
Providers time out after a few seconds. Dispatch a job and return:
ProcessWebhook::dispatch($eventRowId);
return response()->noContent(); // 204
If the queue is down, return a 5xx so the provider retries; your unique index will absorb any duplicate.
4. Process once, even when the job retries
Jobs can also run twice (after a worker timeout, for example). Check and set processed_at in the same transaction as the side effect:
DB::transaction(function () use ($id) {
$event = WebhookEvent::lockForUpdate()->findOrFail($id);
if ($event->processed_at) {
return;
}
// ... create the order, mark the invoice paid, etc.
$event->update(['processed_at' => now()]);
});
For side effects outside your database, such as calling another API, pass an idempotency key derived from the event ID if that API supports one.
Ordering
Events can arrive out of order: subscription.updated before subscription.created. Do not rely on arrival order. Store the provider’s timestamp or version and ignore events older than what you already have, or re-fetch the current state from the provider’s API when an event arrives.