- by x32x01 ||
What happens when a customer pays successfully, but your backend still shows the order as Pending?
The payment provider confirmed the transaction, but its webhook notification never reached your server. Even worse, the same webhook might arrive twice, arrive late, or arrive after a newer event.
A reliable webhook delivery system must handle all of these situations without losing events or triggering duplicate operations.
Let's break down how to design a scalable webhook delivery platform similar to Stripe.
Common examples include:
However, sending an HTTP request doesn't guarantee that the receiving server successfully processed it.
That's the core problem we need to solve.
Functional Requirements
The delivery flow:
This architecture allows event creation and webhook delivery to scale independently.
Imagine this scenario:
Instead of writing the payment record and publishing an event as separate operations:
Because both records are committed together, a crash after the transaction doesn't destroy the event.
The publisher must also track successfully published records so that it can safely recover after failures.
Should it retry immediately?
Usually, no. Repeated requests can overwhelm an endpoint that's already struggling.
A better approach is Exponential Backoff with Jitter.
For example:
These are illustrative values, not a universal retry schedule.
Jitter adds a small random delay to prevent thousands of failed requests from retrying simultaneously.
The retry policy should also define:
Consider this scenario:
This could cause:
This means the system retries until delivery is acknowledged or the retry policy is exhausted. Duplicate deliveries are possible.
The solution is Idempotency.
Every event should have a unique ID, such as:
The receiving application stores processed event IDs and checks them before performing operations.
If the same event arrives again, the application recognizes it and avoids repeating its side effects.
Important: Recording the event ID and applying the business operation must be atomic, or the application must use a durable processing mechanism. Otherwise, a crash between those steps can cause lost or duplicated work.
Imagine these subscription events:
If the application blindly applies events in arrival order, it might incorrectly reactivate the subscription.
Several strategies can help:
Events
WebhookEndpoints
Deliveries
DeliveryAttempts
Why separate Events from Deliveries?
Because one event might need to be delivered to multiple endpoints, and each endpoint must have its own delivery status and retry schedule.
The most important mechanism is HMAC Signature Verification.
The sender uses a shared secret to generate a signature for the request body. The receiver independently calculates the signature and compares the results.
A secure implementation should also:
Backpressure
If a customer endpoint cannot handle incoming traffic, reduce its delivery rate instead of overwhelming its server.
Queue Partitioning
Distribute events across queue partitions using a key such as Customer ID or Endpoint ID.
Dead Letter Queue (DLQ)
Move deliveries that have exhausted their retry policy into a failed state for investigation and manual redelivery.
Observability
Track important metrics:
A reliable system must assume that:
Design for retries, not perfect delivery.
In distributed systems, success isn't about delivering a message exactly once. It's about recovering from failures without losing important events or repeating dangerous operations.
The payment provider confirmed the transaction, but its webhook notification never reached your server. Even worse, the same webhook might arrive twice, arrive late, or arrive after a newer event.
A reliable webhook delivery system must handle all of these situations without losing events or triggering duplicate operations.
Let's break down how to design a scalable webhook delivery platform similar to Stripe.
1. Understanding the Problem
A Webhook is an HTTP request sent from one system to another when a specific event occurs.Common examples include:
- 💳 Payment succeeded.
- 📦 Order shipped.
- 👤 User subscribed.
- ❌ Subscription canceled.
- 🔀 GitHub pull request created.
However, sending an HTTP request doesn't guarantee that the receiving server successfully processed it.
That's the core problem we need to solve.
2. System Requirements
Before designing the architecture, let's define what the platform must support.Functional Requirements
- Receive events from different producers.
- Deliver events to registered customer endpoints.
- Retry failed deliveries automatically.
- Support manual redelivery.
- Record every delivery attempt.
- Verify webhook signatures.
- High availability and scalability.
- At-least-once delivery.
- Low delivery latency.
- No silent event loss.
- Protection against duplicate processing.
- Secure communication.
3. High-Level Architecture
A scalable webhook platform needs several independent components:| Component | Responsibility |
|---|---|
| Event Producer | Generates events, such as a Payment Service |
| Event Store | Persistently stores events |
| Message Queue | Separates event ingestion from delivery |
| Delivery Workers | Send HTTP requests to customer endpoints |
| Retry Scheduler | Schedules failed deliveries |
| Delivery Logs | Records attempts and their results |
Code:
Payment Service
|
v
Event Created
|
v
Event Store
|
v
Message Queue
|
v
Delivery Worker
|
v
Customer Endpoint
|
v
Success / Failure
|
v
Retry Scheduler (if needed) 4. Preventing Event Loss with Transactional Outbox
One of the most important design decisions is ensuring that an event is never lost between a database transaction and message delivery.Imagine this scenario:
- A payment is successfully recorded in the database.
- The application crashes before publishing the webhook.
- The payment exists, but the notification is lost.
Instead of writing the payment record and publishing an event as separate operations:
- Save the payment record.
- Insert the corresponding event into an Outbox table.
- Commit both operations in the same database transaction.
Code:
Database Transaction
|
+---- Payment Record
|
+---- Outbox Event
|
v
Background Publisher
|
v
Message Queue The publisher must also track successfully published records so that it can safely recover after failures.
5. Handling Failed Deliveries and Retries
What happens when a delivery worker sends a webhook and receives: 500 Internal Server Error ?Should it retry immediately?
Usually, no. Repeated requests can overwhelm an endpoint that's already struggling.
A better approach is Exponential Backoff with Jitter.
For example:
| Attempt | Retry Delay |
|---|---|
| 1 | Immediately |
| 2 | 2 seconds |
| 3 | 8 seconds |
| 4 | 30 seconds |
| 5 | 2 minutes |
Jitter adds a small random delay to prevent thousands of failed requests from retrying simultaneously.
The retry policy should also define:
- Maximum retry attempts.
- Maximum retry duration.
- HTTP request timeout.
- Per-customer rate limits.
- Which HTTP responses are retryable.
6. Preventing Duplicate Events with Idempotency
Duplicate delivery is one of the biggest challenges in webhook systems.Consider this scenario:
- The webhook reaches the customer's server.
- The server successfully processes the payment.
- The response gets lost because of a network timeout.
- The provider assumes delivery failed and sends the same event again.
This could cause:
- 💰 Credits to be added twice.
- 📦 An order to be processed twice.
- 📧 Duplicate emails.
- 💳 A refund to be issued twice.
This means the system retries until delivery is acknowledged or the retry policy is exhausted. Duplicate deliveries are possible.
The solution is Idempotency.
Every event should have a unique ID, such as:
evt_123The receiving application stores processed event IDs and checks them before performing operations.
If the same event arrives again, the application recognizes it and avoids repeating its side effects.
Important: Recording the event ID and applying the business operation must be atomic, or the application must use a durable processing mechanism. Otherwise, a crash between those steps can cause lost or duplicated work.
7. Handling Events That Arrive Out of Order
Message queues and retries don't always guarantee that events reach their destinations in the original order.Imagine these subscription events:
- Subscription Created.
- Subscription Cancelled.
If the application blindly applies events in arrival order, it might incorrectly reactivate the subscription.
Several strategies can help:
- Object Versioning: Attach a version number to each entity and reject outdated updates.
- Per-Entity Processing: Process events for the same entity in a controlled order.
- Reconciliation: Fetch the latest state from the original service when necessary.
8. Database Design
A basic webhook platform can start with four main tables.Events
| Column | Purpose |
|---|---|
| id | Unique event ID |
| event_type | Event category |
| payload | Event data |
| created_at | Creation timestamp |
| Column | Purpose |
|---|---|
| id | Endpoint ID |
| customer_id | Endpoint owner |
| url | Destination URL |
| secret | Signing secret reference |
| status | Active or disabled |
| Column | Purpose |
|---|---|
| id | Delivery ID |
| event_id | Associated event |
| endpoint_id | Destination endpoint |
| status | Current delivery status |
| attempt_count | Number of attempts |
| next_retry_at | Scheduled retry |
| last_response_code | Last HTTP status |
| Column | Purpose |
|---|---|
| id | Attempt ID |
| delivery_id | Associated delivery |
| attempted_at | Attempt timestamp |
| response_code | HTTP response |
| response_body | Limited response details |
| duration_ms | Request duration |
Because one event might need to be delivered to multiple endpoints, and each endpoint must have its own delivery status and retry schedule.
9. Webhook Security
How do we prevent attackers from sending fake payment notifications?The most important mechanism is HMAC Signature Verification.
The sender uses a shared secret to generate a signature for the request body. The receiver independently calculates the signature and compares the results.
A secure implementation should also:
- 🔒 Require HTTPS.
- Verify signatures against the original request body.
- Use constant-time signature comparison.
- Include timestamps to reduce replay attacks.
- Reject requests outside an acceptable timestamp window.
- Protect endpoint registration against SSRF.
- Block private, loopback, and internal IP addresses.
10. Scaling to Millions of Deliveries
When the platform handles millions of webhook deliveries, several additional challenges appear.Backpressure
If a customer endpoint cannot handle incoming traffic, reduce its delivery rate instead of overwhelming its server.
Queue Partitioning
Distribute events across queue partitions using a key such as Customer ID or Endpoint ID.
Dead Letter Queue (DLQ)
Move deliveries that have exhausted their retry policy into a failed state for investigation and manual redelivery.
Observability
Track important metrics:
- Delivery success rate.
- Retry rate.
- Queue lag.
- Delivery latency.
- Failed endpoints.
- Pending deliveries.
- Events awaiting processing.
11. Key Design Trade-offs
| Decision | Benefit | Trade-off |
|---|---|---|
| At-Least-Once Delivery | Reduces event loss | Allows duplicates |
| Transactional Outbox | Prevents lost events between database and queue | Adds complexity |
| Exponential Backoff | Reduces pressure during outages | Increases delivery time |
| Distributed Workers | Enables horizontal scaling | Requires queue and worker management |
| Manual Redelivery | Helps recover failed deliveries | Can trigger duplicate processing |
Frequently Asked Questions
-----------------What is the difference between At-Least-Once and Exactly-Once Delivery?
At-Least-Once allows duplicate deliveries to avoid silently losing events. Exactly-Once processing is much harder to guarantee across distributed systems. In practice, systems combine reliable delivery with idempotent processing.Why do webhook systems need a message queue?
A message queue separates event creation from HTTP delivery. This allows workers to process events asynchronously, scale independently, and recover from temporary failures.Should webhook endpoints return a response immediately?
Yes. Customer endpoints should verify the request, persist the event or enqueue it for processing, and return a successful HTTP response quickly. Expensive business operations should generally happen asynchronously.What happens when all retry attempts fail?
The delivery should enter a permanent failed state, remain available for investigation, and support manual redelivery when the underlying problem is fixed.Final Thoughts
The hardest part of designing a webhook delivery platform isn't sending an HTTP request. It's handling everything that can go wrong after that request is sent.A reliable system must assume that:
- Requests can fail.
- Events can be delivered more than once.
- Events can arrive out of order.
- Customer endpoints can remain unavailable for hours.
- Network failures can happen at any point.
Design for retries, not perfect delivery.
In distributed systems, success isn't about delivering a message exactly once. It's about recovering from failures without losing important events or repeating dangerous operations.