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

  1. 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 unique request_id.
    • Deliver on schedule: At timestamp, the service sends data as the JSON body of an HTTP POST request to url.
    • Inspect, update, or cancel: While a request is still waiting (SCHEDULED), clients can look up its status, update its timestamp or data, 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-Id header 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> with Content-Type: application/json, our signature headers, and up to 10 allowlisted custom headers. Connect timeout 3 s, total request timeout 10 s, redirects (3xx) disabled.
    • Success vs. retry: Any 2xx status counts as delivered. 408 Request Timeout, 429 Too Many Requests, 5xx server errors, timeouts, and network/TLS errors are retried up to 8 attempts spread across ~11 hours. Redirects (3xx) and other 4xx client errors fail immediately because resending the same bad request will not fix it.
    • Allowed timestamp window: Timestamps up to 24 hours in the past fire immediately; older timestamps are rejected (400) as likely client bugs; maximum lead time is 1 year ahead.
    • Traffic shape: Average 2,000 submissions/s, peak 20,000 submissions/s; payload average 1 KB, max 64 KB; spikes of 1,000,000 requests scheduled for the exact same round timestamp (such as 00:00:00Z midnight UTC).
  2. 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.

  3. 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: - 201 means durably stored, not delivered: Delivery happens asynchronously at timestamp and is tracked via GET. - Honest 409 Conflict on 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 misleading 200. - Stable Webhook-Id across attempts: Generating a fresh ID on each retry would hide duplicates from the receiver; keeping req_9Xm... fixed lets any receiver turn at-least-once delivery into once-only execution.

  4. 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 into 1,024 logical shards via shard_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 heavy DELETE queries).

    To make finding due rows fast, we create a partial index: a database B-tree index with a WHERE filter 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 UPDATE that succeeds only if the row still has the expected state (or lease_owner and attempt), 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 a POST /v1/requests hashes to the exact same request_id and shard_id, so a single local primary-key check on idempotency_keys catches duplicates with no cross-shard transaction — even if the job was scheduled for "now," already delivered, and deleted from requests! 2. Sharding by hash(request_id) instead of scheduled_at spreads 1,000,000 midnight requests evenly across all 1,024 logical shards (~977 rows per shard) and all 32 primaries.

  5. 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 URLs
    

    Trace of one request from start to finish: 1. Submit: An API pod validates the URL syntax and timestamp, computes request_id and shard_id, and inserts into requests (and idempotency_keys) in one transaction. Once committed on the primary and its synchronous cross-zone replica, the API returns 201. 2. Poll & claim: Every 100 ms, the dispatcher worker assigned to shard_id queries due_idx for rows with next_attempt_at <= now() and atomically flips up to 1,000 due rows from SCHEDULED to SENDING with lease_until = now() + 30s. 3. Sign & send: The worker signs (request_id, unix_timestamp, payload) using the client's secret and sends the HTTP POST through a hardened egress proxy. 4. Record result: - On 2xx: the worker writes DELIVERED (and the attempt record) to the History Store, then deletes the row from requests (WHERE request_id = :id AND lease_owner = :me AND attempt = :a). - On retryable error: if attempt < max_attempts and expires_at has not passed, it updates the row back to SCHEDULED with next_attempt_at = now() + jittered_backoff. Otherwise it marks FAILED in History, deletes from requests, and enqueues the optional failure callback.

  6. 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 350M rows:

    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_idx touches only what is due right now: Within Shard 7, due_idx stores only SCHEDULED rows sorted by next_attempt_at. Suppose it is 08: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 ms per owned shard (and repeats immediately with zero sleep whenever a batch returns a full 1,000 rows):

    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_id filter: Because due_idx is ordered by (shard_id, next_attempt_at), querying one shard_id streams the earliest 1,000 due rows straight off the B-tree leaves with zero sorting, even if 50,000 rows are due at once! 1,024 shards * 10 polls/s = 10,240 tiny index probes/s across 32 primaries (320 probes/s per 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): etcd assigns each of the 1,024 logical shards to a single worker via a lease (a temporary ownership lock with a 10 s TTL renewed every 3 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 as etcd hands its shard to another worker. Correctness therefore relies on the database row: flipping SCHEDULED -> SENDING under FOR UPDATE SKIP LOCKED guarantees only one worker can claim a waiting row. 3. Guarded result writes (fencing stale workers): Every completion or retry update includes WHERE 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.

  7. 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.dev host 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 DELIVERED before sending the POST, 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 same Webhook-Id header on every attempt. - Receivers store processed Webhook-Id values (for at least our retry window, e.g., 72 hours) inside the same local transaction as their business action, returning 200 OK immediately if an ID was already seen.

    Lease reclamation & retry schedule: - Because HTTP timeout is 10 s, setting lease_until = now() + 30 s leaves a 20 s safety buffer. Before opening an HTTP socket, a worker checks that at least 15 s remain on its lease; if not, it drops the item rather than risking an overlapping send. - Workers poll lease_idx (WHERE shard_id = :shard_id AND state = 'SENDING' AND lease_until <= now()) every second. Before resending a reclaimed row, the worker checks request_history by request_id (handling crash #5 cleanly). - Transient failures (408, 429 honoring Retry-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 h across attempts 2..8, ~11 hours max) and pick a uniform random delay between 0 and that cap so thousands of retries to a recovering server spread out smoothly instead of slamming it in lockstep.

  8. Deep dive 3: isolating slow targets and securing outbound calls

    Protecting healthy targets from a slow or dead endpoint: If slow-target.io hangs for 10 s on every request, we prevent it from starving fast-target.io with 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!
    
    1. Strict socket timeouts: 3 s TCP/TLS connect, 10 s total end-to-end, max 64 KB response body read.
    2. Per-host bulkhead: Named after watertight compartments in a ship's hull, a bulkhead caps any single destination hostname at 50 concurrent connections per worker (out of 1,500). Even if slow-bad.io hangs completely, 1,450 slots remain free for everyone else.
    3. Release instead of blocking: If a host's 50-slot bulkhead stays full for > 2 s, the worker releases the row back to SCHEDULED (next_attempt_at = now() + 5 s, without incrementing attempt) rather than tying up worker memory.
    4. Per-host circuit breaker: An automatic safety switch that trips open when a host has >= 20 requests in 60 seconds with > 50% timeouts or 5xx errors. While open, workers immediately reschedule due rows for that host with backoff instead of opening sockets, letting just one probe request through every 30 s to 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.com resolves to a safe public IP when our API validates it, and 1 second later resolves to 127.0.0.1 when the worker sends the POST!

    Our defense routes every outbound call through dedicated egress proxies: - At submit time: Allow only https (and http if required) on ports 443/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: Reject 3xx responses 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.

  9. 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 on due_idx (next_attempt_at BETWEEN m AND m + 1m). When it spots 1,000,000 jobs due at 00:00Z, it scales workers (6 -> 40+), egress proxies, and history write capacity 10 minutes early. - Early arming for extreme spikes: For minutes flagged above 500k requests, workers can claim rows 2 seconds early into an in-memory min-heap timer and fire at 00:00:00.000Z with zero database claim spike at the exact second (the small trade-off: cancellations in that final 2-second window get 409 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 keeps requests compact, and aggressive autovacuum settings prevent index bloat on due_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-Id vs. 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 by request_id eliminates 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 ms normal 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 POST to 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 unchanging Webhook-Id so receivers that remember recent IDs get effectively-once execution.
  • Sharding by request_id vs. 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 share 00:00:00Z. Hashing request_id across 1,024 shards 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 ms is completely stateless on workers and recovers from crashes automatically, adding at most ~100 ms of 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 timers 2 seconds early 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 requests as 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 atomic UPDATE ... WHERE state = 'SCHEDULED' under FOR 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 ms to submissions and guarantees zero data loss if a primary dies. Cross-region replication stays asynchronous to avoid 50-150 ms wide-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 (etcd or 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_owner and attempt, letting a late zombie worker overwrite a reclaimed row back to SCHEDULED and trigger a third delivery.
  • Deleting the Idempotency-Key record when a fast job finishes, so a client retrying a dropped 201 response 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-Id on 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,000 fleet sockets.
  • Validating url via 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 like 169.254.169.254) via DNS rebinding (swapping a domain's IP from public to internal right before delivery) or open HTTP 3xx redirects.

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 ~977 rows per logical shard (~31,250 per 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 on due_idx and pre-scales the dispatcher fleet (40 workers * 5,000 sends/s = 200,000 sends/s), egress proxies, and history writers 10 minutes before midnight, draining 1M calls in ~5 seconds (lag ≈ N / throughput). To smooth database claim writes even further, workers can pre-claim rows 2 seconds before 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 s connect timeout and 10 s total timeout, and each worker isolates destinations with a bulkhead (at most 50 concurrent connections per hostname out of 1,500 worker slots) so the slow endpoint can never touch the remaining 1,450 slots. If those 50 slots stay full for > 2 s, waiting rows for that host are returned to SCHEDULED a few seconds in the future without burning an attempt. Once >= 20 calls in a minute exceed a 50% timeout/5xx rate, a per-host circuit breaker trips open, immediately rescheduling that host's jobs with backoff and sending just one probe every 30 s while 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 atomic UPDATE requests SET state = 'CANCELED' WHERE request_id = :id AND state = 'SCHEDULED' on the exact same primary row that workers claim via SCHEDULED -> SENDING, so database row locking ensures strictly one of the two wins. Under normal fire-time claiming, a cancel arriving 1 second early wins, commits to the synchronous replica, returns 200 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), the UPDATE affects 0 rows and the API honestly returns 409 Conflict with "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), and Webhook-Signature: v1=<hex> computed using HMAC-SHA256 (a cryptographic hash combining the shared secret with id + "." + timestamp + "." + raw_body so nobody without the secret can forge or alter any field). The receiver first checks abs(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, checking Webhook-Id against 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 send v1=<old_sig>,v1=<new_sig> so receivers can verify smoothly without downtime.

Follow-up questions

Similar questions

More Anyscale interview questions

All 1 Anyscale questions →