“Send a webhook” sounds like one line: POST the event to the customer’s URL. Then the real questions start. The customer’s server is down for six hours - do you drop the event or hold it? It returns 200 but took 40 seconds - is that a success? Two events for the same subscription fire a millisecond apart and the slow one lands second - did you just tell the customer the invoice was paid before you told them it was created? One producer event (say payment.succeeded) has 4,000 subscriptions pointing at it - do you really open 4,000 outbound connections in the same instant? And when half of those endpoints time out and you retry them all at once, do you now have a self-inflicted thundering herd that takes out your own egress fleet?

A webhook platform is not an HTTP client in a loop. It is a durable, ordered, at-least-once delivery system whose actual product is trust: the customer has to believe that if an event happened, the callback will eventually arrive, in the right order, exactly the way it would from Stripe or GitHub. The easy part (fire one POST) is trivial. The hard part - ordered per-endpoint delivery, fast detection of permanently dead targets, and fanning one event out to thousands of consumers without melting on retry spikes - is where the whole design lives. Let me build the entire thing.

Functional Requirements (FR)

In scope:

  • Register subscriptions. A customer registers an endpoint: a target URL, a set of event types they care about (invoice.paid, charge.failed, …), a signing secret, and optional filters. One customer can have many endpoints.
  • Ingest producer events. Internal services emit events (POST /events internally, or onto an event bus). Each event has a type, a payload, and an owning account.
  • Fan out one event to all matching subscriptions. A single payment.succeeded may match thousands of endpoints across accounts; every matching, active endpoint must receive a delivery.
  • Deliver reliably with retries. POST the signed payload to the endpoint. On failure (timeout, 5xx, connection refused), retry with exponential backoff and jitter over a long window (say 24-72 hours).
  • At-least-once delivery with idempotency support. We guarantee the callback is attempted until it succeeds or the window expires. We give the consumer the tools (a stable event id, a signature) to dedupe, since at-least-once means they will occasionally see a duplicate.
  • Per-endpoint ordering. Deliveries to a single endpoint should arrive in the order the events occurred, even across retries. We do not promise a global order across endpoints.
  • Dead-letter queue (DLQ). Deliveries that exhaust all retries land in a DLQ, visible to the customer, replayable on demand.
  • Automatic endpoint disabling. An endpoint that is down for a long time (e.g. fails every delivery for days) is auto-disabled and the customer is alerted, so we stop wasting attempts on a dead URL.
  • Signing and verification. Every delivery is HMAC-signed over the body plus a timestamp so the consumer can verify authenticity and reject replays.
  • Delivery log and manual replay. Customers see every attempt (status, response code, timing) and can replay any event or any failed delivery.

Explicitly out of scope (own the boundary):

  • Producing the business events themselves. We are the delivery substrate. The services that decide a payment succeeded are upstream; we consume their events.
  • The consumer’s endpoint. We do not host or run the customer’s receiver. We deliver to a URL they operate.
  • Real-time streaming (WebSocket/SSE) to browsers. This is server-to-server HTTP callbacks. A separate push/streaming system covers browser fan-out.
  • A full workflow/orchestration engine. We deliver events; we do not run multi-step sagas on the customer’s behalf.

The decision that shapes everything: the product is reliable, ordered, at-least-once delivery, and the three hardest constraints are per-endpoint ordering under retries, detecting dead endpoints fast so you do not drown in doomed attempts, and fan-out that does not thundering-herd on retry spikes. Throughput alone is easy. Those three are the design.

Non-Functional Requirements (NFR)

  • Scale: a large platform. Assume 5 million registered endpoints, 2 billion events ingested/day, and an average fan-out such that one event matches multiple subscriptions. Deliveries are the real number and dwarf events (see BoE). Peak is roughly 3x average (business-hours concentration, batch jobs), so delivery QPS peaks in the low hundreds of thousands per second.
  • Latency: this is a near-real-time system, not a hard-real-time one. Target p50 delivery latency (event ingested to first attempt) under a few seconds, p99 under ~30 seconds for healthy endpoints. Retries legitimately stretch to hours. What must be fast is ingestion acceptance: p99 under ~50ms to durably accept an event and return.
  • Availability: 99.95%+ on ingestion. Accepting an event must almost never fail; a durable log absorbs any downstream delivery problem. Delivery itself is best-effort against endpoints we do not control - failure there is expected and handled by retries, not by failing ingestion.
  • Durability: once we ack an event, it is on durable storage and will be attempted for every matching subscription until delivered or the retry window expires. Losing an accepted payment.succeeded is a real, trust-destroying failure.
  • Consistency: eventual for reporting (delivery logs can lag seconds). The one strong guarantee is at-least-once: never silently drop an accepted event. Exactly-once is not promised; we hand consumers idempotency tools instead.
  • Ordering: per-endpoint, per-ordering-key ordering. Deliveries to one endpoint for one logical stream arrive in event-time order. No global ordering across endpoints, and no ordering across unrelated keys.
  • Security: every delivery is HMAC-signed with a per-endpoint secret over timestamp + body, so consumers verify authenticity and reject replays. We never deliver to internal/private IP ranges (SSRF protection).

Back-of-the-Envelope Estimation (BoE)

Real numbers with arithmetic - they dictate the architecture.

Event ingestion:

2,000,000,000 events/day
= 2e9 / 86,400 sec
≈ 23,150 events/sec average
Peak (~3x) ≈ 70,000 events/sec

Fan-out to deliveries (the number that matters):

Most events match a handful of endpoints; a few popular event types match thousands.
Assume an average fan-out of ~5 matching subscriptions per event (long tail pulls it up).
2e9 events * 5 = 1e10 deliveries/day (first attempts)
≈ 115,000 deliveries/sec average, ~350,000/sec peak.

Retries add more outbound attempts. If ~10% of first attempts fail and average
~3 retries each before success/expiry:
extra attempts ≈ 1e10 * 0.10 * 3 = 3e9/day
Total delivery attempts ≈ 1.3e10/day ≈ 150,000/sec average, ~450,000/sec peak.

Storage - delivery attempt log (the part we keep):

Per delivery we keep a compact attempt record:
  delivery_id     16 bytes
  event_id        16
  endpoint_id     16
  status           1
  http_code        2
  attempt_no       1
  latency_ms       4
  next_attempt_at  8
  timestamps      ~16
  ----------------------
  ≈ 80 bytes, round to ~150 with indexes/overhead.
1.3e10 attempts/day * 150 bytes ≈ ~1.95 TB/day of attempt log.
Retain 30 days hot = ~58 TB online, sharded; roll older to cold storage.

Storage - event payloads:

Average payload ≈ 3 KB (JSON event body).
2e9 * 3 KB = 6 TB/day of payload.
Payloads must outlive the retry window plus replay grace: keep ~7-30 days.
6 TB/day * 30 days ≈ 180 TB, on object storage, tiered and cheap.
Deliveries reference a payload by id; we store the body once, not per fan-out copy.

In-flight queue depth (why backlog math matters):

If a major receiver (say a big customer) is down for 1 hour at peak and they take
2,000 deliveries/sec, that is 2,000 * 3,600 = 7.2M deliveries queued for ONE endpoint.
A 6-hour outage across many endpoints can mean hundreds of millions of pending
retries scheduled into the future. The scheduler must hold tens to hundreds of
millions of timers cheaply. This is why retries live in a time-indexed store,
not in RAM timers.

Bandwidth:

Outbound delivery egress: 1.3e10 attempts * ~3 KB ≈ 39 TB/day
≈ 39e12 * 8 / 86,400 ≈ ~3.6 Gbps average, ~11 Gbps peak.
Plus TLS handshakes: connection reuse per endpoint is essential to cut this.

Subscription lookup cache:

5e6 endpoints. The hot index is (account, event_type) -> list of endpoint_ids.
Average metadata per endpoint ~500 bytes = 5e6 * 500 ≈ 2.5 GB.
Fits comfortably in a distributed cache; the matching index is the hot read on
every event (70K/sec peak), so it must be in memory, not a DB round-trip per event.

The headline: raw ingestion (70K/sec) is tractable. The genuinely hard numbers are the fan-out amplification (1.3e10 attempts/day from 2e9 events), the retry backlog (hundreds of millions of scheduled future attempts during an outage), and the retry-spike synchronization that creates thundering herds. Those three drive the architecture.

High-Level Design (HLD)

The spine: a thin ingestion layer that validates and durably logs an event; a fan-out/matching layer that expands one event into one delivery task per matching subscription; a scheduler that holds retries in a time-indexed store and releases them when due; a delivery worker fleet that makes the actual HTTP calls with per-endpoint ordering and circuit breaking; and a DLQ + replay path for exhausted deliveries. Durable queues between each stage are what buy availability and the long retry window.

   ┌───────────────────────────────────────────────────────────────┐
   │              Internal producers (payments, auth, ...)          │
   │        POST /events   or   emit onto internal event bus        │
   └───────────────────────────────┬───────────────────────────────┘
                                   │
                        ┌──────────▼───────────┐
                        │   Ingestion API       │
                        │  validate + auth +    │
                        │  assign event_id +    │
                        │  store payload        │
                        └──────────┬───────────┘
            payload to blob store  │  event record to durable log
          ┌──────────────────┐     │     ┌───────────────────────────┐
          │  Payload Store    │◀────┘     │   Event Log (Kafka)        │
          │  (object storage) │           │   partitioned by account   │
          └──────────────────┘           └─────────────┬─────────────┘
                                                        │ consumed
                                          ┌─────────────▼──────────────┐
                                          │   Fan-out / Matcher         │
                                          │  lookup matching endpoints  │
                                          │  (account,event_type)->[ep] │
                                          │  emit 1 delivery task / ep  │
                                          └─────┬──────────────────┬────┘
                           subscription index   │                  │ delivery tasks
                       ┌──────────────────────┐ │        ┌─────────▼──────────────┐
                       │ Subscription Store +  │◀┘        │  Delivery Queue         │
                       │ hot cache (acct,type) │          │  partitioned by         │
                       └──────────────────────┘          │  endpoint_id (ordering) │
                                                          └─────────┬──────────────┘
                                                                    │ due now
     ┌───────────────────────┐   schedule future retries ┌─────────▼──────────────┐
     │  Retry Scheduler       │◀─────────────────────────│  Delivery Worker Fleet  │
     │  time-indexed store    │─────────────────────────▶│  HTTP POST, HMAC sign,  │
     │  (due-at wheel)        │   re-enqueue when due     │  per-endpoint circuit   │
     └───────────────────────┘                           │  breaker, timeouts      │
                                                          └───┬───────────┬────┬────┘
                                         2xx -> delivered     │  4xx/5xx  │    │ exhausted
                                      ┌───────────────────────▼┐  ┌───────▼──┐ ┌▼──────────────┐
                                      │ Delivery Log +          │  │ Backoff  │ │ Dead-Letter   │
                                      │ Webhook status/metrics  │  │ Schedule │ │ Queue + alert │
                                      └─────────────────────────┘  └──────────┘ └───────────────┘

Ingestion flow (synchronous, must be fast):

  1. A producer calls POST /events (or emits onto the internal bus). We authenticate the producer, validate the event shape, and assign a globally unique event_id (used downstream for idempotency and ordering).
  2. We write the payload to the payload store (object storage, returning a reference) and the event record (event_id, type, account_id, payload_ref, an ordering_key, occurred_at) to the durable Event Log (Kafka), partitioned by account.
  3. Return 202 Accepted with the event_id. The producer is done; everything expensive is asynchronous.

Fan-out and delivery flow (asynchronous):

  1. The Fan-out/Matcher consumes the Event Log. For each event it looks up every active subscription matching (account_id, event_type) plus any filters, from the in-memory subscription index.
  2. For each matching endpoint it emits exactly one delivery task (event_id, endpoint_id, payload_ref, ordering_key, attempt=1) onto the Delivery Queue, which is partitioned by endpoint_id so all deliveries for one endpoint stay on one ordered lane.
  3. A Delivery Worker picks up a task, loads the payload, HMAC-signs timestamp + body with the endpoint’s secret, and makes the HTTP POST with a strict timeout (say 10s).
  4. It evaluates the result:
    • 2xx -> delivered. Write a delivered attempt record, advance the endpoint’s ordering cursor.
    • Timeout / connection error / 5xx / 429 -> transient. Compute the next attempt time with exponential backoff + jitter, and hand the task to the Retry Scheduler, which holds it until due and then re-enqueues it onto the endpoint’s lane.
    • Permanent 4xx (e.g. 410 Gone) or window exhausted -> move to the DLQ, record the terminal failure, and feed the endpoint health tracker.
  5. The endpoint health tracker / circuit breaker watches each endpoint’s recent success rate. Sustained total failure trips the breaker (stop attempting, probe occasionally) and, past a threshold, auto-disables the endpoint and alerts the customer.
  6. DLQ and replay: customers see failed deliveries and can replay an event or a specific delivery, which re-injects a delivery task.

The structural insight: there are three decoupling layers. The Event Log decouples producers from fan-out (ingest stays fast and durable). The Delivery Queue, partitioned by endpoint, decouples endpoints from each other (one dead endpoint backs up only its own lane) and is the mechanism that enforces per-endpoint ordering. The Retry Scheduler decouples “when to try again” from the workers, so hundreds of millions of pending retries cost almost nothing until they are due. Wrapped around delivery is the circuit breaker that keeps a dead endpoint from consuming the fleet.

Component Deep Dive

The hard parts, naive-first then evolved: (1) retries with backoff and the scheduler that holds them, (2) per-endpoint ordering under retries, (3) detecting dead endpoints fast and the circuit breaker, (4) fan-out without thundering-herd.

1. Retries, exponential backoff, and the retry scheduler

The job: when a delivery fails, try it again later, not now, and hold possibly hundreds of millions of “try again at time T” tasks cheaply.

Naive approach: the worker sleeps and retries in a loop

The obvious first cut: when a POST fails, the worker sleeps for the backoff interval and retries in place, looping until success or max attempts.

def deliver(task):
    for attempt in range(MAX_ATTEMPTS):
        resp = http_post(task.url, sign(task.body))
        if resp.ok: return
        sleep(backoff(attempt))   # worker blocked here
    dead_letter(task)

Where it breaks:

  • Workers are pinned by dead endpoints. If an endpoint is down for an hour, a worker sleeps for an hour holding one task. With millions of pending retries you would need millions of blocked workers. The thread/connection budget is destroyed instantly.
  • Backoff state is not durable. If the worker crashes mid-sleep, the retry schedule is lost - either the delivery never retries (dropped, violating at-least-once) or you re-deliver from scratch (lost attempt count).
  • No visibility or control. Retries buried in sleeping workers cannot be inspected, paused, replayed, or rescheduled.
  • Synchronized retries. If a shared dependency blips and 100K deliveries fail at the same instant, they all back off by the same fixed interval and retry at the same future instant - a self-made thundering herd.

Sleeping in the worker converts every slow endpoint into pinned capacity and makes the retry schedule volatile and invisible.

Evolved approach: a durable time-indexed scheduler with backoff plus jitter

Separate “decide when to retry” from “hold the task until then” from “do the work.” The worker never sleeps; it fails fast and hands the task to a durable scheduler keyed by due time.

  • Exponential backoff with jitter. On failure n, next attempt at now + min(cap, base * 2^n) plus random jitter. The schedule might be ~10s, 30s, 2m, 10m, 1h, 3h, 6h… up to a 24-72h window, after which the delivery is dead-lettered. Jitter is mandatory: it smears a synchronized failure burst across a window so retries do not re-converge.
base = 10s, cap = 6h, max_window = 72h
delay(n) = min(cap, base * 2**n)
next_at  = now + delay(n) + uniform(0, delay(n) * 0.5)   # up to 50% jitter
  • A time-indexed retry store (the due-at wheel). Pending retries live in a store ordered by next_attempt_at: a sharded sorted structure (Redis sorted sets keyed by due-time bucket, or a scanned database index, or a hierarchical timing wheel). A lightweight promoter process polls “everything due in the next tick” and re-enqueues those tasks onto their endpoint lanes. Holding 200M future timers is just 200M rows/entries, not 200M threads.
  • Durability of attempt state. Each task carries attempt_no, first_seen_at, and next_attempt_at, persisted. A crash loses nothing; the scheduler simply releases the task when due. At-least-once holds across restarts.
  • Backoff respects the endpoint, not just the task. When the circuit breaker (deep dive 3) marks an endpoint down, the scheduler lengthens or pauses that endpoint’s retries entirely, so a six-hour outage does not generate a flood of doomed attempts every few minutes.
Worker: POST fails ──▶ compute next_at = now + backoff(n) + jitter
                       write task to Retry Store (sorted by next_at)
                                   │
Promoter: every tick, pop tasks with next_at <= now ──▶ re-enqueue onto endpoint lane
                                   │
                           Worker retries (attempt n+1); on 2xx done, else reschedule

Why this is right: workers are never blocked, so a dead endpoint costs one cheap row in a sorted store instead of a pinned worker. Backoff plus jitter prevents synchronized retry storms. The schedule is durable, inspectable, pausable, and replayable, and the scheduler can back off per-endpoint based on health. This is the difference between an HTTP loop and a delivery platform.

2. Per-endpoint ordering under retries

The job: deliveries to one endpoint for one logical stream arrive in event order, even when earlier events are mid-retry. If invoice.created is retrying, we must not deliver invoice.paid ahead of it.

Naive approach: a shared pool of stateless workers pulling from one global queue

The first cut: one big delivery queue, N stateless workers pull tasks and POST them. Simple and massively parallel.

Where it breaks:

  • Reordering is the default. Two events for the same endpoint land on two different workers. The second POST can complete before the first (faster network, fewer retries). The consumer sees invoice.paid before invoice.created. For state-machine consumers this is a correctness bug, not a cosmetic one.
  • Retries make it far worse. Event A fails and is scheduled for 1h later; event B (newer) succeeds immediately. A arrives an hour after B. Ordering is not just occasionally wrong, it is reliably wrong whenever anything retries.
  • No notion of a per-endpoint cursor. Nothing tracks “the last event this endpoint successfully received,” so there is no way to even detect, let alone prevent, out-of-order delivery.

A global queue of stateless workers maximizes parallelism and destroys ordering, which is unacceptable for any consumer that treats webhooks as a state stream.

Evolved approach: partition by ordering key, single-flight per key, head-of-line blocking with a bounded escape hatch

Make the unit of ordered work a (endpoint, ordering_key) lane, and allow only one in-flight delivery per lane at a time.

  • Partition the delivery queue by ordering key. The task’s partition key is hash(endpoint_id, ordering_key) where ordering_key defaults to the resource id (e.g. the subscription/customer/object the events concern). All events for one key route to the same partition, so they are consumed in order by one consumer. Endpoints that do not need ordering use ordering_key = event_id (every event its own key -> full parallelism).
  • Single-flight per key with a cursor. Each lane processes one delivery at a time and only advances to the next event after the current one is terminally resolved (delivered or dead-lettered). The lane holds a durable last_delivered_seq cursor so ordering survives restarts and the consumer never sees event k+1 before event k is done.
  • Head-of-line blocking, on purpose, but bounded. If event A is stuck retrying, events B, C behind it on that lane wait. This is correct: you asked for order. But a permanently dead endpoint would block its lane forever, so there is an escape hatch: once the endpoint trips the circuit breaker / auto-disable (deep dive 3), the whole lane is drained to the DLQ in order, unblocking the backlog by terminally failing it rather than reordering it.
  • Ordering is per key, not global. Different ordering_keys for the same endpoint run on different lanes concurrently, so a customer with 10,000 independent objects still gets high throughput; only events about the same object are serialized. This is the key design choice: ordering is scoped as narrowly as correctness allows, so it does not cost global throughput.
  • At-least-once plus ordering plus idempotency. Because we are at-least-once, a redelivery can repeat an event. We include a monotonically increasing per-key sequence and a stable event_id in every payload and signature, so the consumer can both dedupe (seen event_id) and order-check (reject a sequence lower than one already processed).
Events for endpoint E:
  key=cust_42: [created(seq1)] -> [paid(seq2)] -> [refunded(seq3)]   (one lane, in order)
  key=cust_99: [created(seq1)] -> [paid(seq2)]                       (parallel lane)

Lane cust_42:  deliver seq1 ──2xx──▶ cursor=1 ──▶ deliver seq2 ...
               if seq1 retrying, seq2 WAITS (head-of-line, intended)
               if endpoint tripped -> drain lane to DLQ in order, cursor advances

Why this is right: partitioning by (endpoint, ordering_key) with single-flight per lane makes in-order delivery the default, not a hope, and it survives retries because the cursor only advances on terminal resolution. Scoping the key to the resource keeps throughput high (independent objects run in parallel) while serializing only what must be serialized. The DLQ drain is the pressure-release valve that stops a dead endpoint from blocking its own backlog forever. The embedded sequence and event_id let the consumer enforce order and idempotency on their side too, which is what at-least-once requires.

3. Detecting dead endpoints fast and the circuit breaker

The job: notice quickly that an endpoint is permanently unreachable, stop pouring attempts into it, and auto-disable it - because a dead endpoint with thousands of queued deliveries can otherwise consume a disproportionate share of the fleet forever.

Naive approach: treat every endpoint the same, retry each delivery independently to the full window

The first cut: every delivery retries on its own schedule up to the 72h window, regardless of how the endpoint is behaving overall.

Where it breaks:

  • A dead endpoint generates enormous wasted work. An endpoint that has been down for a day still has every one of its (say) 5 million queued deliveries each independently waking up, retrying, failing, and rescheduling. That is millions of pointless POSTs to a URL we already know is dead, burning connections and worker time that healthy endpoints need.
  • No shared knowledge across deliveries. Delivery #1 to endpoint E times out; delivery #2 to the same E, starting a second later, has no idea and tries anyway. The failure signal is not aggregated per endpoint, so the system cannot react as a whole.
  • Slow detection of permanent death. “Permanently unreachable” (DNS gone, 410 Gone, connection refused for days) looks identical to “temporarily down” if you only ever look at one delivery at a time. You keep retrying a corpse for three days.
  • Fleet starvation. During a broad outage, workers fill with doomed attempts to dead endpoints, and live endpoints wait behind them. One customer’s dead URL degrades everyone.

Per-delivery-only retry logic has no concept of endpoint health, so it cannot detect death quickly and cannot stop wasting the fleet on it.

Evolved approach: per-endpoint health state, a circuit breaker, and auto-disable with probes

Track health at the endpoint level, aggregate every delivery outcome into it, and let that state gate the whole endpoint’s traffic.

  • Per-endpoint health counters. For each endpoint keep a rolling window of recent outcomes (success count, failure count, consecutive failures, last success time), updated by every worker atomically in a fast store (Redis). This is the shared signal the naive design lacked.
  • A three-state circuit breaker per endpoint.
StateConditionBehavior
Closednormal success ratedeliver normally, full concurrency
Openconsecutive failures cross a threshold (e.g. 20 in a row, or success rate < X% over the window)stop sending real deliveries; queued tasks are parked, not retried on their own schedules
Half-openafter a cooldown, send a single probe deliveryon success -> close (resume); on failure -> re-open with a longer cooldown
  • Probing instead of blasting. When open, we do not retry all 5M queued deliveries. We send one lightweight probe on an increasing cooldown (1m, 5m, 15m, 1h…). The moment a probe succeeds, we close the breaker and release the backlog in order. This collapses “millions of failing attempts” into “one probe per interval,” which is the core efficiency win.
  • Fast permanent-death signals, short-circuited. Some responses are unambiguous: 410 Gone, DNS NXDOMAIN, TLS cert permanently invalid, or an endpoint deleted by the customer. These skip the gradual breaker and go straight to disable (for 410/NXDOMAIN after a short confirmation window, since a transient DNS blip exists).
  • Auto-disable and alert. An endpoint that stays open past a long threshold (e.g. fails continuously for 3 days, or N consecutive probe failures) is auto-disabled: we stop fan-out to it, drain its queued deliveries to the DLQ, and alert the customer (email/dashboard) so they can fix and re-enable. This is what bounds wasted work and protects the fleet.
  • The breaker gates fan-out too. The Matcher checks endpoint state: for an open/disabled endpoint it writes the delivery straight to a parked state or DLQ instead of onto the live lane, so a dead endpoint does not even enter the hot path.
Every delivery outcome ──▶ endpoint health counters (Redis, atomic)
                                   │
         consecutive_failures >= T │  success rate < X%
                                   ▼
                          [ Circuit: OPEN ]  stop real deliveries, park backlog
                                   │ cooldown elapsed
                                   ▼
                          [ Half-open ]  send ONE probe
                            success ──▶ CLOSED (release backlog in order)
                            fail    ──▶ OPEN (longer cooldown)
                                   │ open too long (e.g. 3 days) / 410 / NXDOMAIN
                                   ▼
                     AUTO-DISABLE: drain backlog to DLQ, alert customer

Why this is right: aggregating outcomes per endpoint turns “millions of independent failing attempts” into a single health signal, so we detect death fast and react once for the whole endpoint. The breaker’s probe-based half-open state means a down endpoint costs one probe per cooldown instead of its full backlog, which is the single biggest protection against fleet starvation. Fast short-circuits on unambiguous death (410/NXDOMAIN) avoid three days of pointless retries, and auto-disable with a customer alert bounds the waste while keeping the human in the loop.

4. Fan-out without thundering-herd

The job: expand one producer event into deliveries for thousands of subscribed endpoints, and survive the retry spikes that fan-out amplifies, without melting the egress fleet or any shared dependency.

Naive approach: match synchronously in the ingest path and fire all deliveries at once

The first cut: when an event arrives, look up all matching subscriptions right there, and immediately POST to every one of them in a tight loop (or a burst of parallel calls).

Where it breaks:

  • Ingest latency becomes fan-out-dependent. An event matching 4,000 endpoints makes the producer’s POST /events wait on 4,000 lookups and sends. Ingestion p99 blows up and is now coupled to the slowest consumer. Producers back up.
  • Synchronized outbound burst. 4,000 simultaneous POSTs for one event, multiplied by thousands of events per second, is an instantaneous spike that saturates egress and overwhelms connection pools. It is a self-inflicted DDoS on your own fleet and on shared downstreams.
  • Retry amplification is catastrophic. Suppose a popular event type fans out to 10,000 endpoints and a shared dependency (say the payload store) blips so all 10,000 fail together. With naive fixed backoff they all retry at the same future instant - 10,000 synchronized retries, then 10,000 again, a standing wave that never disperses.
  • No isolation between hot and cold events. A viral order.updated event starves a rare but critical account.suspended event because they share the same burst path.
  • Repeated payload fetches. Each of the 4,000 deliveries independently fetches the (identical) payload, multiplying load on the payload store by the fan-out factor.

Synchronous in-line fan-out couples ingest to fan-out, creates synchronized bursts, and turns any shared blip into a self-sustaining retry storm.

Evolved approach: asynchronous expansion, rate-shaped lanes, jittered retries, and payload dedupe

Decouple fan-out from ingest, expand lazily, and shape the outbound rate so bursts and retry spikes are smoothed instead of synchronized.

  • Fan-out is asynchronous and incremental. Ingest only writes the event to the log and returns. The Matcher consumes the log and expands fan-out off the critical path. For huge fan-outs it expands in batches (write delivery tasks in chunks, checkpoint progress) so one 50,000-endpoint event does not produce a single giant synchronous burst; tasks trickle onto lanes at a controlled rate.
  • Per-endpoint rate shaping and global concurrency limits. Each endpoint lane has a max in-flight / max rate (respecting the consumer’s capacity and any 429 Retry-After they send). The egress fleet has a global concurrency budget. Fan-out produces tasks; the scheduler and workers release them within these limits, so 4,000 matches become a shaped stream, not an instantaneous spike.
  • Jitter everywhere, especially on retries. Every backoff includes random jitter (deep dive 1), so a synchronized mass failure disperses: 10,000 deliveries that failed together get 10,000 different next-attempt times spread across a window. The standing retry wave flattens into a smear. This single technique is what prevents the thundering herd on retry spikes.
  • Payload stored once, referenced by many. The event payload is written once to the payload store with an event_id key; every delivery task carries the reference, and workers fetch (and cache) it. Fan-out multiplies tasks, not payload copies or payload-store writes. A local worker cache means a hot event’s payload is fetched a handful of times, not 10,000 times.
  • Priority lanes for hot vs critical events. Separate queues/priorities keep a viral high-volume event type from starving a rare critical one. Critical control events (account.suspended) ride a high-priority lane; bulk notifications ride a bulk lane that may lag.
  • Hot subscription index. The (account, event_type) -> [endpoint_ids] matching index is served from an in-memory distributed cache, sharded by account, so matching a 70K/sec event stream never hits a database per event. The index is updated on subscription changes via the subscription store’s change stream.
Event (fan-out 10,000) ──▶ Matcher expands in BATCHES off the ingest path
                                   │  writes tasks at a controlled rate
                     ┌─────────────┼───────────────┐
             endpoint lanes (rate-shaped, bounded in-flight per endpoint)
                     │             │               │
             worker respects per-endpoint rate + global concurrency budget
                     │
   mass failure? each retry gets backoff + JITTER ──▶ 10,000 different next_at times
                     │                                   (herd dispersed, not re-synced)
   payload fetched once per worker (cached), referenced by id, not copied per delivery

Why this is right: moving fan-out off the ingest path keeps acceptance fast and decoupled from the fattest consumer. Batched expansion plus per-endpoint rate shaping plus a global concurrency budget turn a 10,000-way burst into a controlled stream. Jittered backoff is the specific, decisive fix for thundering-herd on retry spikes: it guarantees that a synchronized failure does not produce a synchronized retry. Storing the payload once and caching it per worker removes the fan-out multiplier on the payload store, and priority lanes keep critical events alive during a viral surge.

API Design & Data Schema

API

Producer-facing (internal) event ingestion:

POST /internal/v1/events
Headers: Authorization: Bearer <service_token>
Body:
{
  "type": "invoice.paid",
  "account_id": "acct_123",
  "ordering_key": "cust_42",         // events with same key are ordered per endpoint
  "occurred_at": "2026-11-20T06:30:00Z",
  "data": { "invoice_id": "in_9", "amount": 4999, "currency": "inr" },
  "idempotency_key": "evt-src-uuid"  // producer-supplied dedupe for ingestion
}
Response 202:
{ "event_id": "evt_01hX...", "status": "accepted" }
Errors:
  400  invalid payload / unknown event type
  401  bad service token
  409  duplicate idempotency_key (returns the original event_id)
  413  payload too large

Customer-facing subscription management:

POST   /v1/endpoints
  Body: { "url": "https://api.acme.com/hooks", "event_types": ["invoice.*"],
          "description": "Prod receiver", "metadata": {...} }
  -> 201 { "endpoint_id": "ep_...", "signing_secret": "whsec_...", "status": "enabled" }

GET    /v1/endpoints/{id}                 -> endpoint config + health (status, last_success)
PATCH  /v1/endpoints/{id}                 -> update url / event_types / enable-disable
DELETE /v1/endpoints/{id}                 -> remove endpoint (stops fan-out)
POST   /v1/endpoints/{id}/rotate_secret   -> rotate HMAC secret (dual-secret grace window)

Delivery log, DLQ, and replay:

GET  /v1/endpoints/{id}/deliveries?status=failed&after=...   -> paged attempt log
GET  /v1/deliveries/{delivery_id}                            -> every attempt + responses
POST /v1/events/{event_id}/replay                            -> re-fan-out this event
POST /v1/deliveries/{delivery_id}/retry                      -> re-inject one failed delivery
GET  /v1/endpoints/{id}/dlq                                  -> dead-lettered deliveries

The outbound delivery itself (what we POST to the customer):

POST <customer url>
Headers:
  Webhook-Id: evt_01hX...                 // stable, use for idempotency/dedupe
  Webhook-Timestamp: 1763619000
  Webhook-Signature: v1,<base64 HMAC-SHA256(secret, "evt_id.timestamp.body")>
  Webhook-Sequence: 42                     // per ordering_key monotonic sequence
Body: { "id": "evt_01hX...", "type": "invoice.paid", "data": {...},
        "occurred_at": "..." }
Expected: 2xx within 10s. Anything else (or timeout) -> retry with backoff.

We return 202, not 200, on ingestion - accepted and durably logged, not delivered. The Webhook-Id plus signature is exactly the toolkit a consumer needs to dedupe and verify under at-least-once.

Data stores

Different access patterns, different stores. Be explicit.

1. Event payload store - object/blob storage (S3-class). Payloads are write-once, read-per-attempt, then purged. Referenced by event_id, stored once regardless of fan-out. Lifecycle TTL handles retention.

Blob: events/{yyyy-mm-dd}/{event_id}  -> JSON payload
  Lifecycle: delete after retry window + replay grace (e.g. 30 days).

2. Event + delivery tasks - NoSQL wide-column (Cassandra/Scylla/DynamoDB). Very high write volume (1.3e10 attempts/day), key-scoped lookups, status updates, TTL, no joins. Wide-column sweet spot.

Table: deliveries
  delivery_id    UUID     PARTITION KEY
  event_id       UUID
  endpoint_id    UUID
  ordering_key   STRING
  sequence       BIGINT                 -- per (endpoint, ordering_key)
  status         STRING   -- pending|inflight|delivered|failed|dead_letter
  attempt_no     INT
  http_code      INT      NULL
  next_attempt_at TIMESTAMP NULL
  last_error     STRING   NULL
  created_at     TIMESTAMP
  updated_at     TIMESTAMP
  TTL: 30 days
  Shard by: delivery_id   (single-key status updates)

Table: endpoint_deliveries        -- "show this endpoint's recent deliveries" + ordering cursor
  endpoint_id    UUID     PARTITION KEY
  ordering_key   STRING   CLUSTERING
  sequence       BIGINT   CLUSTERING    -- ordered scan per key
  delivery_id    UUID
  Shard by: endpoint_id  (range scan an endpoint's deliveries; holds the order cursor)

3. Retry schedule - time-indexed store (Redis sorted sets or a scanned index). Pending retries ordered by next_attempt_at, popped when due. Must hold hundreds of millions of future timers cheaply.

ZSET: retries:{bucket}  member=delivery_id  score=next_attempt_at(epoch ms)
  Buckets shard the keyspace; a promoter pops score <= now per bucket each tick.
  Durable backing in the deliveries table (next_attempt_at) so a Redis loss re-derives.

4. Endpoint health / circuit breaker - low-latency store (Redis). Read and updated on every delivery outcome; gates the breaker.

Redis: ep_health:{endpoint_id} -> { success, fail, consec_fail, last_success_at,
                                     breaker_state, cooldown_until }
  Updated atomically (Lua) per outcome; breaker transitions computed in the same op.

5. Subscription store + hot matching index - SQL (Postgres) of record + in-memory cache. Endpoints, secrets, event-type subscriptions, enable/disable state. Small, relational, strong constraints (unique, FKs), low write volume. The hot read path (match (account, event_type)) is served from a distributed in-memory index, kept fresh via Postgres change data capture.

Table: endpoints (Postgres)
  endpoint_id   UUID PK
  account_id    UUID FK
  url           STRING
  signing_secret BYTES (encrypted)
  status        STRING  -- enabled|disabled|auto_disabled
  created_at    TIMESTAMP

Table: subscriptions (Postgres)
  endpoint_id   UUID FK
  event_type    STRING   -- supports wildcard like "invoice.*"
  filter        JSONB    NULL
  PRIMARY KEY (endpoint_id, event_type)

Cache (Redis/distributed): match:{account_id}:{event_type} -> [endpoint_id, ...]
  Rebuilt from CDC on subscription change; hot read on every ingested event.

6. Dead-letter queue - durable queue + the deliveries table. Exhausted/terminally-failed deliveries, with full attempt history, visible and replayable.

DLQ topic (Kafka) + status=dead_letter rows in deliveries. Replay re-injects a task.

Why these choices: the hot paths (delivery tasks, attempt log, health, retry schedule) are high-volume, key-scoped, TTL’d, join-free -> NoSQL wide-column / Redis for horizontal scale and low latency. Payloads are blobs stored once -> object storage. The matching index is read on every event and must not hit a DB per event -> in-memory cache fed by CDC. Subscription/account config is small, relational, and needs real constraints and consistency -> SQL. Nothing on the hot path needs cross-entity ACID, which is why NoSQL carries delivery and SQL stays scoped to configuration.

Bottlenecks & Scaling

Where it breaks first, in order, and the fix for each.

1. Fan-out amplification and synchronized retry storms (breaks first, worst). One event becomes thousands of deliveries; a shared blip fails them together and they re-converge on retry. Fix: asynchronous batched fan-out off the ingest path, per-endpoint rate shaping plus a global concurrency budget, and above all exponential backoff with mandatory jitter so a synchronized failure disperses into thousands of distinct retry times. Priority lanes keep critical events alive during a viral surge.

2. Dead endpoints starving the fleet. A down endpoint with millions of queued deliveries re-retries each one forever, consuming workers live endpoints need. Fix: per-endpoint circuit breaker with a probe-based half-open state - one probe per cooldown instead of the whole backlog - plus auto-disable past a long threshold (drain backlog to DLQ, alert the customer) and short-circuits on unambiguous death (410, NXDOMAIN).

3. Retry backlog that cannot fit in memory. A multi-hour outage schedules hundreds of millions of future retries. Fix: a durable time-indexed retry store (sorted by next_attempt_at), where a pending retry is one cheap row, popped by a promoter when due. Workers never sleep on a retry, so backlog depth costs storage, not threads.

4. Out-of-order delivery under retries. Stateless workers on a global queue reorder events; retries guarantee it. Fix: partition the delivery queue by (endpoint_id, ordering_key), single-flight per lane with a durable cursor that advances only on terminal resolution, intentional head-of-line blocking with a DLQ-drain escape hatch when the endpoint dies. Ordering is scoped to the resource key so independent objects still run in parallel.

5. Matching-index lookups per event. 70K events/sec each needing “which endpoints match” would crush a database. Fix: an in-memory distributed matching index (account, event_type) -> [endpoints], sharded by account, kept fresh via CDC from the subscription store. The DB is the source of truth, not the hot read path.

6. Payload store hammered by the fan-out factor. Each of thousands of deliveries fetching the same payload multiplies load. Fix: store the payload once keyed by event_id, pass a reference in each task, and cache per worker, so a hot event’s body is fetched a handful of times, not thousands.

7. Ingestion as a single point of pressure. All producers funnel through one accept path. Fix: stateless, horizontally scaled ingest behind a load balancer, writing to a partitioned event log (by account). Idempotency keys dedupe producer retries. The log absorbs any downstream slowdown; ingest never waits on delivery.

8. Slow consumers holding worker connections. An endpoint that accepts the connection then responds in 40s pins a worker. Fix: strict per-attempt timeouts (e.g. 10s), bounded in-flight per endpoint, and honoring 429 Retry-After. A slow endpoint consumes only its bounded share, and connection reuse per endpoint caps TLS overhead.

9. Hot keys on health/retry stores during a viral send. One endpoint or bucket hammered at once. Fix: shard health by endpoint_id, retries across time buckets, deliveries by delivery_id; atomic Lua for health updates to avoid lock contention; high-cardinality keys spread naturally. Never shard delivery/attempt stores by created_at - it concentrates all current writes on the “now” shard, a permanent hot spot.

10. Single points of failure. Every stateful piece (Kafka, Redis, the wide-column stores, object storage, Postgres) is replicated across AZs; every stateless piece (ingest, matcher, promoter, workers) is horizontally scaled behind LBs. Deliveries that exhaust retries or fail classification land in the DLQ for inspection and replay - nothing vanishes silently. No single box whose loss stops delivery.

Shard keys, stated plainly: Event log -> partition by account_id (per-account isolation and locality). Delivery queue -> partition by (endpoint_id, ordering_key) (the thing that enforces per-endpoint ordering). deliveries table -> delivery_id (single-key updates). endpoint_deliveries -> endpoint_id (per-endpoint scans and order cursor). retry store -> time buckets by next_attempt_at. health store -> endpoint_id. matching index -> account_id. Never shard by created_at.

Wrap-Up

The trade-offs that define this design:

  • Accept fast, deliver asynchronously. Producers get a 202 in under 50ms; all HTTP work happens behind a durable event log with a 24-72h retry window. We trade immediate delivery for availability, durability, and the ability to retry a down endpoint for hours.
  • At-least-once, not exactly-once. We guarantee an accepted event is attempted until it succeeds or expires, and we hand consumers a stable event_id, a signature, and a per-key sequence so they can dedupe and order-check. Chasing exactly-once on the network would cost availability we are not willing to give up.
  • Ordering scoped to the resource key. Per-(endpoint, ordering_key) lanes with single-flight and a terminal-resolution cursor make in-order delivery the default even under retries, while independent keys run in parallel so ordering does not cost global throughput. Head-of-line blocking is intentional, with a DLQ-drain valve for dead endpoints.
  • Detect death once, per endpoint, not per delivery. Aggregating every outcome into a per-endpoint circuit breaker, probing instead of blasting, and auto-disabling with a customer alert is what stops a dead URL from consuming the fleet and what detects permanent unreachability fast.
  • Jitter is the anti-thundering-herd. Asynchronous batched fan-out, per-endpoint rate shaping, and a global concurrency budget smooth bursts, but the decisive fix for retry spikes is exponential backoff with mandatory jitter, which guarantees a synchronized failure never produces a synchronized retry.

One-line summary: a thin ingestion layer that durably logs events after an idempotency check, an asynchronous batched matcher that fans one event out into per-endpoint delivery tasks, an endpoint-partitioned delivery fleet that enforces per-key ordering with single-flight lanes, a durable time-indexed scheduler that holds hundreds of millions of jittered exponential-backoff retries cheaply, and a per-endpoint circuit breaker with auto-disable and a DLQ - so billions of events a day reach millions of endpoints reliably, in order, without one dead target or one retry spike taking down the platform.