InterviewDryRun
Lesson 25 · 23 min video · free

Design Webhook Delivery

A platform tells its customers' servers when something happens, an order paid, a file uploaded, by sending an HTTP request called a webhook. This lesson designs delivery that customers can trust: events captured with an outbox so none are lost, a durable queue, workers that retry with backoff for days, ordering where it matters, isolation so one slow endpoint cannot delay everyone else, signed payloads, and a log customers can search and replay.

What you will learn

  • Capture events in the same transaction as the business change (an outbox), so no event is ever lost.
  • Delivery is at least once: sign every payload, give it a unique event id, and tell customers to deduplicate.
  • Retry failures with exponential backoff and jitter for about three days, then park the event for manual replay.
  • Isolate endpoints: per-endpoint queues or concurrency limits, so one slow customer never delays the rest.
  • Ordering is per resource at best; offer sequence numbers, or a thin event that customers re-fetch.
  • Customers need a delivery log with every attempt, its status and response, and a replay button.

In this lesson

  1. The question
  2. Step 1: Clarify the requirements
  3. Step 2: Back-of-the-envelope estimates
  4. Step 3: The API and the payload
  5. Step 4: The data model
  6. Step 5: Capturing events without losing any
  7. Step 6: Fan-out and delivery workers
  8. Step 7: Retries and backoff
  9. Step 8: Isolating slow and failing endpoints
  10. Step 9: Ordering
  11. Step 10: Security
  12. Step 11: Customer-visible logs and replay
  13. Step 12: One event, end to end
  14. Step 13: Scaling and failures
  15. Step 14: The parts people forget
  16. Step 15: The follow-up questions
  17. Recap
Practice this question with Max

The question

Welcome to lesson twenty-five of the InterviewDryRun system design course. Today we design webhook delivery: the system a platform uses to tell its customers' servers that something happened. A payment succeeded. A file finished uploading. A subscription was cancelled.

A webhook is just an HTTP request that we send to a web address the customer gave us. That sounds trivial, and the first version of every webhook system is a few lines of code that make the request right after the event. Then reality arrives. Customers' servers go down for hours. Some answer in thirty seconds instead of thirty milliseconds. Events arrive out of order. Someone registers an address that points inside our own network. And every customer eventually writes in to ask, did you send it? This question is about building delivery that survives all of that.

Max asks

“Design reliable webhook delivery with retries, ordering and customer-visible logs.”

That is how Max, our AI interviewer, asks it. Three words to underline: retries, ordering and logs. Retries means we must keep trying when the customer is down, without hammering them. Ordering is the trap: true ordering and reliable retries pull against each other, and the interviewer wants to see you notice. And logs means customers must be able to see, for every event, what we sent, when, and what their server answered.

The plan: requirements and numbers, then the API and the data model. Then the pipeline: capturing events without losing any, queueing them, and the delivery workers. Then the deep dives: retries and backoff, isolating slow endpoints, ordering, and security. Then the delivery log, one event walked end to end, scaling, failures, and the follow-up questions.

Step 1: Clarify the requirements

Functional requirements
  1. 01
    SubscribeCustomer registers a URL and the event types they want
  2. 02
    DeliverPOST a JSON payload for each matching event
  3. 03
    RetryKeep trying when the endpoint fails or times out
  4. 04
    LogsEvery attempt visible: request, response, timing
  5. 05
    ReplayResend one event, or everything since a time

Start with questions.

Customers register an endpoint, a web address on their server, and choose which event types they want: payment succeeded, refund created, and so on. A customer may have several endpoints, for example one for production and one for testing.

When an event happens, we send an HTTP POST with a JSON payload to every endpoint subscribed to that type. A two-hundred response means delivered. Anything else, or no answer within a timeout, means try again later.

Customers can see every delivery attempt in a dashboard, and they can replay: resend a single event, or every event since their server went down. Ask whether customers also want to pull events through an API. Often yes, as a backup, and we will come back to it in the follow-ups.

Non-functional requirements
  1. 01
    Never lose an eventOnce it happened, it will be delivered or visibly parked
  2. 02
    At least onceDuplicates possible; exactly once is not
  3. 03
    Fast when healthyDelivered within seconds
  4. 04
    IsolationOne bad endpoint cannot slow others
  5. 05
    SafeSigned payloads; never call our own network

The qualities.

Durability first: if an event happened, the customer will get it, or we will show clearly that we gave up after many days of trying. And be honest about the delivery guarantee: at least once. We can never know for sure whether a request that timed out was processed, so we may deliver twice. Exactly once delivery over HTTP to someone else's server is not possible; say that plainly, and design for duplicates.

Healthy endpoints should get events within a second or two. One customer's broken server must not delay anyone else's events. And security: customers must be able to verify that a request really came from us, and we must never be tricked into calling our own internal services.

Step 2: Back-of-the-envelope estimates

Sizing it
Events per day500 millionabout 6,000 a second average
Peak30,000 / send of month, sales
Endpoints1 millionacross 300,000 customers
Failing at any timeabout 5%each failure means retries
Payloadabout 2 KBplus headers and response

Let us size it.

Say five hundred million events a day, about six thousand a second on average and perhaps thirty thousand at peak. Each event may go to more than one endpoint, so deliveries can be somewhat higher than events.

A million endpoints, and at any moment perhaps five percent of them are failing: down for maintenance, misconfigured, or slow. That five percent matters more than the average, because failures turn one delivery into many attempts, and slow endpoints tie up workers.

Payloads are about two kilobytes. We keep the request and a trimmed copy of the response for every attempt, for the logs, so a few kilobytes per attempt, about two terabytes a day of logs. Keep detailed logs for thirty days, which is about sixty terabytes, cheap in a column store or object storage.

And workers. If a healthy delivery takes two hundred milliseconds, one worker connection handles five a second, so thirty thousand a second needs around six thousand concurrent requests in flight. With asynchronous input and output, a single server can hold thousands of open requests, so that is a small fleet. But a slow endpoint that takes the full timeout of ten seconds holds a connection fifty times longer than a healthy one. That number is why isolation will be a whole step.

Step 3: The API and the payload

API
POST   /v1/webhook_endpoints   { url, events: ["payment.succeeded"] }
       → { id: we_123, secret: whsec_… }
GET    /v1/webhook_endpoints/{id}/deliveries?status=failed
POST   /v1/events/{eventId}/redeliver   { endpointId }

we → customer:  POST https://customer.example/hooks
  Webhook-Id: evt_789      Webhook-Timestamp: 1793350000
  Webhook-Signature: v1=hmac_sha256(secret, id.timestamp.body)
  { id: evt_789, type: payment.succeeded, created, data: {…} }

Two sides: the customer manages endpoints with our API, and our system calls the customer's endpoint.

Creating an endpoint returns a signing secret, shown to the customer once. Customers can list deliveries, filtered by status, and ask to redeliver an event.

Every request we send carries the event id, a timestamp, and a signature: a keyed hash of the id, the timestamp and the body, computed with the endpoint's secret. The customer recomputes the hash with their copy of the secret, and if it matches, the request came from us and was not altered. The timestamp lets them reject old requests replayed by an attacker, say anything older than five minutes.

The event id is how customers handle duplicates. Since we deliver at least once, we tell customers in the documentation: store the ids you have processed, and ignore one you have seen. Putting the deduplication tool in the customer's hands is the honest version of exactly once.

Step 4: The data model

Tables
TableKeyColumns
endpointendpointIdcustomer, url, event types, secret, state
eventeventIdcustomer, type, payload, created
deliveryeventId, endpointIdstatus, attempts, next attempt at
attempt (log)deliveryId, ntime, request, status code, latency, response

Four kinds of data.

Endpoints hold the customer, the address, the subscribed event types, the secret, and a state: enabled, or disabled after failing for days. Endpoint data is small and read on every delivery, so cache it in the workers.

Events are immutable: an id, a type, a payload, a creation time. A delivery is one event going to one endpoint, with a status, pending, delivered or failed, the number of attempts, and when the next attempt is due.

Attempts are the log: one row per HTTP request we made, with the time, the response code, the latency, and the first few kilobytes of the response body. This is append-only and the largest table by far, so it lives in a store built for append-heavy, time-ordered data, partitioned by day, and dropped after the retention period.

Separating delivery state, which changes, from attempts, which are only appended, is a small decision that matters. The delivery row is updated a handful of times. The attempt log grows forever and is queried by customers. Different access patterns, different stores.

Step 5: Capturing events without losing any

From a business change to the queue
one transactionpublishSERVICEPayments serviceSTOREPayments DBpayment + outbox rowWORKEROutbox relayreads new rowsQUEUEEvent logpartitioned

Let us start where events are born. The payments service marks a payment as succeeded in its database. Now it needs to emit the event.

The naive way is to commit the payment and then send the event to a queue. But if the service crashes between those two steps, the payment is recorded and the event is lost forever. Or the other order: the event is sent, then the database commit fails, and the customer is told about a payment that never happened. Both are real bugs that real systems ship.

The fix is the transactional outbox. In the same database transaction that records the payment, the service inserts a row into an outbox table: the event to publish. The two writes commit together or not at all.

A relay process reads new outbox rows, either by polling or by following the database's change stream, publishes each to the event log, and marks the row as sent. If the relay crashes after publishing but before marking, it publishes the row again, which is a duplicate, and duplicates are already part of our contract. Nothing is ever lost.

The outbox pattern is the single most useful sentence in this interview, because it closes the gap that every other part of the design depends on. If an event can be lost before it reaches the webhook system, no amount of retrying later can save it.

Step 6: Fan-out and delivery workers

The delivery pipeline
POSTfailedwhen dueQUEUEEvent logSERVICEFan-outmatch endpointsQUEUEDelivery queuesby endpointWORKERDelivery workersasync HTTPCLIENTCustomer serversSTOREAttempt logWORKERRetry schedulerdue times

Now the webhook system itself.

A fan-out service reads the event log. For each event, it looks up which endpoints of that customer subscribe to the event's type, and creates a delivery for each: one row in the delivery table and one message on a delivery queue.

Delivery workers take messages from the queues and make the HTTP request, with a timeout of, say, ten seconds. They use asynchronous input and output, so one worker process has thousands of requests in flight at once rather than one thread per request.

Every attempt, success or failure, is appended to the attempt log. On a two-hundred response, the delivery is marked delivered. On anything else, the worker hands the delivery to the retry scheduler with the time of the next attempt, and moves on immediately. A worker never sleeps waiting to retry.

The retry scheduler holds deliveries waiting for their next attempt, ordered by due time, and puts each back on the delivery queue when it is due. It can be a table indexed by next attempt time, polled every second, or a queue with delayed delivery. Either way, the delay lives in durable data, not in memory.

Step 7: Retries and backoff

A retry schedule
AttemptWait before itTime since event
1immediately0
2about 30 s30 s
3about 5 min6 min
4about 30 min40 min
5about 2 h3 h
6 to 15about 6 h eachup to 3 days, then parked

How often should we retry? Too fast, and we hammer a server that is struggling, which makes its recovery harder. Too slow, and a short blip delays events for hours.

The standard answer is exponential backoff: each wait is several times longer than the last. A schedule like thirty seconds, five minutes, thirty minutes, two hours, then every six hours, covers both a ten-second blip and a weekend outage, with about fifteen attempts over three days.

Add jitter: randomise each wait by, say, plus or minus twenty percent. Why? When a big customer's server comes back after an hour, it may have a hundred thousand events waiting. Without jitter, they would all retry at the same instant and knock it over again. Jitter spreads them out.

Not every failure deserves a retry. A timeout, a connection error, or a five-hundred-series response is temporary: retry. A four-ten, gone, means the customer removed this endpoint: stop. Most four-hundred responses usually mean a bug on their side that retrying will not fix soon, but they might deploy a fix, so keep retrying on the slow schedule. Respect a retry-after header if they send one.

After the last attempt, park the delivery as failed. It stays visible in the dashboard, with a replay button, and we email the customer. If an endpoint has failed every delivery for several days, disable it and tell them, so we stop spending effort on an address nobody is listening to.

Step 8: Isolating slow and failing endpoints

Noisy neighbours
  1. 01
    The problemSlow endpoints hold workers; everyone's events wait
  2. 02
    Per-endpoint limitAt most N requests in flight per endpoint
  3. 03
    Separate lanesHealthy, slow and failing endpoints on different queues
  4. 04
    Circuit breakerEndpoint failing fast? Pause it, probe, then resume

This is the deep dive that separates strong answers. Imagine one large customer whose server starts taking ten seconds to time out on every request, and who receives a fifth of all our events.

With one shared queue, workers fill up with requests waiting on that slow server. Healthy customers' events queue behind them, and their delivery time goes from one second to minutes. One customer's problem has become everyone's problem.

First defence: a concurrency limit per endpoint. No endpoint may have more than, say, twenty requests in flight. Extra deliveries for that endpoint wait in its own backlog. The slow customer is slowed down, but only they are.

Second: lanes. Track each endpoint's recent success rate and latency. Healthy endpoints go through the fast lane. Endpoints that are slow or failing are moved to a separate lane with its own workers. The slow lane can back up for hours without touching the fast lane. When an endpoint recovers, it moves back.

Third: a circuit breaker per endpoint. If the last fifty attempts all failed, stop sending for a while, and send only an occasional probe. When a probe succeeds, resume, slowly at first. This protects the customer's struggling server, and saves our workers from requests we know will fail. Together these three ideas make delivery fair: each endpoint gets service according to its own health, not according to its neighbours'.

Step 9: Ordering

Ordering options
  1. 01
    No orderingSimplest; parallel; retries never block
  2. 02
    Per-resource orderOne in flight per resource; a failure blocks that resource
  3. 03
    Sequence numbersDeliver freely; customer ignores older versions
  4. 04
    Thin events'Order 42 changed', customer fetches the latest

Now the trap in the question. Customers often assume events arrive in order: created, then updated, then deleted. Can we promise that?

Strict ordering conflicts with retries. If event one fails and we hold back event two until event one succeeds, then one failure blocks everything after it, possibly for days. And strict ordering across all of a customer's events means sending one at a time, which caps throughput at one request per round trip.

The middle ground is ordering per resource: all events about order forty-two go through the same queue partition, one at a time, while events about other orders flow in parallel. A failure blocks only that one order's events. Partition the delivery queue by endpoint and resource id to get this.

But the more robust answer is to make order not matter. Put a version or sequence number on each resource's events, so the customer can ignore an update older than one they have already applied. Or send thin events: just order forty-two changed, and the customer calls our API to fetch the current state. A thin event is always safe to process late, twice, or out of order, because it always leads to the latest truth.

The answer I would give: we do not guarantee global order. We include a creation time and a per-resource sequence number in every event, we recommend customers fetch the current state for anything order-sensitive, and we offer per-resource ordering as an option for customers who need it, with the trade-off that a failure blocks that resource's later events. Explaining that trade-off is what the interviewer is listening for.

Step 10: Security

Security
  1. 01
    SignaturesHMAC with a per-endpoint secret; rotate with overlap
  2. 02
    TimestampsCustomer rejects requests older than 5 minutes
  3. 03
    SSRFCustomers choose the URL; never let it reach our network
  4. 04
    Egress proxyResolve DNS, block private ranges, fixed outbound IPs

Two security problems, one on each side.

For customers: signatures. We covered the keyed hash. Add secret rotation: when a customer rotates their secret, sign with both the old and the new one for a day, so they can deploy without dropping events. The timestamp in the signature lets them reject replays.

For us: server-side request forgery. A customer chooses the address we call. A malicious one might register an address that resolves to an internal service, like our metadata endpoint or an admin API, and use our webhook workers to reach inside our network.

So workers send all requests through an egress proxy that resolves the host name itself and refuses private, loopback and link-local addresses, and checks again after redirects, because an address can resolve to a public address at registration and a private one later. Run the workers in a network segment with no route to internal services anyway. And send from a fixed set of outbound addresses, which many customers want so they can allow us through their firewall.

Step 11: Customer-visible logs and replay

What customers see
  1. 01
    Per eventEvery attempt: time, status, latency, response snippet
  2. 02
    Per endpointSuccess rate, recent failures, current state
  3. 03
    SearchBy event id, type, status, time range
  4. 04
    ReplayOne event, or all failed since a time

The third phrase in the question: customer-visible logs. This feature cuts support tickets more than any other.

For each event, the dashboard shows every attempt: when it was made, the status code, how long it took, and the first part of the response body. A customer who sees four-oh-one with an error from their own framework knows instantly that the bug is theirs, without writing to support.

Per endpoint, show the success rate over the last hour and day, and the current state: healthy, slow, failing, or disabled. Searching by event id or type over a time range is served by the attempt log store, which is partitioned by day and indexed by customer and event id.

Replay is simple because events are immutable and stored. Replaying one event creates a new delivery for it. Replaying everything since Tuesday at ten creates deliveries for every matching event since then, which can be hundreds of thousands, so it goes through the same per-endpoint concurrency limits as normal traffic, at a gentle rate, so a replay never becomes an attack on the customer's own server. Mark replayed deliveries as such in the log.

Step 12: One event, end to end

One event, one bad afternoon
WhenWhat happens
14:00:00.000payment committed with an outbox row
14:00:00.050relay publishes evt_789 to the event log
14:00:00.080fan-out: 2 endpoints subscribe; 2 deliveries
14:00:00.300endpoint A: 200 in 180 ms; delivered
14:00:10.300endpoint B: timeout; retry at about 14:00:40
14:06 to 16:40B fails 3 more times; moved to slow lane
16:41B deploys a fix; next attempt 200; delivered

Let us follow one event through the system, including a failure.

At two o'clock, a payment succeeds. The payments service commits the payment and an outbox row in one transaction. Fifty milliseconds later the relay publishes event seven-eight-nine to the event log.

Fan-out finds two endpoints subscribed to payment succeeded for this customer, A and B, and creates two deliveries. A worker sends A's request, signed with A's secret; A answers two hundred in a hundred and eighty milliseconds. Delivered, logged.

B's server is overloaded and does not answer within ten seconds. The worker logs a timeout and hands the delivery to the retry scheduler, due in about thirty seconds, with jitter. The next three attempts fail too, at growing intervals. B's success rate drops, so B moves to the slow lane, where its failures cannot delay anyone else. The circuit breaker sends only probes.

B's engineers see the failed attempts in their dashboard, with the timeout and their own error responses, and deploy a fix. The next attempt gets a two hundred. B moves back to the fast lane, and the backlog drains within their concurrency limit. B's code checks the event id, sees it has not processed seven-eight-nine before, and records the payment. Nothing was lost, and nobody else waited.

Step 13: Scaling and failures

Scale and failure
  1. 01
    Partition by endpointQueues, workers and limits all keyed by endpoint
  2. 02
    Workers are statelessA crash re-delivers in-flight messages
  3. 03
    Retry storeDurable, indexed by due time, sharded
  4. 04
    Our own outageBacklog builds in the log; drain at a safe rate

Scaling and what breaks.

Partition delivery queues by endpoint id, so per-endpoint limits and ordering are enforced in one place. Workers are stateless and scale out freely. The event log, delivery table and retry store are all partitioned too, and grow with traffic.

If a worker crashes mid-request, its queue message was not acknowledged, so another worker picks it up and sends it again. That might be a duplicate, which is part of the contract. The retry store is durable and replicated, so a scheduled retry is never forgotten.

And if our own delivery system is down for an hour, events keep accumulating safely in the event log, because the outbox relays still publish. When delivery recovers, the backlog drains, but through the same per-endpoint limits, so customers are not flooded with an hour of events in one second. Watch the end-to-end delay, from event creation to first attempt, as the main health number.

Step 14: The parts people forget

Easy to miss
  1. 01
    Payload versionsPin each endpoint to an API version
  2. 02
    Big payloadsCap the size; send a link for the rest
  3. 03
    Test eventsA send-test button and a test mode
  4. 04
    Data retentionPayloads hold customer data; expire them

A few details that turn a solid answer into a strong one.

Versions. Payloads change shape as the product grows. Pin each endpoint to the API version that was current when it was created, and render each event in that version's shape at delivery time, so adding a field never breaks a customer's parser. Customers upgrade an endpoint when they are ready, and can test the new shape first.

Size. Some events, like a large invoice with thousands of lines, would produce huge payloads. Cap the body at, say, two hundred and fifty kilobytes, and for anything bigger send the summary with a link to fetch the full object through the API. Large bodies slow every customer's parser and fill our logs for no benefit.

Testing. Developers building their receiver need a way to trigger a sample event on demand, and a test mode whose events never mix with live ones. It is a small feature, but it is the first thing every customer uses, and asking about it shows you have thought about the people on the other end.

And retention. Payloads contain customer data, sometimes personal data. Keep full payloads only as long as replay needs them, say thirty days, keep the attempt metadata a little longer for support, and delete on schedule. Encrypt stored payloads, and never write signing secrets into any log, including ours.

Step 15: The follow-up questions

Max asks

“A customer says they never received an event. How do you investigate?”

Look up the event id in the attempt log. Either we have attempts with responses, which shows exactly what their server answered, or the delivery is still pending in retries, or it is parked as failed, or there is no delivery at all, which means their endpoint did not subscribe to that type at the time. Each case has a clear answer, and the customer can see the same information themselves, which is the point of the logs.

Max asks

“Some customers can't accept inbound requests at all. What do you offer them?”

An events API they can poll: list events since a cursor, ordered by creation time, kept for thirty days. It uses the same immutable event store. Polling also serves as a backup for webhook customers who want to reconcile, for example, a nightly job that fetches the day's events and compares them with what they processed.

Max asks

“Why not just make the HTTP call right inside the payments service, after the commit?”

Because then the payments service is tied to customers' servers: a slow customer slows payments, a crash loses the event, and retries, logs, signing and isolation would have to be built in every service that emits events. A separate delivery system, fed by an outbox, keeps the business services fast and makes delivery one shared, well-tested piece.

Max asks

“How would you deliver to an endpoint that needs events in strict order?”

Give that endpoint a single ordered partition, with one request in flight at a time. A failure blocks the queue until it succeeds or is parked, and we tell the customer that clearly, because it is the price of strict order. In practice I would also suggest sequence numbers or thin events, which give them the correctness they want without the blocking.

Recap

Your 45 minutes
  1. 01
    0 to 5: requirementsSubscribe, deliver, retry, log, replay; at least once
  2. 02
    5 to 10: estimates30,000 events/s at peak; 5% failing endpoints
  3. 03
    10 to 20: pipelineOutbox, event log, fan-out, async workers
  4. 04
    20 to 35: deep divesBackoff with jitter, isolation, ordering
  5. 05
    35 to 45: trustSignatures, SSRF, logs, replay, failures

On the clock: five minutes on requirements, with at-least-once delivery stated plainly. Five minutes of numbers, which show that the failing five percent, not the average, drives the design.

Ten minutes on the pipeline: the outbox so no event is lost, the event log, fan-out, and asynchronous workers with a durable retry scheduler.

Fifteen minutes on the deep dives: exponential backoff with jitter, isolating slow endpoints with limits, lanes and circuit breakers, and the honest answer on ordering. And ten minutes on signatures, blocking internal addresses, logs and replay. If you explain why one slow customer must never delay the others, you will stand out.

Reliability questions reward candidates who can explain trade-offs calmly, and that takes practice out loud. You can practice this exact question with Max, our AI interviewer, at interview dry run dot com. It is free to start, and you get a scored report with what to fix. The written lesson, with every diagram, is on the site too. See you in lesson twenty-six.

Now say it out loud

Watching an answer is not the same as giving one. Max asks this exact question, pushes back when an answer is vague and keeps time, then scores you per skill.

Practice with Max

Free: a 5-minute voice round and unlimited typed drills, with scored feedback. No card, and your camera is never recorded.