Scheduled Outbound Webhook Delivery Service
Medium · System Design · Software Engineer · Onsite
Prompt
Architect a distributed scheduling platform that accepts deferred HTTP delivery jobs formatted as JSON documents:
{
"url": "https://billing.acme.dev/webhooks/invoice",
"timestamp": "2026-09-14T08:15:00Z",
"data": { "invoice_id": "inv_804", "action": "charge" }
}
Callers register jobs ahead of time; your platform durably records each job and dispatches data to url once the ISO-8601 UTC timestamp arrives.
Several product and operational parameters are intentionally left open—clarify them or state concrete engineering assumptions up front:
- Outbound HTTP verb, headers, payload size ceiling, and connection/read timeouts.
- Peak submission rate, concurrent dispatch throughput, and whether large batches of jobs cluster on identical round timestamps (such as midnight UTC).
- Allowed scheduling horizon (past timestamps vs. months ahead), target firing precision, and whether early execution is ever permissible.
- Definition of successful vs. retryable HTTP responses, retry backoff horizon, and whether callers can inspect, modify, or cancel pending jobs.
- Caller trust boundaries and security restrictions when url can point to arbitrary internet hosts.
Scope & Expectations
- Define the client REST endpoints (including idempotent submission, lookup, and cancellation) alongside the outbound webhook request and authentication format.
- Design the storage schema, sharding key, and indexing mechanism so workers locate due jobs in sub-second time without full-table scans, partition hotspots, or duplicate claims.
- Establish an honest delivery guarantee when a worker crashes between sending the outbound HTTP call and recording the outcome, paired with a clear retry schedule.
- Address multi-tenant isolation against slow or timing-out destination hosts, outbound SSRF defenses, traffic-spike scaling, and node-level fault recovery.
Step-by-step walkthrough
Clarify requirements and scope
Storing a few hundred million small JSON payloads is straightforward. What makes a scheduled webhook service genuinely hard at scale is three distributed-systems problems: 1. Finding the few thousand requests due this second among hundreds of millions of future requests without scanning the entire database. 2. Being honest about what happens if a worker crashes after sending the HTTP call to the target URL, right before recording success in our database. 3. Isolating one slow, hanging, or broken destination URL so it cannot delay deliveries for every other customer.
Functional requirements
- Schedule a delivery: A client submits
{url, timestamp, data}and receives a uniquerequest_id. - Deliver on schedule: At
timestamp, the service sendsdataas the JSON body of an HTTPPOSTrequest tourl. - Inspect, update, or cancel: While a request is still waiting (
SCHEDULED), clients can look up its status, update itstimestampordata, or cancel it. - Retry transient failures: Failed deliveries are retried automatically with increasing delays; permanently failed requests are visible via the API and can trigger an optional client failure-notification URL.
Non-functional requirements
- Durability: Once the API returns
201 Created, a single server or availability-zone crash must never lose the scheduled request. - Timeliness: Never deliver early; under normal load, keep p99 delivery lag (the 99th-percentile delay, meaning 99 out of 100 requests fire faster than this bound) under
1 second; keep lag bounded and predictable during traffic spikes. - At-least-once delivery: Every accepted request is delivered one or more times (never silently dropped). Every retry carries the same stable
Webhook-Idheader so the receiver can make processing idempotent (safe to apply multiple times without duplicating the business effect). - Isolation: One slow target endpoint or one noisy client must not delay deliveries to healthy targets.
- Safe outbound calls: Callers cannot trick our servers into calling private internal networks, and receivers can cryptographically verify that a request came from us.
Concrete assumptions agreed up front
- Outbound HTTP call:
POST <url>withContent-Type: application/json, our signature headers, and up to 10 allowlisted custom headers. Connect timeout3 s, total request timeout10 s, redirects (3xx) disabled. - Success vs. retry: Any
2xxstatus counts as delivered.408 Request Timeout,429 Too Many Requests,5xxserver errors, timeouts, and network/TLS errors are retried up to8 attemptsspread across~11 hours. Redirects (3xx) and other4xxclient errors fail immediately because resending the same bad request will not fix it. - Allowed timestamp window: Timestamps up to
24 hoursin the past fire immediately; older timestamps are rejected (400) as likely client bugs; maximum lead time is1 yearahead. - Traffic shape: Average
2,000submissions/s, peak20,000submissions/s; payload average1 KB, max64 KB; spikes of1,000,000requests scheduled for the exact same round timestamp (such as00:00:00Zmidnight UTC).
- Schedule a delivery: A client submits
Back-of-the-envelope numbers
To convert request rates and wait times into storage and connection counts, we use Little's Law: a queuing rule stating that the average number of items inside a system equals the arrival rate multiplied by the average time each item spends inside (
items = arrival_rate * average_wait_time).1. Traffic & payload assumptions Submissions: 2,000 req/s average (~172.8M/day), 20,000 req/s peak Wait time: median a few minutes, mean 2 days (172,800 s), max 1 year Payload size: 1 KB average, 64 KB max Target latency: 0.3 s median HTTP response time, 10 s hard timeout 2. Pending database size (Little's Law: rate * mean wait) Waiting rows: 2,000 req/s * 172,800 s = 345.6M (~350M) active rows Storage per copy: 350M rows * ~1.5 KB (JSON + row columns + index) = ~525 GB 3 copies (primary + sync replica + cross-region async replica): ~1.6 TB 3. Outbound HTTP concurrency (Little's Law: send rate * HTTP duration) Normal steady state (2,000 sends/s): 2,000 sends/s * 0.3 s = 600 open HTTP connections in flight Midnight spike (1,000,000 due at 00:00:00Z, drained in 5 s -> 200,000 sends/s): 200,000 sends/s * 0.3 s = 60,000 open HTTP connections in flight Worker fleet sizing (at 1,500 async connections/worker -> ~5,000 sends/s each): Normal: 6 workers (2 per availability zone, 30,000 sends/s capacity) 1M midnight spike: pre-scale to 40 workers -> 40 * 5,000 = 200,000 sends/s 4. Why one slow target is dangerous Suppose 1 broken host receives 1,000 req/s and hangs until our 10 s timeout: 1,000 req/s * 10 s = 10,000 stuck connections (~17x normal fleet usage!) 5. Hot database write load 4 row writes on the hot `requests` table per job: (1) INSERT request + (2) INSERT idempotency key + (3) UPDATE claim + (4) DELETE Normal: 2,000/s * 4 = 8,000 row writes/s (+ ~2,000/s expired key cleanup) Midnight spike (20,000/s submit + 200,000/s drain; pause key cleanup): (20,000 * 2) + (200,000 * 2) = 440,000 row writes/s Across 32 database primaries: 440,000 / 32 = ~13,750 row writes/s per primary Because claims batch up to 1,000 rows per SQL statement and deletes batch ~100, each primary executes only ~150 write transactions/s during the spike.What these numbers tell us: - Storage is modest (~525 GB logical): Sharded relational databases (such as PostgreSQL) easily hold the entire active set on NVMe SSDs while giving us strict row-level transactions for claiming and cancelling. - Full-table scans are impossible: Scanning 350M rows every second cannot work; workers must touch only the rows due right now. - Per-host connection caps are mandatory: Without per-destination isolation, a single timing-out endpoint will exhaust all worker sockets in seconds.
API design
To prevent duplicate schedules when a client's network drops right as our API replies, clients pass an
Idempotency-Key: a client-chosen unique string (such as an order ID) that tells our server to return the original scheduled request instead of creating a second copy if the same submission is retried.Client -> Scheduler API ----------------------- POST /v1/requests Headers: Authorization: Bearer <api_key> Idempotency-Key: <client_unique_token, <= 64 chars> (optional, strongly recommended) Body: { "url": "https://billing.acme.dev/webhooks/invoice", "timestamp": "2026-09-14T08:15:00Z", "data": { "invoice_id": "inv_804", "action": "charge" }, (<= 64 KB) "headers": { "X-Tenant": "42" }, (optional, allowlisted names) "max_attempts": 8, (optional, 1..8) "expires_at": "2026-09-14T09:15:00Z" (optional cutoff for retries) } Responses: 201 Created { "id": "req_9Xm...", "state": "SCHEDULED", "timestamp": "..." } 200 OK Same body if Idempotency-Key was already accepted with identical payload 400 Bad Request Invalid URL, private IP literal, or timestamp > 24h in past / > 1y ahead 413 Too Large Payload > 64 KB 422 Unprocessable Idempotency-Key reused with a different request body 429 Too Many Req Per-client submission or pending-row quota exceeded GET /v1/requests/{id} -> 200 { "state": "SCHEDULED|SENDING|DELIVERED|FAILED|CANCELED", "attempts": 2, "last_status_code": 503, "last_error": "timeout", "delivered_at": null } PATCH /v1/requests/{id} { "timestamp"?, "data"? } -> 200 OK if still SCHEDULED, else 409 Conflict { "state": "SENDING|DELIVERED|..." } DELETE /v1/requests/{id} -> 200 { "state": "CANCELED" } if still SCHEDULED, else 409 Conflict with current state GET /v1/requests?state=FAILED&cursor=... -> Paginated list of failed deliveries for this client Scheduler -> Target URL (Outbound Webhook) ------------------------------------------ POST https://billing.acme.dev/webhooks/invoice Content-Type: application/json Webhook-Id: req_9Xm... (identical across all retry attempts -> receiver dedup key) Webhook-Attempt: 2 Webhook-Timestamp: 1789373700 (current attempt Unix epoch seconds) Webhook-Signature: v1=<hex HMAC-SHA256(client_secret, id + "." + timestamp + "." + raw_body)> Body: <raw `data` JSON>Why each API choice matters: -
201means durably stored, not delivered: Delivery happens asynchronously attimestampand is tracked viaGET. - Honest409 Conflicton late cancel/update: Once a worker claims a row (SENDING), the API refuses to promise cancellation and reports the exact state instead of returning a misleading200. - StableWebhook-Idacross attempts: Generating a fresh ID on each retry would hide duplicates from the receiver; keepingreq_9Xm...fixed lets any receiver turn at-least-once delivery into once-only execution.Data model and state machine
We separate hot active rows from finished historical rows: - Hot request store (32 PostgreSQL primaries + synchronous standby replicas): Holds only waiting (
SCHEDULED) and in-flight (SENDING) requests, split into1,024logical shards viashard_id = hash(request_id) % 1024(32 logical shards per primary). - History store (key-value / wide-column store such as DynamoDB or ScyllaDB): Holds finished records (request_history) and per-try logs (attempts) with a 7-day TTL (Time-To-Live, where the database automatically expires old records without heavyDELETEqueries).To make finding due rows fast, we create a partial index: a database B-tree index with a
WHEREfilter so only rows matching that state are stored inside the index.CREATE TABLE requests ( request_id TEXT PRIMARY KEY, -- UUIDv5(client_id, Idempotency-Key), or random UUIDv4 shard_id SMALLINT NOT NULL, -- hash(request_id) % 1024 client_id TEXT NOT NULL, url TEXT NOT NULL, headers JSONB, payload BYTEA NOT NULL, -- <= 64 KB raw JSON bytes scheduled_at TIMESTAMPTZ NOT NULL, -- original requested timestamp (immutable on retry) next_attempt_at TIMESTAMPTZ NOT NULL, -- next fire time (= scheduled_at on attempt 0) expires_at TIMESTAMPTZ, state TEXT NOT NULL, -- SCHEDULED | SENDING | DELIVERED | FAILED | CANCELED attempt INT NOT NULL DEFAULT 0, max_attempts INT NOT NULL DEFAULT 8, lease_owner TEXT, -- worker_id currently holding the row lease_until TIMESTAMPTZ, -- when a stuck SENDING row may be reclaimed last_status_code INT, last_error TEXT, version INT NOT NULL DEFAULT 0 ); -- Partial index on waiting rows only: ordered by next_attempt_at within each shard CREATE INDEX due_idx ON requests (shard_id, next_attempt_at) WHERE state = 'SCHEDULED'; -- Partial index on in-flight rows only: tiny index used to recover crashed workers CREATE INDEX lease_idx ON requests (shard_id, lease_until) WHERE state = 'SENDING'; -- Stored on the same shard (same request_id) in the same transaction as INSERT INTO requests. -- Kept for 24 hours even if the request fires immediately and is deleted from `requests`. CREATE TABLE idempotency_keys ( request_id TEXT PRIMARY KEY, -- UUIDv5(client_id, Idempotency-Key) body_hash BYTEA NOT NULL, -- SHA-256 of request body to catch mismatched reuse created_at TIMESTAMPTZ NOT NULL );Every state transition uses CAS (compare-and-swap): an atomic conditional
UPDATEthat succeeds only if the row still has the expectedstate(orlease_ownerandattempt), preventing race conditions between workers and client cancellations.Request lifecycle state machine ------------------------------- client DELETE (CAS: WHERE state = 'SCHEDULED') +------------------------------------------------+ | v [submit] -> SCHEDULED ---- worker claim (CAS) ----> SENDING CANCELED (terminal -> history) ^ | | retryable error (408/429/5xx/net) +--- 2xx ------------> DELIVERED (terminal) +-- next_attempt_at = now + backoff ---+ +--- permanent 4xx / -> FAILED (terminal) | attempts == max | SENDING with lease_until < now() ------+--> reclaimed into SENDING (attempt + 1)Why
request_id = UUIDv5(client_id, Idempotency-Key)is so clean: 1. Retrying aPOST /v1/requestshashes to the exact samerequest_idandshard_id, so a single local primary-key check onidempotency_keyscatches duplicates with no cross-shard transaction — even if the job was scheduled for "now," already delivered, and deleted fromrequests! 2. Sharding byhash(request_id)instead ofscheduled_atspreads 1,000,000 midnight requests evenly across all1,024logical shards (~977rows per shard) and all32primaries.High-level architecture
Client Backends | | HTTPS (API key + Idempotency-Key) v +----------------------+ INSERT / CAS cancel / GET +------------------------------------+ | Stateless API Fleet | ------------------------------> | Sharded Request Store (PostgreSQL) | | (auth, URL syntax, | | 32 primaries + 32 sync replicas | | per-client quotas) | | 1,024 logical shards by request_id | +----------------------+ +------------------------------------+ | ^ | fallback GET for terminal IDs | poll due_idx every 100 ms, v | atomic CAS claim, update/del +----------------------+ +------------------------------------+ | History Store (KV) | <------------------------------ | Dispatcher Workers (6 -> 40+ pods) | | request_history + | write terminal state & try | async HTTP pool, per-host bulkhead | | attempts (7-day TTL) | | & circuit breaker, HMAC signer | +----------------------+ +------------------------------------+ ^ ^ | shard leases (10 s TTL) | | pre-scale | HTTPS +----------------------------+ +----------+ 10m ahead | POST v | v +--------------------+ +----------------------+ +------------------+ | Coordinator (etcd) | | Spike Forecaster | | Egress Proxies | +--------------------+ | (counts upcoming min | | (DNS pin, block | | on due_idx) | | private CIDRs, | +----------------------+ | no redirects) | +------------------+ | v Public Target URLsTrace of one request from start to finish: 1. Submit: An API pod validates the URL syntax and timestamp, computes
request_idandshard_id, and inserts intorequests(andidempotency_keys) in one transaction. Once committed on the primary and its synchronous cross-zone replica, the API returns201. 2. Poll & claim: Every100 ms, the dispatcher worker assigned toshard_idqueriesdue_idxfor rows withnext_attempt_at <= now()and atomically flips up to1,000due rows fromSCHEDULEDtoSENDINGwithlease_until = now() + 30s. 3. Sign & send: The worker signs(request_id, unix_timestamp, payload)using the client's secret and sends the HTTPPOSTthrough a hardened egress proxy. 4. Record result: - On2xx: the worker writesDELIVERED(and the attempt record) to the History Store, then deletes the row fromrequests(WHERE request_id = :id AND lease_owner = :me AND attempt = :a). - On retryable error: ifattempt < max_attemptsandexpires_athas not passed, it updates the row back toSCHEDULEDwithnext_attempt_at = now() + jittered_backoff. Otherwise it marksFAILEDin History, deletes fromrequests, and enqueues the optional failure callback.Deep dive 1: finding due requests and claiming each one once
Scanning all 350M stored rows every second would saturate disk I/O immediately. Compare the main scheduling patterns at
350Mrows:Scheduling approach Why it breaks (or works) at 350M rows + 1M midnight spikes ------------------------------------ ------------------------------------------------------------ Full table scan every second Reads 350M rows/s -> melts I/O immediately. Single DB + index on due time One primary handles all 440k spike writes/s; workers contend heavily on the head of one B-tree index. Partition by minute (time buckets) All 1M midnight requests hit the single `00:00` partition on one server while the other 31 servers sit idle! In-memory timer wheels only Fast, but not durable; a worker crash loses pending timers. Cloud delay queues (e.g., SQS) Max delay is capped (15 min in SQS), so days-ahead jobs still require a database scheduler anyway. ID-sharded DB + partial `due_idx` CHOSEN: writes & spikes spread evenly across 1,024 shards; + per-shard lease + CAS row claim each poll walks only the tiny due prefix of `due_idx`.Why
due_idxtouches only what is due right now: Within Shard 7,due_idxstores onlySCHEDULEDrows sorted bynext_attempt_at. Suppose it is08:15:00.050Z:Shard 7 partial index `due_idx` (sorted by next_attempt_at): [08:14:59.980Z -> req_A] <-- <= now(): read & claim! [08:15:00.000Z -> req_B] <-- <= now(): read & claim! [08:30:00.000Z -> req_C] <-- > now(): B-tree scan STOPS right here! [2027-01-01... -> req_D] (340,000 future rows in this shard are never touched)A worker runs this single-shard poll-and-claim SQL every
100 msper owned shard (and repeats immediately with zero sleep whenever a batch returns a full1,000rows):UPDATE requests SET state = 'SENDING', attempt = attempt + 1, lease_owner = :worker_id, lease_until = now() + interval '30 seconds', version = version + 1 WHERE request_id IN ( SELECT request_id FROM requests WHERE shard_id = :shard_id AND state = 'SCHEDULED' AND next_attempt_at <= now() ORDER BY next_attempt_at LIMIT 1000 FOR UPDATE SKIP LOCKED ) RETURNING request_id, client_id, url, headers, payload, attempt, max_attempts, expires_at;Notice two crucial details in that SQL: - Single
shard_id = :shard_idfilter: Becausedue_idxis ordered by(shard_id, next_attempt_at), querying oneshard_idstreams the earliest1,000due rows straight off the B-tree leaves with zero sorting, even if50,000rows are due at once!1,024 shards * 10 polls/s = 10,240tiny index probes/s across 32 primaries (320 probes/sper primary,< 2%of one CPU core when empty). -FOR UPDATE SKIP LOCKED: Locks each selected row before updating it, and tells any concurrent query on the same shard to skip already-locked rows instead of waiting behind them.Preventing duplicate claims across workers (three layers): 1. Coordinator shard leases (for efficiency):
etcdassigns each of the1,024logical shards to a single worker via a lease (a temporary ownership lock with a10 sTTL renewed every3 s). In normal operation, only one worker polls each shard. 2. Row-level CAS claim (for correctness): Distributed leases can briefly overlap if a worker freezes during garbage collection and wakes up just asetcdhands its shard to another worker. Correctness therefore relies on the database row: flippingSCHEDULED -> SENDINGunderFOR UPDATE SKIP LOCKEDguarantees only one worker can claim a waiting row. 3. Guarded result writes (fencing stale workers): Every completion or retry update includesWHERE request_id = :id AND lease_owner = :worker_id AND attempt = :attempt, so a slow worker whose lease expired can never overwrite the new worker's state.Deep dive 2: the crash between sending and recording
Calling an external server over HTTP introduces a fundamental distributed-systems boundary: our PostgreSQL database and the customer's
billing.acme.devhost cannot share a single atomic transaction.Worker billing.acme.dev Our Database | | | |--- 1. CAS claim (SENDING) ------>|----------------------------->| (lease_until = 08:15:30) |--- 2. HTTP POST (Webhook-Id) --->| | |<-- 3. 200 OK --------------------| | X [WORKER CRASHES POWER LOSS!] | (still says SENDING!)Walk through all six places a worker can die:
Crash point DB state Recovery outcome ------------------------------------------- ----------- -------------------------------------------- 1. Before claim commits SCHEDULED Next 100 ms poll claims it -> sent once. 2. After claim, before bytes leave socket SENDING Lease expires at +30 s -> resent once (late). 3. After sending bytes, before HTTP reply SENDING Lease expires -> resent; receiver MAY see 2x. 4. After 200 OK, before History write SENDING Lease expires -> resent; receiver WILL see 2x. 5. After History write, before hot DELETE SENDING Reclaimer checks History first, sees DELIVERED, and only deletes hot row -> NO duplicate send! 6. After hot DELETE (History) Completely done -> nothing left to do.If we recorded
DELIVEREDbefore sending thePOST, crashing at step 2 would silently drop customer webhooks (at-most-once). Sending first and recording second guarantees at-least-once delivery. To make duplicates harmless: - We send the exact sameWebhook-Idheader on every attempt. - Receivers store processedWebhook-Idvalues (for at least our retry window, e.g.,72 hours) inside the same local transaction as their business action, returning200 OKimmediately if an ID was already seen.Lease reclamation & retry schedule: - Because HTTP timeout is
10 s, settinglease_until = now() + 30 sleaves a20 ssafety buffer. Before opening an HTTP socket, a worker checks that at least15 sremain on its lease; if not, it drops the item rather than risking an overlapping send. - Workers polllease_idx(WHERE shard_id = :shard_id AND state = 'SENDING' AND lease_until <= now()) every second. Before resending a reclaimed row, the worker checksrequest_historybyrequest_id(handling crash #5 cleanly). - Transient failures (408,429honoringRetry-After,5xx, network timeouts) use exponential backoff with full jitter: after each failed attempt, we raise the delay cap (30 s,2 m,10 m,30 m,1 h,3 h,6 hacross attempts 2..8, ~11 hours max) and pick a uniform random delay between0and that cap so thousands of retries to a recovering server spread out smoothly instead of slamming it in lockstep.Deep dive 3: isolating slow targets and securing outbound calls
Protecting healthy targets from a slow or dead endpoint: If
slow-target.iohangs for10 son every request, we prevent it from starvingfast-target.iowith four layers inside each dispatcher worker:Dispatcher Worker (1,500 total async HTTP slots) +-- Bulkhead [fast-a.com]: [###.................] 3 / 50 slots used -> fires immediately +-- Bulkhead [fast-b.com]: [#####...............] 5 / 50 slots used -> fires immediately +-- Bulkhead [slow-bad.io]: [####################] 50 / 50 slots FULL -> overflow rescheduled!- Strict socket timeouts:
3 sTCP/TLS connect,10 stotal end-to-end, max64 KBresponse body read. - Per-host bulkhead: Named after watertight compartments in a ship's hull, a bulkhead caps any single destination hostname at
50concurrent connections per worker (out of1,500). Even ifslow-bad.iohangs completely,1,450slots remain free for everyone else. - Release instead of blocking: If a host's 50-slot bulkhead stays full for
> 2 s, the worker releases the row back toSCHEDULED(next_attempt_at = now() + 5 s, without incrementingattempt) rather than tying up worker memory. - Per-host circuit breaker: An automatic safety switch that trips open when a host has
>= 20requests in 60 seconds with> 50%timeouts or5xxerrors. While open, workers immediately reschedule due rows for that host with backoff instead of opening sockets, letting just one probe request through every30 sto detect recovery. Chronically failing hosts can also be routed to a dedicated small "slow-lane" worker pool.
Defending against SSRF (Server-Side Request Forgery): Because callers choose
url, an attacker could submit"url": "http://169.254.169.254/latest/meta-data/"or"url": "https://internal-admin.corp/"to trick our servers into reading cloud credentials or internal APIs — an attack called SSRF. Worse, in a DNS rebinding attack,evil.comresolves to a safe public IP when our API validates it, and1 secondlater resolves to127.0.0.1when the worker sends thePOST!Our defense routes every outbound call through dedicated egress proxies: - At submit time: Allow only
https(andhttpif required) on ports443/80, reject URL credentials (user:pass@), and reject raw IP literals in private ranges. - At send time inside the egress proxy (single resolution + IP pinning): Resolve DNS once, verify every returned IP is NOT in any private, loopback, link-local, or cloud-metadata range (0.0.0.0/8,10.0.0.0/8,100.64.0.0/10,127.0.0.0/8,169.254.0.0/16,172.16.0.0/12,192.168.0.0/16, plus IPv6::1,fc00::/7,fe80::/10, and IPv4-mapped::ffff:0:0/96), and open the TCP connection directly to that verified IP so DNS cannot rebind between check and connect. - No HTTP redirects: Reject3xxresponses as permanent failures (a redirect target could point to an internal IP). - Network-level isolation: Run egress proxies in an isolated DMZ subnet with firewall rules blocking all routes to internal VPC subnets and cloud metadata IPs.- Strict socket timeouts:
Scaling, failure handling, and trade-offs
Handling spikes & database churn: - Proactive pre-scaling (the Spike Forecaster): Unlike normal web apps where traffic spikes are surprises, future scheduled webhooks are already sitting in
requests! Once a minute, a forecaster runs index-only counts per upcoming minute ondue_idx(next_attempt_at BETWEEN m AND m + 1m). When it spots1,000,000jobs due at00:00Z, it scales workers (6 -> 40+), egress proxies, and history write capacity10 minutesearly. - Early arming for extreme spikes: For minutes flagged above500krequests, workers can claim rows2 secondsearly into an in-memory min-heap timer and fire at00:00:00.000Zwith zero database claim spike at the exact second (the small trade-off: cancellations in that final 2-second window get409 Conflict). - PostgreSQL dead-row cleanup (autovacuum): Because every row is inserted, updated, and deleted, PostgreSQL leaves dead row versions behind until vacuumed. Deleting finished rows into the separate History Store keepsrequestscompact, and aggressiveautovacuumsettings prevent index bloat ondue_idx.Failure handling summary:
Component failure Impact & automatic recovery ------------------------------ ------------------------------------------------------------------ API pod crashes mid-POST Client retries with same Idempotency-Key -> UUIDv5 hits existing row. DB primary crashes 32 shards pause briefly; synchronous standby promotes in seconds with zero lost acknowledged submits or cancels. Dispatcher worker crashes etcd shard lease expires in <= 10 s (other workers take over polling); in-flight SENDING rows are reclaimed after 30 s lease_until. Coordinator (etcd) unreachable Workers keep polling last-owned shards; DB row CAS still prevents double-claiming. History store degraded Workers write terminal DELIVERED/FAILED state back to `requests` in place; a background mover flushes to History and deletes later. Regional outage Fail over to secondary region's async replica. State RPO honestly (a few seconds of recent submits may be lost or resent unless clients pay the latency of synchronous cross-region commits).Core trade-offs to summarize for the interviewer: - At-least-once + stable
Webhook-Idvs. false "exactly-once" promises: Arbitrary external HTTP servers cannot join our DB transaction, so idempotent deduplication at the receiver is the only truthful guarantee. - ID-sharded relational DB + partial index vs. time-partitioned queues: Hashing byrequest_ideliminates midnight partition hotspots and gives single-row atomic cancel/claim (CAS), trading off PostgreSQL vacuum tuning. - 100 ms polling vs. pure in-memory timers: Stateless crash recovery and< 100 msnormal lag by default, using pre-armed memory timers only for forecast spikes. - Single-hop poll-and-send workers vs. scheduler + Kafka + senders: One source of truth with no extra queue-handoff crash window, at the minor cost of scaling pollers and HTTP senders together.
Intuition & how it works
Think of this system like a hotel wake-up call desk serving 350 million guests across the world. When a guest asks for a wake-up call at 08:15:00 UTC, the clerk writes a slip (req_84) and files it chronologically inside one of 1,024 numbered pigeonholes based on the slip's ID (hash("req_84") % 1024 = pigeonhole 19). Before dialing a room, the clerk stamps the slip SENDING with a 30-second deadline so no coworker dials the same room; only after the guest answers does the clerk move the slip into the archive cabinet.
The naive approach — putting all 350 million rows into a single database table and running SELECT * FROM requests WHERE timestamp <= now() every second — collapses immediately because scanning hundreds of millions of rows melts disk I/O, and partitioning by timestamp instead puts all 1,000,000 midnight alarms onto a single overloaded server while the other 31 sit idle. Keeping timers purely in server memory is equally broken because a power outage erases every future call. Worse, because dialing an external URL and updating our database are two separate network steps, a worker crash right between them makes strict "exactly-once" delivery impossible without the receiver's help.
Walk through a concrete 4-event example to see how the pieces fit together:
1. Submit (08:00:00.100Z): A client posts { "url": "https://billing.acme.dev/webhooks/invoice", "timestamp": "2026-09-14T08:15:00Z", "data": {"invoice_id": "inv_804", "action": "charge"} } with Idempotency-Key: inv-804. The API hashes (client_id, "inv-804") into deterministic ID req_84 (shard_id = 19), inserts SCHEDULED into Shard 19's primary and synchronous standby replica, and returns 201 Created.
2. Poll & claim (08:15:00.040Z): Worker B holds the temporary ownership lease (a short-lived 10 s lock in etcd) for Shard 19. Its 100 ms poll reads the very front of Shard 19's partial index (an index storing only SCHEDULED rows ordered by fire time), sees req_84 has next_attempt_at <= now(), and atomically flips it to SENDING (attempt = 1, lease_until = 08:15:30Z) in one SQL statement.
3. Send via egress proxy (08:15:00.210Z): Worker B signs (req_84, timestamp, body) and sends POST https://billing.acme.dev/webhooks/invoice with header Webhook-Id: req_84 through an outbound proxy that verifies billing.acme.dev resolves to a public IP.
4. Finish or recover (08:15:00.280Z): billing.acme.dev replies 200 OK. Worker B writes DELIVERED to the 7-day History Store and deletes req_84 from the hot requests table. (If Worker B had crashed at 08:15:00.250Z right after billing.acme.dev answered 200 OK, another worker would reclaim req_84 at 08:15:30Z and resend it with the exact same Webhook-Id: req_84, allowing billing.acme.dev to recognize the ID and return 200 OK without charging inv_804 twice.)
Key trade-offs
- At-least-once vs. at-most-once delivery. An HTTP
POSTto a third-party server and a commit in our database cannot form a single atomic step (an all-or-nothing operation). Crashing between them forces a choice: recording success before sending risks silently dropping webhooks (at-most-once), whereas sending before recording risks resending after a crash (at-least-once). We choose at-least-once and attach an unchangingWebhook-Idso receivers that remember recent IDs get effectively-once execution. - Sharding by
request_idvs. partitioning by due time. Partitioning by minute makes "find due jobs" hit a single partition, which turns into a catastrophic hotspot when 1,000,000 jobs share00:00:00Z. Hashingrequest_idacross1,024shards spreads every midnight spike evenly across all 32 database primaries and all workers, at the minor cost of 10 lightweight index probes per second per shard. - 100 ms database polling vs. in-memory timers. Polling the partial index every
100 msis completely stateless on workers and recovers from crashes automatically, adding at most~100 msof scheduling delay. In-memory timer heaps fire to the millisecond without polling, yet lose state on crash or shard handover; we keep polling as the simple default and pre-claim into memory timers2 secondsearly only for forecast mega-spikes. - Single-hop poll-and-send workers vs. scheduler + message queue + senders. Placing a durable log like Kafka between scheduler pollers and HTTP senders decouples their scaling, yet introduces a second state store, an extra duplicate window (crashing after producing to Kafka before updating the DB), and head-of-line blocking when one slow host stalls a partition. Having one worker pool poll, claim, and send via async I/O keeps
requestsas the single source of truth. - Coordinator leases vs. database CAS claims. A coordinator lease (a timed shard assignment in
etcd) keeps 99.9% of polls uncontended, whereas CAS (compare-and-swap, an atomicUPDATE ... WHERE state = 'SCHEDULED'underFOR UPDATE SKIP LOCKED) guarantees two workers never claim the same row even if a paused worker's lease expires mid-query. Using leases for efficiency and row locks for correctness gives both speed and safety. - Synchronous in-region vs. asynchronous cross-region replication. Waiting for a synchronous replica (a standby database in another availability zone that must confirm every write before the API returns
201) adds~2 msto submissions and guarantees zero data loss if a primary dies. Cross-region replication stays asynchronous to avoid50-150 mswide-area latency, with its small regional disaster window stated explicitly.
Common mistakes
- Scanning the full table or indexing finished rows alongside waiting ones, so every 100 ms poll slows down as billions of historical webhooks accumulate.
- Partitioning by
scheduled_at, which routes an entire midnight or top-of-the-hour spike onto a single database node. - Trusting a distributed lock (
etcdor Redis) alone without a conditional row update, allowing a worker frozen by a garbage-collection pause to double-send jobs after another worker takes over its shard. - Updating row results without checking
lease_ownerandattempt, letting a late zombie worker overwrite a reclaimed row back toSCHEDULEDand trigger a third delivery. - Deleting the
Idempotency-Keyrecord when a fast job finishes, so a client retrying a dropped201response a second later schedules a duplicate webhook. - Promising "exactly-once HTTP delivery" to arbitrary internet URLs that cannot join a two-phase transaction, or generating a brand-new
Webhook-Idon every retry so receivers cannot deduplicate. - Sleeping inside a worker thread during retries or omitting jitter, which ties up connection slots and causes thousands of synchronized retries (thundering herd) to knock a recovering target right back down.
- Allowing unbounded concurrency per destination host, letting a single hanging URL consume all
60,000fleet sockets. - Validating
urlvia DNS at submission time and resolving DNS again at send time, leaving the door wide open to SSRF (tricking our servers into calling private IPs like169.254.169.254) via DNS rebinding (swapping a domain's IP from public to internal right before delivery) or open HTTP3xxredirects.
Follow-up questions
- Suppose 1,000,000 webhooks all target 00:00:00 UTC sharp. How does your architecture bound dispatch delay during that burst? First, sharding by
hash(request_id)spreads the 1,000,000 rows evenly to~977rows per logical shard (~31,250per database primary), so all 32 primaries and all workers share the load equally. Second, because scheduled work is visible ahead of time, the Spike Forecaster counts upcoming rows ondue_idxand pre-scales the dispatcher fleet (40workers *5,000 sends/s=200,000 sends/s), egress proxies, and history writers10 minutesbefore midnight, draining 1M calls in~5 seconds(lag ≈ N / throughput). To smooth database claim writes even further, workers can pre-claim rows2 secondsbefore midnight into an in-memory timer heap, while per-destination caps bound lag fairly if one single host is the target of all 1M calls. - If a single destination host hangs and times out on every connection, how do you isolate it so healthy hosts still receive deliveries on schedule? Every outbound call enforces a
3 sconnect timeout and10 stotal timeout, and each worker isolates destinations with a bulkhead (at most50concurrent connections per hostname out of1,500worker slots) so the slow endpoint can never touch the remaining1,450slots. If those 50 slots stay full for> 2 s, waiting rows for that host are returned toSCHEDULEDa few seconds in the future without burning an attempt. Once>= 20calls in a minute exceed a50%timeout/5xxrate, a per-host circuit breaker trips open, immediately rescheduling that host's jobs with backoff and sending just one probe every30 swhile all healthy endpoints keep sub-second delivery. - What happens when a caller sends a cancel request 1 second prior to the scheduled timestamp—can your API strictly promise the webhook will not fire? We guarantee that the API never lies:
DELETE /v1/requests/{id}runs an atomicUPDATE requests SET state = 'CANCELED' WHERE request_id = :id AND state = 'SCHEDULED'on the exact same primary row that workers claim viaSCHEDULED -> SENDING, so database row locking ensures strictly one of the two wins. Under normal fire-time claiming, a cancel arriving1 secondearly wins, commits to the synchronous replica, returns200 OK, and is guaranteed never to be sent. If a worker already claimed the row (for instance, during the optional 2-second early-arming window before a forecast midnight spike), theUPDATEaffects0rows and the API honestly returns409 Conflictwith"state": "SENDING", telling the caller the request could no longer be stopped. - How can a destination server cryptographically authenticate incoming deliveries from your platform and reject captured replays? Each client receives a rotatable secret key, and every delivery includes
Webhook-Id,Webhook-Timestamp(current attempt Unix seconds), andWebhook-Signature: v1=<hex>computed using HMAC-SHA256 (a cryptographic hash combining the shared secret withid + "." + timestamp + "." + raw_bodyso nobody without the secret can forge or alter any field). The receiver first checksabs(now - Webhook-Timestamp) <= 300 seconds, recomputes the HMAC over the raw request bytes using a constant-time comparison, and rejects mismatches or stale timestamps so an attacker cannot replay an old captured request later. Finally, checkingWebhook-Idagainst a cache of already-processed IDs blocks both within-window attacker replays (needing only a 5-minute cache) and our own legitimate retry duplicates (needing a 3-day cache matching our retry window); during secret rotation, we sendv1=<old_sig>,v1=<new_sig>so receivers can verify smoothly without downtime.
Follow-up questions
- Suppose 1,000,000 webhooks all target 00:00:00 UTC sharp. How does your architecture bound dispatch delay during that burst?
- If a single destination host hangs and times out on every connection, how do you isolate it so healthy hosts still receive deliveries on schedule?
- What happens when a caller sends a cancel request 1 second prior to the scheduled timestamp—can your API strictly promise the webhook will not fire?
- How can a destination server cryptographically authenticate incoming deliveries from your platform and reject captured replays?
Similar questions
- Global Live Video Streaming Platform
- Multi-User Collaborative Document Editor
- Burst-Resilient Multi-Channel Notification Platform
- Prior Authorization Status Engine, Clinical Worklists, and Digests
- Diagnosing and Optimizing Full-Stack Web Request Latency
- Multi-Source Enterprise Question Answering System