Skip to content
9 min read—views—reactions
Integrations and APIs

What is webhook in simple words and how not to lose events

Что такое webhook и как работать с событиями без потерь: подписи, повторы, идемпотентность, очереди, логи и защита от дублей.

On this page
What is webhook in simple words and how not to lose events cover

When you’re just starting out with integrations, webhook often seems like something complicated and unreliable. Events come, then duplicate, then suddenly disappear without a trace, and you spend hours looking for the cause.

This article is written specifically for those who want to understand from scratch: as simple as possible, but with a working architecture that can be implemented today.

**##Short* *

  • Webhook is when an external service sends you data to the specified URL immediately after the event.
  • It replaces the constant API polling and gives an almost instantaneous response.
  • Most event losses are not due to the webhook itself, but to improper processing on your side.
  • A reliable scheme looks like this: signature verification → save in the database → instant 200 OK → processing in the queue.
  • With proper idempotence, retros and monitoring, event losses virtually disappear.

**# An example of fingers **

Simple words

Imagine you ordered a sushi delivery. Instead of calling the restaurant every five minutes and asking, “Well, have you left?” the courier calls the intercom when he arrives at your entrance.

Webhook works the same way. Once you give the service your address (URL), and when the desired event occurs, it “bells the doorbell” and transmits information.

What it looks like in a real project

  • The payment system (Stripe, YuKassa, Tinkoff) reports: “the payment has passed.”.
  • GitHub writes, “A new commit is launched.”.
  • The Telegram bot receives a message from the user.
  • The CRM system reports: “the customer left the application” or “the transaction moved to another status”.

All this comes in the form of a regular HTTP POST request with JSON data.

Dictionary of terms (without water) **

  • Webhook - Notification from an external service to your server.
  • Endpoint is the specific URL that webhooks come to.
  • **Payload is a request body, usually JSON with event information.
  • Signature – A cryptographic signature of a request to make sure it is indeed from the right service.
  • **Idempotency is a property of a system in which repeated processing of the same event does not lead to duplication of actions.
  • Retry - automatically resending an event if you have not confirmed receipt.
  • Queue (queue) - a mechanism for the background processing of heavy tasks.
  • *DLQ (Dead Letter Queueue) is a graveyard of events that cannot be processed after all attempts.
  • *Replay – the ability to manually repeat the processing of a specific event.

**# When webhook is needed and when you can do without it

Webhook is essential if:

  • The speed of the reaction (almost in real time) is important.
  • Events happen unevenly and rarely.
  • Persistent polling will be too expensive on API or traffic limits.
  • You want to build a modern event-oriented architecture.

You can do without webhook if:

  • A delay of several minutes is allowed.
  • The project is very small and there are few events.
  • The service does not support webhook (then polling is the only option).

**# Why things get lost: 7 real reasons

  1. Endpoint is unavailable during deploits, server crashes or SSL issues.
  2. Long processing right in the controller - the external service receives a timeout and considers the event not delivered.
  3. *No signature verification – Valid events are lost in the trash.
  4. **No idempotence ** - with retras there are double actions (double payment, double access).
  5. No queue - at peak load, the server does not have time to process all requests.
  6. There is no storage of raw events – when something goes wrong, you don’t even know the event has come.
  7. *Lack of DLQ and replay – Fallen events simply disappear without recovery.

# Recommended basic architecture

The correct processing of webhook is based on a clear principle:

  1. Accept a POST request at endpoint.
  2. Check the signature.
  3. Save the raw event to the database (with event id uniqueness).
  4. Return 200 OK immediately.
  5. Put the task in line.
  6. In the background (worker) perform business logic.
  7. Maintain statuses and log everything.

The main rule: HTTP-endpoint should work as fast as possible. All the hard work - only after confirmation of receipt.


# Level implementation: from simple to reliable

Level 1 - Base

What are we doing

  • Create an endpoint for webhook.
  • Checking the signature.
  • Save the full event in the webhook_events table.
  • Return 200 OK as soon as possible.

What does that mean

  • You have a full log of all the events that have come.
  • Significantly less losses due to timeouts.
  • The ability to investigate any problems in the future.

Level 2 - Working minimum

What do we add:

  • It is called Laravel Horizon + Redis.
  • Job for background processing.
  • Event statuses (received, processing, succeeded, failed).
  • Automatic Retrai (5-10 attempts with exponential backoff).

What does that mean

  • The system withstands load peaks.
  • Errors do not kill the handling of other events.
  • Repeated attempts occur automatically.

Level 3 – Reliable production

What do we add:

  • Dead Letter Queueue for troubled events.
  • Replay function (re-processing from adminka).
  • Full monitoring and alerts.
  • Advanced idempotence at the level of business entities.

What does that mean

  • Nearly zero losses.
  • Quick recovery after failures.
  • Full system surveillance.

# Specific example: Laravel 12

Here is the minimum, but already reliable implementation:

php
// routes/web.php
Route::post('/webhooks/stripe', [WebhookController::class, 'handleStripe']);

// app/Http/Controllers/WebhookController.php
public function handleStripe(Request $request)
{
    $payload = $request->getContent();
    $signature = $request->header('Stripe-Signature');

    if (!$this->verifySignature($payload, $signature)) {
        return response('Invalid signature', 401);
    }

    $event = json_decode($payload, true);
    $eventId = $event['id'] ?? null;

    if (!$eventId) {
        return response('Missing event id', 400);
    }

    // Сохраняем сырое событие (идемпотентно)
    WebhookEvent::updateOrCreate(
        ['provider' => 'stripe', 'event_id' => $eventId],
        [
            'type' => $event['type'],
            'payload' => $event,
            'status' => 'received'
        ]
    );

    // Отправляем в очередь
    ProcessWebhookJob::dispatch($eventId, 'stripe');

    return response('OK', 200);
}
php
// app/Jobs/ProcessWebhookJob.php
public function handle()
{
    $webhookEvent = WebhookEvent::where('event_id', $this->eventId)->firstOrFail();
    
    try {
        $webhookEvent->markAsProcessing();

        // Здесь твоя бизнес-логика
        match($webhookEvent->type) {
            'invoice.paid' => $this->handleSuccessfulPayment($webhookEvent->payload),
            // другие типы событий...
        };

        $webhookEvent->markAsSucceeded();
    } catch (\Exception $e) {
        $webhookEvent->markAsFailed($e->getMessage());
        throw $e; // для ретраев Laravel
    }
}

## SQL: a table that saves from doubles

php
Schema::create('webhook_events', function (Blueprint $table) {
    $table->id();
    $table->string('provider');
    $table->string('event_id')->unique();
    $table->string('type');
    $table->json('payload');
    $table->string('status')->default('received');
    $table->text('error_message')->nullable();
    $table->timestamp('received_at')->useCurrent();
    $table->timestamp('processed_at')->nullable();
    $table->timestamps();
});

Why it matters:

  • The same webhook can come 2-5 times.
  • Without a unique index, you’ll easily make double payment, double email, or double access.

**# What tools do you really use

  • Laravel Horizon + Redis - for queues and a convenient dashboard.
  • spatie/laravel-webhook-client is a ready-made solution.
  • ngrok or Cloudflare Tunnel for local testing.
  • Laravel Telescope or Pulse for debugging.
  • Sentry/Bugsnag - bug tracking in jobs.

If the project is small, Redis + one worker + simple logs is enough.


**# What you need to monitor* *

Minimum metrics:

  1. webhook_received_totalXX
  2. webhook_failed_totalXX
  3. webhook_processing_latency_msXX
  4. queue_depthXX
  5. dlq_countXX

Minimum allerts:

  • wKVTXNTOKEN0X
  • turn grows too fast
  • endpoint gives 5xxx above the threshold

# Typical errors

  1. Do all the logic right at the endpoint Correction: Endpoint only accepts and confirms, processing - in the background.
    • Ignoring the signature** Correction: Without a signature, you cannot trust an event.
  2. No idempotency Fix: provider + event_id should be unique.
  3. No retry and DLQ Correction: Repeats + separate queue for unsuccessful.
  4. No replay Correction: Make a command or "re-process" button.

# Implementation checklist

  • Endpoint for webhook

  • Verification of signature

  • Table webhook_events + unique index

  • Fast 200 after recording

  • Line and worker

  • Status of processing

  • Related policy

  • Basic Logic by event_id

  • DLQ

  • Replay

  • Metrics and alerts

  • Runbook: What to Do When You Grow Failed


## FAQ

Is Webhook difficult? ** Nope. It is difficult not to accept webhook, but to make the processing reliable.

**Why are doubles normal? ** Providers do retry if they are not sure you have accepted the event.

Is it possible without a queue? ** You can start at the start, but as the load increases, you will begin to lose events.

When do I return 200? ** After safely fixing the event, not after full processing.

**Polling is better than webhook? ** Usually not. Polling is heavier, slower and more expensive on request.


## Bottom line

Webhook is a simple mechanism that only becomes reliable with proper processing.

Formula for practice: проверка подписи → идемпотентная запись → быстрый 200 → очередь → воркер → мониторинг.

Reactions

—reactions