跳到正文
DEV Community· Saleh Ahammed Noor·· 50 分鐘前AI 評分58

Laravel Webhook Inbox 模式如何安全處理重試

The Webhook Inbox Pattern: Making Laravel Integrations Safe to Retry

AI 導讀

文章介紹 Laravel 的持久化 Webhook Inbox 模式,將事件接收與業務處理分開,令 HTTP 成功回應只代表事件已安全接收,而非下游操作已完成。

正文

How to handle duplicate events, queue failures, concurrent processing, and out-of-order delivery without corrupting business data.

The Webhook Inbox Pattern: Making Laravel Integrations Safe to Retry

A webhook endpoint returning HTTP 200 does not necessarily mean the business operation was completed successfully.

It only means the receiving application acknowledged the request.

This distinction becomes important when integrating payment gateways, subscription platforms, ERP systems, and other external services.

A provider may retry an event because of a timeout. The same event may arrive twice. Two different events may arrive in an unexpected order. A queue job may fail after the webhook endpoint has already acknowledged the request.

If the application assumes every webhook arrives exactly once and in order, eventually something will go wrong.

A useful architectural pattern for handling these situations is a durable webhook inbox.

1. Why Traditional Webhook Handlers Become Unreliable

Consider a typical payment integration.

A customer completes a payment, and the payment provider sends an event:

{
    "id": "evt_example_123",
    "type": "payment_intent.succeeded",
    "data": {
        "object": {
            "id": "pi_example_456",
            "status": "succeeded"
        }
    }
}

A basic Laravel controller might immediately update an order:

public function handle(Request $request)
{
    $event = $request->all();

    if ($event['type'] === 'payment_intent.succeeded') {
        Order::where('payment_id', $event['data']['object']['id'])
            ->update(['status' => 'paid']);
    }

    return response()->json(['success' => true]);
}

This looks reasonable, but several problems are hidden inside it:

  • What happens if the provider sends the same event again?
  • What happens if the database update succeeds but the response times out?
  • What happens if the application crashes halfway through processing?
  • What happens if two copies arrive simultaneously?
  • What happens if an older event arrives after a newer event?

Stripe explicitly documents duplicate event deliveries and warns that event delivery order is not guaranteed.

The application must be designed around those possibilities.

2. Introduce a Durable Webhook Inbox

Instead of processing everything inside the HTTP request, separate receiving an event from processing it.

The architecture becomes:

External Provider
       |
       v
Webhook Endpoint
       |
       v
Verify Signature
       |
       v
Store Event in Database
       |
       v
Return HTTP 2xx
       |
       v
Queue Processing Job
       |
       v
Apply Business Logic
       |
       v
Mark Event Processed

The database becomes the reliable record of received events.

Start with a dedicated table:

Schema::create('webhook_events', function (Blueprint $table) {
    $table->id();

    $table->string('provider', 40);
    $table->string('event_id', 191);
    $table->string('event_type', 120);

    $table->json('payload');

    $table->timestamp('received_at');
    $table->timestamp('processed_at')->nullable();

    $table->timestamps();

    $table->unique([
        'provider',
        'event_id',
    ]);

    $table->index([
        'processed_at',
        'received_at',
    ]);
});

The most important part is the unique constraint:

$table->unique(['provider', 'event_id']);

This prevents the same provider event from being recorded multiple times.

Including the provider name also allows the application to support multiple integrations without assuming that event IDs are globally unique across providers.

3. Verify First, Persist Second

Never trust an incoming webhook simply because it contains a familiar event name.

Signature verification must happen before business logic.

For providers that sign the request body, use the original raw request body rather than a re-serialized JSON representation.

For example, Stripe requires the raw request body for signature verification.

A clean Laravel design can use a provider-specific verifier:

$verifiedEvent = $this->webhookVerifier->verify(
    provider: $provider,
    payload: $request->getContent(),
    headers: $request->headers->all(),
);

Here, webhookVerifier is an application-owned adapter, not a built-in Laravel class.

After successful verification, persist the event.

try {
    DB::transaction(function () use ($provider, $verifiedEvent) {
        $event = WebhookEvent::create([
            'provider' => $provider,
            'event_id' => $verifiedEvent->id,
            'event_type' => $verifiedEvent->type,
            'payload' => $verifiedEvent->payload,
            'received_at' => now(),
        ]);

        ProcessWebhookEvent::dispatch($event->id)
            ->afterCommit();
    });
} catch (UniqueConstraintViolationException $exception) {
    $alreadyReceived = WebhookEvent::query()
        ->where('provider', $provider)
        ->where('event_id', $verifiedEvent->id)
        ->exists();

    if (! $alreadyReceived) {
        throw $exception;
    }
}

return response()->noContent();

The duplicate check relies on the database constraint, not a preceding exists() check. That matters because two requests can pass an existence check simultaneously.

The afterCommit() method ensures that the queued job is dispatched after the database transaction commits. Otherwise, a worker could attempt to process an event before its database record is visible.

One additional safeguard is necessary: the inbox must have a recovery mechanism.

If the database transaction commits but queue dispatch fails, the event still exists. A scheduled recovery process should find unprocessed events that were never successfully dispatched and enqueue them again.

The inbox remains the source of truth, not the queue.

4. Make the Processing Job Idempotent

Preventing duplicate event records is only the first layer.

The processing job must also protect against duplicate execution.

For example:

class ProcessWebhookEvent implements ShouldQueue
{
    public function __construct(
        public int $eventId
    ) {}

    public function handle(WebhookProcessor $processor): void
    {
        DB::transaction(function () use ($processor) {
            $event = WebhookEvent::query()
                ->lockForUpdate()
                ->findOrFail($this->eventId);

            if ($event->processed_at !== null) {
                return;
            }

            $processor->applyDatabaseChanges($event);

            $event->update([
                'processed_at' => now(),
            ]);
        });
    }
}

The row lock prevents concurrent workers from processing the same event simultaneously.

The processor should perform database changes inside this transaction. External API calls, emails, and other irreversible side effects should be handled separately through an outbox or another reliable post-commit mechanism.

There is another important distinction:

Event-level idempotency is not the same as business-level idempotency.

Imagine two different events referring to the same payment.

They may have different event IDs, but both could attempt to grant the same subscription entitlement.

The application should also enforce uniqueness around important business operations.

For example:

Webhook Event ID
       |
       v
Payment Object ID
       |
       v
Unique Business Operation
       |
       v
Update Subscription State

Instead of incrementing a balance every time a payment event arrives, record the payment against a unique provider payment ID and apply the corresponding state transition once.

5. Never Assume Events Arrive in Order

Duplicate protection does not solve event ordering.

Consider these events:

Event A: Payment Pending
Event B: Payment Successful
Event C: Payment Refunded

The application might receive them in this order:

Payment Successful
Payment Refunded
Payment Pending

If the last event blindly overwrites the order status, the application could incorrectly mark a refunded order as pending.

A better approach is to design explicit state transitions.

Possible strategies include:

  • Fetch the latest resource state from the provider.
  • Use provider-supported object versions or sequence numbers.
  • Reject invalid backward state transitions.
  • Apply domain-specific transition rules.
  • Keep an audit trail of received events.

Do not assume timestamps alone can establish reliable ordering.

Stripe specifically documents that event delivery order is not guaranteed.

6. Keep Webhook Endpoints Lightweight

Webhook endpoints should not perform expensive business operations synchronously.

For example, avoid doing all of these inside one HTTP request:

  • Generating invoices.
  • Sending multiple emails.
  • Updating several external systems.
  • Generating large reports.
  • Performing complex subscription calculations.

Instead:

  1. Verify the request.
  2. Persist the event.
  3. Queue processing.
  4. Return a successful response.

Remember that Laravel's sync queue driver executes jobs in the current process. A real asynchronous queue driver is needed when the intention is to separate processing from the webhook request.

7. Test Failure Scenarios, Not Just Successful Requests

A webhook test that sends one valid event and expects HTTP 200 is not sufficient.

A useful test suite should cover several scenarios.

Scenario Expected behavior
Valid new event Persist and process
Same event received twice One inbox record
Two simultaneous deliveries One unique event record
Invalid signature Reject request
Queue dispatch failure Event remains recoverable
Worker crashes Event can be retried
Duplicate job execution No duplicate business operation
Out-of-order events No invalid state regression
Provider replay Existing event handled safely

The goal is not simply to verify that the endpoint responds correctly.

The goal is to verify that repeated deliveries, failures, and concurrency cannot corrupt business state.

8. The Bigger Architectural Lesson

External integrations should be treated as unreliable communication channels.

Even when a provider has a well-documented webhook system, your application cannot assume perfect delivery behavior.

A durable inbox gives the application:

  • A persistent record of incoming events.
  • Database-enforced duplicate protection.
  • A recoverable processing pipeline.
  • Better separation between HTTP handling and business logic.
  • A foundation for auditing and troubleshooting.

The most important principle is this:

A webhook acknowledgment should mean the event was safely received, not that every downstream business operation has already completed.

Once that distinction is reflected in the architecture, integrations become much easier to reason about, test, and recover.


References


AI Disclosure: This article was generated primarily by an AI writing system. The technical examples should be reviewed and verified against the specific payment provider and application before publication.

來源:DEV Community · dev.to