A practical pattern for handling duplicate deliveries, concurrent requests, retries, and the gap between database commits and queued jobs.
A webhook endpoint can receive the same event more than once.
That sounds like a small integration detail until the event represents something important:
- A successful payment.
- A subscription activation.
- An order fulfillment.
- A customer account update.
- An inventory adjustment.
If the same event is processed twice, the application might accidentally perform the same business operation twice.
A common mistake is to assume that moving webhook processing into a Laravel queue solves this problem.
It doesn't.
Queues help manage asynchronous workloads. Idempotency requires a separate design.
1. Understand Why Duplicate Webhook Deliveries Happen
Webhook providers generally use retries to handle temporary delivery failures.
For example, Stripe documents that webhook deliveries can be retried, events may arrive out of order, and the same event may be delivered multiple times.
Consider this scenario:
10:00:00 - Payment succeeds
10:00:01 - Webhook received
10:00:02 - Application processes payment
10:00:03 - Response fails to reach provider
10:00:10 - Provider retries webhook
10:00:11 - Application receives the same event again
From the provider's perspective, the previous delivery might not have succeeded.
From your application's perspective, the payment may already have been processed.
This is why a webhook handler must not assume that every incoming request represents a new business event.
2. Separate Webhook Reception from Business Processing
A good architecture separates three responsibilities:
- Verify and receive the event.
- Persist the event safely.
- Process the event asynchronously.
A simplified architecture looks like this:
Webhook Provider
|
v
Laravel Webhook Endpoint
|
v
Signature Verification
|
v
Database Event Receipt
|
v
Outbox / Queue Dispatcher
|
v
Laravel Queue Worker
|
v
Business Logic
The HTTP endpoint should perform only the work required to securely accept the event.
For Stripe, signature verification must use the original request body. Complex processing should be deferred so the endpoint can return a successful response quickly.
This reduces the amount of work happening inside the webhook request itself.
3. Create a Durable Webhook Receipt Table
The database should be responsible for preventing duplicate event records.
A migration could look like this:
Schema::create('webhook_receipts', function (Blueprint $table) {
$table->id();
$table->string('provider', 40);
$table->string('event_id');
$table->string('event_type');
$table->json('payload');
$table->string('status')->default('received');
$table->timestamp('processed_at')->nullable();
$table->timestamps();
$table->unique([
'provider',
'event_id',
]);
});
The important part is the composite unique constraint:
$table->unique([
'provider',
'event_id',
]);
Why include the provider?
Because an application may eventually receive events from multiple services. Keeping the provider and event identifier together gives the database a clear deduplication boundary.
4. Use Laravel's createOrFirst() Instead of Check-Then-Insert
Consider this implementation:
$existing = WebhookReceipt::query()
->where('provider', 'stripe')
->where('event_id', $eventId)
->first();
if (! $existing) {
WebhookReceipt::create([
'provider' => 'stripe',
'event_id' => $eventId,
]);
}
It looks reasonable.
But there is a concurrency problem.
Two webhook requests can execute the existence check at almost the same time.
Both requests may see that the event does not exist.
Both then attempt to insert it.
This is a classic race condition.
Laravel's Eloquent builder provides createOrFirst(), which attempts the insert first and handles a unique constraint violation by retrieving the existing record.
For example:
$receipt = WebhookReceipt::query()->createOrFirst(
[
'provider' => 'stripe',
'event_id' => $event['id'],
],
[
'event_type' => $event['type'],
'payload' => $event['payload'],
'status' => 'received',
]
);
if (! $receipt->wasRecentlyCreated) {
return response()->noContent();
}
Here, the provider-specific verifier is assumed to have already validated the request and normalized its event data.
The important distinction is that the database constraint protects the insert, rather than relying on an earlier application-level existence check.
5. Don't Confuse Queue Uniqueness with Business Idempotency
Laravel supports unique jobs through the ShouldBeUnique interface.
For example:
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Contracts\Queue\ShouldBeUnique;
class ProcessWebhookReceipt implements ShouldQueue, ShouldBeUnique
{
public function __construct(
public int $receiptId,
) {}
public function uniqueId(): string
{
return (string) $this->receiptId;
}
}
This can prevent another instance of the same unique job from being dispatched while the existing job holds its uniqueness lock.
However, this is not a replacement for database-level idempotency.
There are important limitations:
- Unique jobs depend on a cache driver supporting atomic locks.
- Unique job constraints do not apply to jobs inside batches.
- A job can be dispatched again after its uniqueness lock is released.
- A worker may retry a job after partial processing.
Think of ShouldBeUnique as an additional queue-level optimization, not the ultimate protection for your business data.
6. Understand the Database Transaction and Queue Dispatch Gap
Another subtle problem occurs when dispatching jobs inside database transactions.
Imagine this:
DB::transaction(function () use ($receipt) {
$receipt->update([
'status' => 'received',
]);
ProcessWebhookReceipt::dispatch($receipt->id);
});
Depending on the queue configuration, a worker may start processing the job before the database transaction commits.
The worker might not see the latest database state.
Laravel provides afterCommit() and the after_commit queue configuration to address this problem.
For example:
ProcessWebhookReceipt::dispatch($receipt->id)
->afterCommit();
This ensures the job is dispatched after the surrounding transaction commits.
But there is another consideration.
afterCommit() does not make a database write and an external queue publish one atomic operation.
If the database commits and the application fails before the queue message is successfully published, the event receipt can exist without a corresponding job.
For more reliable event processing, consider the transactional outbox pattern.
7. Use the Transactional Outbox Pattern for Reliable Dispatch
An outbox stores the intention to perform asynchronous work in the same database transaction as the original event receipt.
The workflow becomes:
BEGIN TRANSACTION
|
+-- Insert webhook receipt
|
+-- Insert outbox message
|
COMMIT
|
v
Outbox Dispatcher
|
v
Queue Job
|
v
Business Processing
A simplified implementation:
DB::transaction(function () use ($event) {
$receipt = WebhookReceipt::query()->createOrFirst(
[
'provider' => 'stripe',
'event_id' => $event['id'],
],
[
'event_type' => $event['type'],
'payload' => $event['payload'],
'status' => 'received',
]
);
if ($receipt->wasRecentlyCreated) {
WebhookOutbox::create([
'webhook_receipt_id' => $receipt->id,
'message_type' => 'process_webhook_receipt',
]);
}
});
The outbox dispatcher reads committed, unpublished messages and sends corresponding jobs to the queue.
It should use an atomic claiming or lease mechanism to coordinate multiple dispatchers.
If a dispatcher crashes after publishing a job but before marking its outbox message as published, the job may be dispatched again.
That is acceptable when the worker is also designed to be idempotent.
The important benefit is that the intention to process the event is stored durably, so a temporary queue publishing failure does not leave the system with no record of pending work.
8. Make Business Operations Idempotent Too
Preventing duplicate event records is only one layer of protection.
The actual business operation must also be safe to repeat.
For example, consider:
$account->increment('balance', 100);
If the same operation executes twice, the balance increases twice.
A safer approach depends on the business operation.
For state transitions, prefer setting a desired state:
$subscription->update([
'status' => 'active',
]);
For financial transactions, use a ledger with a unique external transaction reference.
For external API calls, use the provider's supported idempotency mechanism where available.
Also remember that two different event IDs can sometimes represent the same underlying business change.
Event deduplication and business-operation deduplication are related, but they are not identical.
9. Don't Assume Events Arrive in the Correct Order
Another common mistake is processing webhook events as though they always arrive sequentially.
Consider:
subscription.updated
subscription.created
If the update arrives first, a naive handler might overwrite newer application state when the older creation event arrives later.
For integrations where event ordering matters:
- Identify the affected business resource.
- Understand the provider's event ordering guarantees.
- Use version or timestamp information only where the provider documents it as suitable.
- Retrieve the current resource state from the provider when necessary.
- Make state transitions resilient to repeated and delayed events.
The correct strategy depends on the provider's event model.
10. Test More Than the Successful Webhook Response
A webhook test that checks only for an HTTP 200 response is incomplete.
Include these scenarios in the test plan:
| Scenario | Expected behavior |
|---|---|
| Same event delivered twice | One receipt |
| Two concurrent deliveries | One receipt |
| Different event IDs | Both receipts retained |
| Queue dispatch temporarily fails | Pending outbox message remains recoverable |
| Worker retries | Business operation remains safe |
| Events arrive out of order | Application state does not regress |
| Invalid signature | Request rejected |
Also test the actual database constraint rather than relying exclusively on mocked repositories.
Concurrency-related bugs can be difficult to discover when tests only execute requests sequentially.
Final Thoughts
A reliable webhook integration is not simply an HTTP endpoint connected to a Laravel queue.
It is a system that needs to handle retries, duplicate requests, concurrent execution, database transactions, queue failures, and delayed events.
A robust design separates these concerns:
- Verify incoming requests.
- Persist event receipts using database uniqueness.
- Use an outbox when durable queue dispatch matters.
- Process asynchronously.
- Make business operations idempotent.
- Test duplicate and failure scenarios.
The most important lesson is this:
A queue can help you process work asynchronously, but your database and business logic must make repeated processing safe.

Top comments (1)
The increment vs set-the-state example in section 8 is the part I'd want more people to read. You can get the receipt table perfect and still double someone's balance if the handler itself isn't safe to run twice.
Also glad you showed check-then-insert as the wrong version. It reads so naturally that most people would write it first and never think about two requests landing in the same second.