Webhook Delivery System Design: Stripe-Style

x32x01
  • by x32x01 ||
Webhook Delivery System Design: Stripe-Style
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.



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.
Instead of constantly polling another service for updates, your application receives notifications automatically when something changes.
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.
Non-Functional Requirements
  • 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:
ComponentResponsibility
Event ProducerGenerates events, such as a Payment Service
Event StorePersistently stores events
Message QueueSeparates event ingestion from delivery
Delivery WorkersSend HTTP requests to customer endpoints
Retry SchedulerSchedules failed deliveries
Delivery LogsRecords attempts and their results
The delivery flow:
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)
This architecture allows event creation and webhook delivery to scale independently.



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:
  1. A payment is successfully recorded in the database.
  2. The application crashes before publishing the webhook.
  3. The payment exists, but the notification is lost.
A reliable solution is the Transactional Outbox Pattern.
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.
A background publisher then reads pending Outbox records and publishes them to the message queue.
Code:
Database Transaction
|
+---- Payment Record
|
+---- Outbox Event
|
v
Background Publisher
|
v
Message Queue
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.



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:
AttemptRetry Delay
1Immediately
22 seconds
38 seconds
430 seconds
52 minutes
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:
  • Maximum retry attempts.
  • Maximum retry duration.
  • HTTP request timeout.
  • Per-customer rate limits.
  • Which HTTP responses are retryable.
For example, network errors, timeouts, and server errors generally deserve retries. A permanent client error such as an invalid endpoint usually requires investigation rather than repeated attempts. HTTP 429 should respect the server's rate-limit instructions when available.



6. Preventing Duplicate Events with Idempotency​

Duplicate delivery is one of the biggest challenges in webhook systems.
Consider this scenario:
  1. The webhook reaches the customer's server.
  2. The server successfully processes the payment.
  3. The response gets lost because of a network timeout.
  4. The provider assumes delivery failed and sends the same event again.
Now the customer might receive the same payment notification twice.
This could cause:
  • 💰 Credits to be added twice.
  • 📦 An order to be processed twice.
  • 📧 Duplicate emails.
  • 💳 A refund to be issued twice.
Most reliable webhook platforms use At-Least-Once Delivery.
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_123
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.



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:
  1. Subscription Created.
  2. Subscription Cancelled.
Due to delivery delays, the cancellation event arrives first. An older creation event arrives afterward.
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.
Another useful approach is treating events as notifications that something changed, then retrieving the current object state through the source API.



8. Database Design​

A basic webhook platform can start with four main tables.
Events
ColumnPurpose
idUnique event ID
event_typeEvent category
payloadEvent data
created_atCreation timestamp
WebhookEndpoints
ColumnPurpose
idEndpoint ID
customer_idEndpoint owner
urlDestination URL
secretSigning secret reference
statusActive or disabled
Deliveries
ColumnPurpose
idDelivery ID
event_idAssociated event
endpoint_idDestination endpoint
statusCurrent delivery status
attempt_countNumber of attempts
next_retry_atScheduled retry
last_response_codeLast HTTP status
DeliveryAttempts
ColumnPurpose
idAttempt ID
delivery_idAssociated delivery
attempted_atAttempt timestamp
response_codeHTTP response
response_bodyLimited response details
duration_msRequest duration
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.



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.
SSRF protection is particularly important because customers can register destination URLs. Validate DNS resolution and IP addresses when registering and connecting, and revalidate redirects to prevent requests from reaching internal services.



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.
These metrics help identify problems before they affect a large number of customers.



11. Key Design Trade-offs​

DecisionBenefitTrade-off
At-Least-Once DeliveryReduces event lossAllows duplicates
Transactional OutboxPrevents lost events between database and queueAdds complexity
Exponential BackoffReduces pressure during outagesIncreases delivery time
Distributed WorkersEnables horizontal scalingRequires queue and worker management
Manual RedeliveryHelps recover failed deliveriesCan 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.
The key principle is simple:
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.
 
Similar threads
x32x01
Replies
0
Views
150
x32x01
x32x01
x32x01
Replies
0
Views
240
x32x01
x32x01
x32x01
Replies
0
Views
137
x32x01
x32x01
x32x01
Replies
0
Views
175
x32x01
x32x01
x32x01
Replies
0
Views
188
x32x01
x32x01
Register & Login Faster
Forgot your password?
Forum Statistics
Threads
1,254
Messages
1,262
Members
20
Latest Member
cositaricagerra
Back
Top