Skip to content
Tech Interview Prep
Technical interview guide

Webhooks & Asynchronous API Integration

Handling work that can't complete within a single request/response cycle: inbound webhooks and long-running async job APIs.

Minutes to read
4
Practice MCQs
25
Interview Q&A
25
Edition
v4
Editorial status
Reviewed

Scope: HTTP Semantics RFC 9110 and OpenAPI Specification 3.2.

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-1

What is a webhook, and what makes them harder than they look?

Answer

The 90-second answer. A webhook is an HTTP POST the provider makes to a URL the consumer registered, so the consumer stops polling. It removes polling latency and the empty responses that polling wastes. The hard part is the direction of control: you are now an HTTP client calling an endpoint you do not own, do not monitor, and cannot fix, and the URL came from a user. Everything else follows from that: at-least-once delivery, no ordering guarantee, retries with backoff and a bounded window, dead-lettering, signature verification, and destination validation.

A receiver that survives it. Python 3.12, Flask 3.0:

Python
import hmac, hashlib, time
from flask import Flask, request, abort

app = Flask(__name__)
SECRET = b"whsec_..."      # from the provider dashboard
TOLERANCE = 300            # seconds; Stripe's default timestamp tolerance

@app.post("/hooks/stripe")
def hook():
    parts = dict(p.split("=", 1) for p in
                 request.headers["Stripe-Signature"].split(","))
    body = request.get_data()          # raw bytes, not the parsed JSON
    signed = parts["t"].encode() + b"." + body
    expected = hmac.new(SECRET, signed, hashlib.sha256).hexdigest()
    if not hmac.compare_digest(expected, parts["v1"]):
        abort(400)                     # forged or corrupted
    if abs(time.time() - int(parts["t"])) > TOLERANCE:
        abort(400)                     # replayed old delivery
    event = request.get_json()
    if not claim(event["id"]):         # INSERT ... ON CONFLICT DO NOTHING
        return "", 200                 # duplicate: already handled
    enqueue(event)                     # do the work off the request
    return "", 200

Trace it against Stripe-Signature: t=1700000000,v1=<hex>. parts becomes {"t": "1700000000", "v1": "<hex>"}. The body must be the raw bytes: re-serialising the parsed JSON changes whitespace and the digest stops matching. Three branches decide the response: bad digest gives 400, |now - 1700000000| > 300 gives 400, and on a second delivery of the same evt_... id claim() returns False and the handler returns 200 with no side effect. The digest itself is not reproducible by hand, so the trace covers the branches, not the hash.

Why at-least-once is the only honest guarantee. Hypothetical retry schedule, endpoint down at first:

attemptt (s)receiverresponsesender
10DB connection refused500schedule retry
210DB still down500schedule retry
340processed, committed200stop
4———none

Now the case that matters: attempt 1 commits and returns 200, but the TCP connection resets before the sender reads the response. The sender cannot distinguish that from a failure, so it retries. The receiver sees the same evt_... id, claim() returns False, and it returns 200 without reprocessing. That is why the dedupe key must be the provider's event id, not a hash of the payload: two legitimate events can carry identical bodies.

Failure modes and how you see them.

  • Duplicates. Dedupe table keyed on the event id; alert on the duplicate rate, because a spike means your endpoint is timing out after committing.
  • Out-of-order. Neither Stripe nor GitHub guarantees ordering. If order matters, carry a monotonic version per resource and drop stale deliveries; serialising per receiver instead means one slow endpoint stalls every other event for that receiver.
  • Retry exhaustion. Stripe retries live-mode events for up to three days with exponential backoff, so a receiver down for a week loses those events permanently. Dead-letter queue plus an alert on the queue depth.
  • SSRF. The destination URL is user-supplied. A naive sender will happily POST to http://169.254.169.254/latest/meta-data/ (the EC2 instance metadata endpoint) or to RFC1918 addresses. Allowlist hostnames, resolve DNS and check the resolved IP, and disable redirects or re-check after each hop.
  • Forgery and replay. Verify the HMAC and the timestamp window as above. GitHub uses X-Hub-Signature-256 (HMAC-SHA256) and X-GitHub-Delivery, a GUID per delivery; GitHub does not redeliver automatically, so a failed delivery is gone unless you redeliver it yourself.

When not to use one. Between systems you control, a durable queue or a retained log is usually better: buffering, backpressure, and replay without custom delivery machinery. Webhooks exist for crossing an organisational boundary where you cannot share a broker.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-5

Compare webhooks, polling, server-sent events and WebSockets.

Answer

In 60 seconds. Two axes decide it: who initiates (pull vs push) and what the consumer is (browser or server). Polling and long polling pull; SSE and WebSockets push over a held connection; webhooks push to a server you own. Browsers cannot receive webhooks, so a browser consumer is SSE, WebSocket or polling. A server consumer can take webhooks, so it is webhooks for latency or polling for simplicity.

DirectionTransportReconnectWire overheadScales as
Pollingclient pullsHTTPn/afull request + headersreq/s
Long pollingclient pulls, server holdsHTTP, held ~30 sclient re-issuesfull request per eventheld connections
SSEserver→clienttext/event-stream over HTTP/1.1 or h2automatic, Last-Event-IDtens of bytes of framingopen connections
WebSocketboth waysHTTP Upgrade → 101, then framesapp-level2–14 B frame headeropen connections
Webhooksserver→serverHTTP POSTprovider policyfull requestdeliveries/s

Polling. 50,000 devices on a 30 s interval is 1,667 req/s; if 95% return "nothing changed", ~1,580 of those are pure waste. ETag + If-None-Match turns the body into a 304 but the request still costs a round trip. Jitter the interval, or every client wakes in the same second.

SSE. The wire format is text:

retry: 5000

id: 42
event: price
data: {"sku":"A1","cents":1999}

retry: 5000 sets the reconnect delay to 5 s; without it the browser picks its own default. On reconnect the browser sends Last-Event-ID: 42 and the server replays from 43: resumption is in the protocol, not your code. It is UTF-8 text only; binary needs base64. Over HTTP/1.1 browsers cap at ~6 connections per origin, so a second tab can starve the first; HTTP/2 removes that.

WebSockets. The handshake is an HTTP Upgrade returning 101. The frame header is 2 bytes, +2 or +8 for extended length, +4 mask on client→server frames: a 1-byte client message is 7 bytes on the wire. Close codes: 1000 normal, 1001 going away, 1006 abnormal (no close frame). You own reconnection and heartbeats.

Webhooks. At-least-once by contract: Stripe retries for up to three days with exponential backoff. Verify Stripe-Signature's t= timestamp inside the default 300 s tolerance or you accept replays. Ordering is not guaranteed: carry the event's own timestamp and drop stale ones. Detect duplicates by counting deliveries against distinct event IDs; dedupe on the event ID with a unique index.

Failure modes and how you see them. SSE behind a buffering proxy arrives in bursts instead of a stream: measure inter-arrival times, fix with X-Accel-Buffering: no and Cache-Control: no-cache. Idle WebSockets die at the load balancer: ALB's default idle timeout is 60 s and nginx proxy_read_timeout defaults to 60 s, so the client sees 1006. Count 1006 closes, then ping every 30 s or raise the timeout. A deployment disconnects every client at once; reconnect with jitter or you DDoS yourself.

Choosing. Browser: SSE if one-way, WebSocket if genuinely bidirectional, polling if updates are rarer than the interval. Server: webhooks for latency, polling for reconciliation. A public API should offer both: webhooks for latency, polling so a consumer who missed events can catch up without a support ticket.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

When would you choose webhooks over a message queue, and vice versa?

Answer

Assume both sides are services you operate unless stated otherwise. Default to a queue when the consumer is inside your trust boundary and you can require it to run a broker client. Choose webhooks when the consumer is outside that boundary (a customer, a partner, a third-party SaaS) and you cannot ship them a Kafka/SQS client, credentials, and network access. The decision is who owns delivery: the broker or your HTTP client.

DimensionQueueWebhook
Delivery guaranteeBroker persists until ack; at-least-once, or exactly-once with SQS FIFO dedupeProvider-dependent; usually at-least-once with retries, so duplicates are normal
BackpressureConsumer pulls at own rate; backlog is visible as lagProvider pushes; slow consumer causes timeouts and retries, not a backlog you can inspect
ReplayKafka retains 7 days by default (log.retention.hours=168); SQS retains 4 days default, 14 maxReplay only if provider stores events and offers a redelivery API
OrderingKafka per partition; SQS FIFO per message groupUsually unordered; timestamp or sequence number needed
AuthBroker IAM/SASL/mTLSHMAC-SHA256 signature + timestamp, or OAuth
Failure detectionConsumer lag, DLQ depthDelivery logs, endpoint failure rate, DLQ
CostBroker + storage + egressHTTP calls + retries + support

Worked example: an internal order service emits 10k events/day to a fulfilment service. With webhooks, 0.5% of deliveries fail (50/day). Retries at 1s, 10s, 100s, 1000s, 10000s sum to about 3 hours; a 24-hour outage exhausts the schedule, so you need a DLQ and manual replay. With SQS, the same 50 failures become visibility-timeout redeliveries; set maxReceiveCount=5 and a DLQ. The queue gives you the retry schedule, DLQ, and redrive without code. That is the default inside one org.

A webhook receiver still needs idempotency and signature checks. Python 3.11:

Python
import hmac, hashlib, time
from flask import Flask, request, abort

app = Flask(__name__)
SECRET = b"..."  # from provider
seen = set()  # replace with Redis/DB in production

@app.post("/webhook")
def receive():
    sig = request.headers.get("X-Signature", "")
    ts = request.headers.get("X-Timestamp", "")
    body = request.get_data()
    if abs(time.time() - int(ts)) > 300:
        abort(400)  # replay window
    expected = hmac.new(SECRET, ts.encode() + b"." + body, hashlib.sha256).hexdigest()
    if not hmac.compare_digest(expected, sig):
        abort(401)
    event_id = request.json["id"]
    if event_id in seen:
        return "", 200  # idempotent
    seen.add(event_id)
    # enqueue to internal queue, then return fast
    return "", 202

The hybrid is the robust pattern: use a queue internally, with a delivery worker consuming from it and making the outbound HTTP calls. The queue gives durability, retry, and backpressure for the internal half; the webhook is only the last hop.

producer -> queue (SQS/Kafka) -> delivery worker -> HTTP POST -> consumer endpoint
                                      |
                                      +-> DLQ on 5xx/429 after N retries

Some providers let you write directly to a queue the consumer owns, or to a cloud event bus. S3 event notifications can target SQS, and EventBridge can target SQS. That gives queue semantics across the boundary and avoids the webhook problems entirely, but it requires the consumer to have that infrastructure, so it will not be the default.

Concrete failure modes: webhooks duplicate after retry, arrive out of order, or get disabled after consecutive failures; detect via delivery logs, DLQ depth, and 5xx rate. Queues show consumer lag, poison messages, and ordering only per partition or message group; detect via lag metrics, DLQ depth, and max.poll.interval.ms exceeded causing a rebalance. Use a queue when the consumer can connect and you need replay or ordering. Use a webhook when the consumer cannot run a broker client, or the event is a low-volume notification where a queue client is overkill.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-7

What should a webhook payload contain?

Answer

A webhook payload needs four things before anything else: a stable event id unique per delivery, an event type, a timestamp, and the id of the affected resource. Without the event id the receiver cannot deduplicate; without the type it cannot dispatch; without the timestamp it cannot order or expire; without the resource id it cannot look anything up.

Real providers put them in different places, which is worth knowing when you design your own. GitHub sends type and delivery id as headers (X-GitHub-Event: push, X-GitHub-Delivery: 7d3f... (a GUID, new on every redelivery)) and the timestamp inside the body. Stripe puts everything in the body: id: "evt_...", type: "payment_intent.succeeded", created: 1712345678 (Unix seconds), data.object.id: "pi_...".

The decision that matters is thin versus fat. Here is a Stripe-shaped fat event, trimmed:

JSON
{
  "id": "evt_1Nx8aB2eZvKYlo2C",
  "type": "payment_intent.succeeded",
  "created": 1712345678,
  "api_version": "2023-10-16",
  "livemode": true,
  "data": { "object": { "id": "pi_3Nx8aB2eZvKYlo2C",
                        "amount": 4200, "currency": "usd",
                        "status": "succeeded" } }
}

(IDs illustrative.) A thin version of the same event drops data.object to just the id and makes the receiver call GET /v1/payment_intents/pi_.... Sizes below are approximate.

thinfat
payload size~200 Ba few KB for a full object
receiver workone API call per eventnone
stalenessstate at fetch time, may have moved onstate as of the event
your API loadone read per event per receivernone
sensitive datastays with younow in their logs

Default: fat enough that the common case needs no follow-up call, carrying state as of the event, with ids so a receiver needing more can fetch it.

Deduplicate on the event id, not the resource id: one resource legitimately produces many events. The insert and the side effect must share a transaction:

Python
# Python 3.12, psycopg 3
def handle(event):
    with conn.transaction():
        row = conn.execute(
            "INSERT INTO processed_events (event_id) VALUES (%s) "
            "ON CONFLICT (event_id) DO NOTHING RETURNING event_id",
            (event["id"],)).fetchone()
        if row is None:
            return          # already handled
        apply_event(event)

Trace: the first delivery of evt_1Nx8aB... inserts, RETURNING yields the id, row is not None, apply_event runs, commit. A redelivery of the same id hits ON CONFLICT DO NOTHING, returns no row, fetchone() is None, and the function exits with no side effect. If apply_event raises, the transaction rolls back and the insert disappears with it, so the retry can still process the event.

Acknowledge before you work. Slack requires a 2xx within 3 seconds; GitHub times out a delivery after 10 seconds. Enqueue and return.

Sign it. GitHub's X-Hub-Signature-256 is HMAC-SHA256 over the raw body; Stripe's Stripe-Signature carries t= and v1=, and its libraries reject signatures older than 300 seconds by default. Verify against the raw bytes, not a re-serialised object.

Evolution: add fields, never remove or repurpose. Stripe stamps api_version on every event so the receiver knows which shape it got; GitHub's X-GitHub-Event lets a receiver ignore types it does not know. Say in the docs, before you have consumers, that unknown fields and unknown types must be ignored. Describe payloads in OpenAPI so receivers can validate and generate handlers.

Exclude anything sensitive the receiver does not need. Payloads get logged, stored and forwarded in ways neither party controls.

The framing worth keeping: an event describes what happened, as a fact. A payload that tells the receiver what to do couples you to their implementation and ages badly.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-24

What delivery guarantee does a webhook system actually provide, and what does each clause of that guarantee force the consumer to build?

Answer

The guarantee is at-least-once, unordered, and bounded in time, and it ends in terminal failure. Not exactly-once, not ordered, and not "we will get it there eventually". I would state those four clauses separately, because each one moves work onto the consumer, and an integrator who assumes any of them differently will lose money.

At-least-once means duplicates are a normal case, not an error. They happen when the receiver commits the event but the response is lost, when the receiver returns 5xx after partially processing, or when a timeout fires on our side while their handler is still running. So the consumer needs an idempotency key, the event ID, and a dedup store whose retention covers our whole retry window plus delivery lag. If they keep IDs for 24 hours and we retry for 15, a duplicate from hour 16 gets processed twice.

Unordered means retries reorder delivery. Event B's first attempt can land before event A's third. Arrival order is not causal order, so the consumer must not apply events in the order received: either carry a per-resource version or sequence number and reject stale writes, or treat the event as a hint and re-fetch current state.

The retry window is defined by the backoff schedule. Ours, with full jitter (the AWS Well-Architected reliability guidance's recommendation, since synchronized retries from many endpoints become a thundering herd against a recovering consumer): base 30 s, multiplier 4, cap 6 h, 8 attempts.

AttemptBackoff valueDelay before it (full jitter: 0–value)Cumulative if no jitter
1000
230 s30 s30 s
32 m2 m2 m 30 s
48 m8 m10 m 30 s
532 m32 m42 m 30 s
62 h 8 m2 h 8 m2 h 50 m 30 s
78 h 32 m → capped 6 h6 h8 h 50 m 30 s
8capped 6 h6 h14 h 50 m 30 s

Each delay is 30 s × 4ⁿ⁻² until it hits the 6 h cap, which it does at attempt 7. Without jitter the eighth attempt lands about 15 hours after the first. With full jitter each delay is random between zero and the backoff value, so 15 hours is a bound, not a schedule: the contract has to publish the maximum window, not promise attempt times. That number is the one that matters operationally: a consumer outage longer than 15 hours means those events are gone from delivery, and no amount of retry tuning fixes it.

What counts as success decides the whole retry behaviour. Per RFC 9110's status classes: 2xx is delivered; timeouts and 5xx are retryable; 429 and 408 are retryable and we honour Retry-After; any other 4xx is terminal on the first attempt, because the consumer told us no and retrying a 400 eight times is just load. Each attempt gets a hard timeout, 10 s in our design, so one slow endpoint cannot pin a delivery worker.

Terminal failure is part of the guarantee, not a gap in it. After the eighth attempt the event is dead-lettered: retained (30 days of events, 7 days of attempt logs in our setup), visible in the consumer's delivery log with status codes and response bodies, and surfaced to them. A failure notification or a "failing endpoint" flag, not silence. Silence is what turns a delivery problem into a support ticket.

The guarantee is only sound if the consumer can reconcile. Webhooks are notifications, not the source of truth. We expose a GET event-history endpoint with the same IDs, so a consumer who missed a window, or who was down, can diff their state against ours and backfill. Without that fallback, at-least-once is really "at-least-once or lost, and you can't tell which".

So the contract I'd publish has five lines: at-least-once with duplicates possible; unordered; the backoff schedule and the maximum window; what counts as delivered (2xx within 10 s) and what is terminal; retention, dead-letter handling, notification, and the reconciliation endpoint. OpenAPI 3.1 has a webhooks object where that description lives next to the rest of the API, which is where integrators will look for it.

Failure modes I'd watch for: double side effects because the consumer trusted exactly-once; dedup TTL shorter than our window; stale overwrites from assuming ordering; and a consumer returning 200 before persisting, which loses events on their crash and only shows up as a reconciliation diff.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-21

Explain the failure modes a webhook consumer should plan for.

Answer

The 60-second answer. Assume every event arrives twice, out of order, hours late, or never. Four things follow: idempotent handlers keyed on the provider's event id, ordering resolved per object rather than globally, a reconciliation job that closes gaps the retry window cannot, and signature verification with a timestamp tolerance. Bursts, unknown fields and your own deploys are consequences of those four, not separate problems.

Duplicates. At-least-once is the contract, so duplicates are certain. Dedupe on the event id inside the same transaction as the work: a separate check-then-act races.

Python
# Python 3.12, psycopg 3.2, PostgreSQL 16
def handle(raw_body: bytes, headers: dict) -> int:
    verify_signature(raw_body, headers)      # raises on bad HMAC or stale timestamp
    event = json.loads(raw_body)
    with conn.transaction():
        row = conn.execute(
            "INSERT INTO processed_events (event_id) VALUES (%s) "
            "ON CONFLICT (event_id) DO NOTHING RETURNING event_id",
            (event["id"],),
        ).fetchone()
        if row is None:
            return 200                       # already applied
        apply_effect(event)                  # same transaction
    return 200

Trace, body {"id":"evt_1","type":"invoice.paid","created":1735689600}:

  1. Delivery A: signature passes, INSERT returns ('evt_1',), apply_effect runs, COMMIT, 200.
  2. Delivery B, same id, 30 s later: INSERT conflicts on the primary key, RETURNING yields zero rows, fetchone() is None, so apply_effect never runs and the handler returns 200.
  3. B arriving while A is still open: B's INSERT blocks on the unique index until A commits, then sees the committed row and returns zero rows. Exactly one apply.

A SELECT-then-INSERT version lets A and B both read "absent" before either commits, and both apply. That is the race.

Out of order. Retries reorder events even when the sender emitted them in order. Stripe's event.created is second-resolution and delivery order is not guaranteed, so compare against a stored per-object version or timestamp and drop anything older than what you have applied.

Missing. Stripe retries failed deliveries with exponential backoff for up to 3 days in live mode. GitHub does not auto-redeliver at all: a failed delivery is gone unless you redeliver it from the UI or API. Reconciliation against the provider's list API is the only backstop; without it a gap is permanent and invisible. Detect it by comparing your hourly event count against the provider's.

Late. An event can arrive hours after it happened. Use created, not wall clock, before sending a "just happened" notification.

Unknown types and fields. Providers add both. Log and ignore unknown types rather than returning 4xx, and pin the endpoint's API version so a provider release cannot change the payload shape under you.

Forged and replayed. Verify the HMAC over the raw bytes before parsing: re-serializing JSON changes the bytes and breaks the check. Stripe sends Stripe-Signature: t=...,v1=..., HMAC-SHA256 over {t}.{raw_body}, with a 300-second default tolerance in Stripe's libraries. GitHub sends X-Hub-Signature-256: sha256=... over the raw body. Standard Webhooks uses webhook-id, webhook-timestamp, webhook-signature over {id}.{timestamp}.{payload}. The timestamp tolerance plus the dedupe insert is what stops a captured request being replayed forever.

Bursts and your own downtime. After an outage the backlog arrives at once, so acknowledge fast (2xx in under a second), enqueue, and process asynchronously with a bounded worker pool. During your deploys, return 5xx so the provider retries; returning 200 while broken loses events permanently. Stripe treats 410 Gone as a signal to disable the endpoint.

FailureDetectionMitigation
Duplicateunique-violation count on processed_eventsinsert-and-apply in one transaction
Out of orderper-object version regression counterdrop stale by created/version
Missinghourly count vs provider list APIreconciliation job
Lateevent-age histogramuse created, not now
Unknown typecount of unhandled type valuesignore, do not 4xx
Forgedsignature-failure counterverify raw body before parse
Replaytimestamp-tolerance rejects300 s tolerance + dedupe
Burstqueue depth, p99 ack latencyack fast, async process
Own downtimeprovider retry log5xx, never 2xx while broken

Retention arithmetic, hypothetical: dedupe rows must outlive the retry window. At 50 events/s peak that is 50 × 86,400 = 4.32M rows/day; 30 days is ~130M rows, roughly 8 GB with a UUID key and timestamp at ~60 bytes/row including index overhead. Keep at least the provider's window (3 days for Stripe) and prune on a schedule.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-4

How should a webhook receiver be implemented?

Answer

The 90-second answer. Verify the signature over the raw body, write the event to a durable table or queue keyed by the provider's event id, return 2xx, and do the work in a worker. The endpoint's only job is to accept or reject; everything downstream is asynchronous. Budget the handler at a few hundred milliseconds: the sender's timeout is measured in seconds and you don't control it.

Processing inline is the mistake that compounds: the work outlives the sender's timeout, the sender records a failure and retries, and now the same event is running twice concurrently while the first attempt is still going. A slow handler becomes a duplicate-processing bug.

Verify before you parse. Sign the raw bytes, not a re-serialized object: json.dumps(json.loads(body)) changes whitespace and key order and the HMAC stops matching. Header names differ by provider: Stripe-Signature (t=<unix>,v1=<hex>), GitHub's X-Hub-Signature-256 (sha256=<hex>), Shopify's X-Shopify-Hmac-Sha256 (base64).

Python
# Python 3.12, stdlib only. Stripe-style header: "t=1700000000,v1=<hex>"
import hashlib, hmac, time

TOLERANCE = 300  # seconds; Stripe's default timestamp tolerance

def verify(raw_body: bytes, header: str, secret: bytes) -> bool:
    parts = dict(p.split("=", 1) for p in header.split(","))
    ts = int(parts["t"])
    if abs(time.time() - ts) > TOLERANCE:
        return False                       # stale or future-dated: replay
    signed = str(ts).encode() + b"." + raw_body
    expected = hmac.new(secret, signed, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, parts["v1"])

Trace it with header="t=1700000000,v1=<hex>", raw_body=b'{"id":"evt_1"}', secret=b"whsec_x", and the clock at 1700000100:

  1. parts → {"t": "1700000000", "v1": "<hex>"}.
  2. ts = 1700000000; |1700000100 - 1700000000| = 100, which is ≤ 300, so it continues.
  3. signed = b"1700000000." + b'{"id":"evt_1"}'.
  4. expected is the HMAC-SHA256 of those bytes; compare_digest returns True only if v1 matches. Change one byte of the body and it returns False.

The timestamp check is what stops a captured request being replayed tomorrow. Reject with 4xx and never act on a failed verification.

Deduplicate on the event id, inside the transaction. At-least-once delivery means duplicates are certain. Two deliveries of evt_1 arriving 40 ms apart:

stepworker Aworker B
1SELECT for evt_1 → no row
2SELECT for evt_1 → no row
3INSERT + side effect, COMMIT
4INSERT → unique violation, rollback, return 2xx

With the check outside the transaction both commit and the side effect (a $20 credit, an email) happens twice. A unique index on event_id plus INSERT ... ON CONFLICT DO NOTHING makes step 4 the only possible outcome. This race passes every sequential test you will write.

Return the right status. 2xx means received. Anything else means "retry me", which is correct only if you genuinely could not accept it. Returning 200 while failing internally is the worst option: the sender considers it delivered, the event is gone, and neither side knows.

senderretry policycost of a non-2xx
Striperetries for up to 3 days with exponential backoff (live mode)duplicate deliveries, order not guaranteed
GitHubno automatic redeliverythe event is lost unless you redeliver manually

Ignore unknown event types and unknown fields, returning 2xx. Senders add both; a receiver that rejects them breaks on the sender's next release.

Handle out-of-order events. Retries reorder deliveries even when the sender sent them in order. Compare the event's timestamp or sequence number against what you have applied and drop anything older.

Reconcile. Events will still be missed: an outage longer than the retry window, a deployment gap, a bug. Poll the provider's list API for the last 7 days on a schedule; that window is wider than Stripe's 3-day retry, so anything the retries gave up on still gets caught. Sizing: 1M events/day × 7 days = 7M ids; a 16-byte id plus an 8-byte timestamp and index overhead is roughly 40 bytes a row, so about 280 MB. Cheap enough to keep, and the step most receivers skip.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

What are the most common correctness mistakes in webhook consumer implementations, and how do you avoid them?

Answer

Nearly every consumer bug traces back to three facts people forget: delivery is at-least-once, it is unordered, and the payload is a snapshot of when the event fired, not of state now.

Verifying signatures over re-encoded bytes. HMAC covers the exact bytes the sender signed. If your JSON middleware parses the body and you re-serialize to verify, whitespace and key order differ and verification fails, or you end up comparing decoded fields and no longer verifying the message at all. Capture the raw body before anything parses it and verify against that buffer, with a constant-time compare and a timestamp tolerance so a captured delivery can't be replayed days later.

JavaScript
// Node.js 20 / Express 5. Raw body must be captured before express.json() runs.
app.post('/webhooks', express.raw({ type: 'application/json' }), (req, res) => {
  const [t, v1] = req.get('x-signature').split(',').map(p => p.split('=')[1]);
  if (Math.abs(Date.now() / 1000 - Number(t)) > 300) return res.sendStatus(400);
  const expected = crypto.createHmac('sha256', SECRET)
    .update(`${t}.`).update(req.body).digest('hex');     // req.body is a Buffer
  const a = Buffer.from(expected), b = Buffer.from(v1);
  if (a.length !== b.length || !crypto.timingSafeEqual(a, b)) return res.sendStatus(401);
  enqueue({ id: req.get('x-event-id') });                 // dedup + process off the request path
  res.sendStatus(202);
});

This is the shape RFC 9421 assumes: signature components taken from the message as received, not from a reconstruction of it.

A handler that isn't idempotent. You will receive the same event twice: timeout on the ack path is enough. The fix is two-layered: dedup on the event ID, and make the write itself idempotent so correctness doesn't depend on the dedup store being right.

twhat happens
09:00:00attempt 1 charges the card, then the ack is lost
09:10:00attempt 2, same event ID. Insert hits UNIQUE(event_id), returns 200, no second charge

So: INSERT ... ON CONFLICT (event_id) DO NOTHING, or an upsert keyed on the domain entity so a stale repeat converges.

Doing real work inside the HTTP handler. Any blocking call (a downstream API, a bulk DB write, an email) goes after the ack. Return 202 (RFC 9110: accepted for processing, not completed) and enqueue. Otherwise one slow call turns your endpoint into the sender's timeout, which produces more retries, which makes you slower.

No timeout discipline on your own outbound calls. An unbounded HTTP client inside a handler that the sender is retrying amplifies both systems' load. Set a connect and read timeout, retry only on 5xx and transport errors, cap attempts, back off with jitter, and don't retry 4xx. This is exactly the unsafe consumption OWASP API10:2023 describes: trusting a downstream without bounding time, retries or payload size.

Assuming order. deleted arriving before updated will resurrect a record if the handler is written as a state-machine transcript. Keep tombstones, compare event timestamps or entity versions before applying, and ignore anything older than the last state you wrote.

Trusting the payload. Treat it as a hint that something changed about order_123, then GET the order. The event was authored against a state that may be three attempts and an hour old; fetching converges even when events arrive stale or duplicated. The cost is an API call per event, so budget it against their rate limits.

A dedup window shorter than the retry horizon. If the sender retries for 24 hours and you keep dedup keys for 24 hours but retain replay for 30 days, every replayed event older than a day reprocesses. Size the TTL from the sender's published retry schedule plus your replay window, and say so in the docs.

Wrong status codes. 2xx once accepted; 5xx when you want a retry; 4xx for a payload you can never process so the sender stops burning attempts on a poison event.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-25

How would you decide whether a webhook receiver should process events synchronously or through its own queue?

Answer

Acknowledge fast, always: verify the signature, write the event down, return 2xx. Everything after that is the real question, and it comes down to three numbers: the p99 duration of the work, whether the work calls anything outside the process, and the peak arrival rate.

My rule:

  • p99 under ~200 ms, no network calls, retryable from the stored row → process inline. One less system, and the sender's retry is a fine safety net.
  • Any call to a third party with a timeout of a second or more → queue. You are now holding a request slot open for someone else's latency.
  • λ × p99 exceeds the concurrency you can afford to hold open → queue. This is the one people miss.
SignalInlineQueue
p99 handler duration< 200 ms≥ 1 s, or dominated by a remote call
External callsnonepartner API, email, another service
Peak arrival ratea few per secondbursts where λ × p99 exceeds worker count
Retry ownershipsender's retry is enoughreceiver must retry on its own schedule
Ack pathsame requestsame request; enqueue is the last step

The arithmetic that decides it. Little's Law: in-flight requests = arrival rate × latency. Take a handler that verifies an HMAC (0.2 ms), inserts a row (2 ms), and calls a partner API (p50 120 ms, p99 1.2 s). At 200 events/s:

  • Inline: 200 × 0.125 s = 25 concurrent requests at p50, and 200 × 1.3 s = 260 at p99.
  • Ack-only path (verify + insert + enqueue, ~3 ms): 200 × 0.003 s = 0.6. One worker.

That is the whole argument. Inline, your web tier's concurrency is sized by someone else's p99.

The burst trace. A provider is down for 30 minutes at 5 events/s, so 9,000 events are pending. Stripe retries failed deliveries with exponential backoff for up to three days (Stripe's webhook docs), which spreads that out, but a provider on a fixed short retry schedule, or one whose backlog is released when it recovers, delivers it as a spike. 9,000 events over 60 s is 150/s. Inline at p50 that needs 19 in-flight requests; at p99, 195. Requests that sit behind a saturated pool blow the sender's timeout, API Gateway's REST integration timeout is a hard 29 s, the sender sees a non-2xx and retries, and the retries land on an endpoint that is already behind. That loop is how a webhook receiver takes an outage.

Persist before you ack, either way. GitHub does not automatically redeliver failed webhook deliveries, so a dropped event is gone unless someone redelivers it by hand. Write the event and the enqueue intent in one transaction, the outbox pattern, so a crash between them cannot lose it:

Python
# Python 3.12, FastAPI + psycopg 3
@app.post("/webhooks/stripe")
def receive(request: Request):
    raw = request.body()
    event = stripe.Webhook.construct_event(
        raw, request.headers["Stripe-Signature"], SECRET)   # HMAC-SHA256, 300 s tolerance
    with conn.transaction():
        conn.execute("INSERT INTO events (id, payload) VALUES (%s, %s)"
                     " ON CONFLICT DO NOTHING", (event["id"], raw))
        conn.execute("INSERT INTO outbox (event_id) VALUES (%s)"
                     " ON CONFLICT DO NOTHING", (event["id"],))
    return Response(status_code=200)   # ack before any processing

A relay then publishes outbox rows to the queue. ON CONFLICT DO NOTHING on the provider's event id is the dedupe, and it is needed regardless of architecture: SQS standard queues are at-least-once, and Stripe retries.

Failure modes to name. A poison event that always fails blocks the head of the queue: set a max receive count and a dead-letter queue (SQS redrive policy), and alert on DLQ depth. A message whose processing outruns the visibility timeout is redelivered and processed twice: SQS defaults to 30 s, max 12 hours, and AWS recommends at least 6× the consumer's timeout for Lambda event sources. And a silent backlog looks healthy if you only alert on error rate: watch queue depth and the age of the oldest message, not just 5xx counts.

What does not change either way: verify the signature, dedupe on the event id, return the right status code. A queue moves where the work happens; it removes none of that.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

What happens when a webhook receiver is much slower than the event rate?

Answer

The 90-second answer. A backlog forms, and the first thing to establish is whether it is a spike or a sustained mismatch, because only one of those needs action. Measure arrival rate against drain rate over a window. If the receiver drains 40 events/s and you emit 120/s, the backlog grows 80/s: 288,000 events an hour, roughly 288 MB at 1 KB per event. That is not a spike, and it will not drain on its own. Then, in order: isolate the receiver so its backlog cannot starve other subscribers, tell the receiver (they usually do not know), offer batching or coalescing, bound the backlog with a defined overflow policy, and check whether your own event volume is sane. A receiver that cannot keep up is usually a symptom, of their inline processing or of your event design, not purely a capacity problem on their side.

The mechanism. The backlog is a queue with an arrival rate and a service rate. Spikes are what the queue is for; a sustained mismatch means the queue is a buffer on a losing race, and its only outcomes are unbounded growth or a ceiling you chose in advance. The most common root cause is a receiver that does its work before acknowledging: the sender's request times out, the sender retries, and the receiver now does the same work twice while falling further behind. Stripe's webhook docs say exactly this: return a 2xx before any complex logic that could cause a timeout.

Ack-first, with a bounded queue (Python 3.12, stdlib only; figures below are a labelled hypothetical):

Python
import queue, threading, time

q = queue.Queue(maxsize=10_000)          # the ceiling

def handle(payload):                     # the slow part: 250 ms
    time.sleep(0.25)

def worker():
    while True:
        payload = q.get()
        try:
            handle(payload)
        finally:
            q.task_done()

threading.Thread(target=worker, daemon=True).start()

def webhook(request):
    try:
        q.put_nowait(request.json)       # ~0 ms
    except queue.Full:
        return 429, {"Retry-After": "5"} # backpressure, not silence
    return 200, b""                      # ack before processing

Trace it: one worker at 250 ms/event drains 4 events/s. At 120 events/s inbound, the queue fills 10,000 slots in 10,000 / (120 − 4) ≈ 86 s. From then on every delivery gets 429 with Retry-After: 5, and the sender backs off instead of hammering. The failure mode has moved from "sender times out and duplicates work" to "we own a bounded backlog", which requires idempotency keys, because a crash between the 200 and handle() loses the event.

Levers, with the knobs that implement them:

LeverConcrete knobEffect
Isolationone queue/worker pool per subscriber (e.g. an SQS queue per endpoint)one slow receiver cannot starve the rest
BackpressureHTTP 429 + Retry-After (RFC 6585 §4)sender slows down instead of retrying immediately
Batchingup to N events per POSTamortises per-request overhead
Coalescinglatest state per resource key onlyvolume drops to distinct resources, not events
CeilingSQS retention defaults to 4 days (max 14); RabbitMQ x-max-length with x-overflow: reject-publish-dlxbacklog has a hard limit and a defined overflow

Failure modes to name. If the receiver is a Kafka consumer, the metric is consumer lag, and max.poll.interval.ms defaults to 300000 ms: a batch that takes longer than that evicts the consumer and triggers a rebalance, which makes the backlog worse, not better. A sender that ignores Retry-After turns 429s into a retry storm. Coalescing silently discards intermediate states, so it is only safe when consumers want current state. And a ceiling that drops events without notification converts a visible backlog into invisible data loss: decide the overflow policy before you need it, and document it. Finally, check your own side: if one receiver is drowning, others may be close, and the events may simply be too granular.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-6

How would you handle webhook event ordering?

Answer

The 90-second answer

Ordering isn't guaranteed, and you can't buy it back on the sender side. So I'd design receivers to be order-insensitive and give them the two things that make that possible: a per-resource version on every event, and full current state rather than a delta. Where a receiver genuinely can't tolerate reordering, a state machine with illegal transitions, it detects the gap and re-reads the resource from the API.

Why the sender can't fix it

Serialising delivery per receiver (send N, wait for the 2xx, send N+1) gives ordering only while nothing fails. One slow receiver stalls its own queue; one that's down blocks everything behind it for the whole retry window. Stripe retries failed deliveries for up to three days in live mode, so a receiver that's down for an hour has an hour of events queued behind a single failure.

Retries reorder regardless. Take a hypothetical backoff of 1 s, 2 s, 4 s, 8 s, 16 s, 32 s, 64 s: event 1 fails at t=0 and finally succeeds at t=127 s, while events 2 through N were delivered at t=0.1 s, 0.2 s, and so on. Event 1 lands two minutes after event 2. A receiver-side buffer can't fix that either: you'd need to know the reorder window in advance, and 5 s of buffering does nothing against a 127 s tail.

What the receiver does instead

Make the write conditional on the version, so out-of-order and duplicate deliveries both collapse to a no-op:

Python
# Python 3.12, psycopg 3, Postgres 16
APPLY = """
INSERT INTO resources (id, version, state)
VALUES (%s, %s, %s)
ON CONFLICT (id) DO UPDATE
  SET version = EXCLUDED.version, state = EXCLUDED.state
  WHERE resources.version < EXCLUDED.version
"""

def apply_event(conn, event):
    cur = conn.execute(APPLY, (event["resource_id"], event["version"], Json(event["state"])))
    return "applied" if cur.rowcount else "stale"

Trace four deliveries for ord_123 arriving as v5, v7, v5, v7:

deliveryrow beforeconflict clauserowcountresultrow after
v5noneINSERT1appliedv5
v7v55 < 7 → UPDATE1appliedv7
v5v77 < 5 false0stalev7
v7v77 < 7 false0stalev7

Final state is v7 whichever order they arrive in, and the duplicate is free. The WHERE on DO UPDATE is what makes it atomic: a read-then-write check races under concurrent deliveries.

Getting the version right

Assign it inside the transaction that mutates the resource, not at send time. Two workers emitting concurrently can otherwise stamp versions that don't match the state they carry. Use a monotonic per-resource counter, not a wall-clock timestamp: two hosts writing 5 ms apart can have skewed clocks and invert the order. A global counter is also wrong: events for different resources interleave, so a gap in the global sequence is normal, not a lost event.

When the receiver needs order

Detect a gap (event.version > stored.version + 1), then fetch the resource from the API and jump straight to the current version. Bound the wait: if the gap is older than the sender's retry window, three days for Stripe, the event is never coming, so fetch rather than wait. Alert on gap age and on the stale-event rate; a rising stale rate means the sender is retrying more than you think.

What to document

State that events may arrive out of order and duplicates are possible, name the version field, and say the API is the source of truth. A consumer who assumes ordering builds something that passes in testing and corrupts state under load, and it looks like your bug.

Named precedents

Stripe events carry id and created and are explicitly not ordered; GitHub sends a unique X-GitHub-Delivery GUID per delivery with no ordering guarantee; SQS FIFO gives ordering per MessageGroupId with a 5-minute MessageDeduplicationId window; Kafka gives ordering per partition, so you key by resource id. All of them push the ordering decision to the consumer.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-2

How would you design webhook delivery to be reliable?

Answer

Core answer. Make the event durable before the network call, deliver it from a worker that retries on a schedule, and treat each receiver's endpoint as an untrusted dependency you isolate and observe. Everything else follows from those three.

1. Write the event in the same transaction as the business change (outbox).

SQL
BEGIN;
INSERT INTO orders (id, total_cents) VALUES ($1, $2);
INSERT INTO webhook_outbox (id, endpoint_id, event_type, payload, next_attempt_at)
VALUES (gen_random_uuid(), $3, 'order.created', $4, now());
COMMIT;

If the event only exists in memory during the HTTP call, a restart loses it. The outbox makes delivery a retryable background task instead of a side effect of the request. Workers claim rows without blocking each other:

SQL
UPDATE webhook_outbox
SET status = 'in_flight', attempts = attempts + 1
WHERE id IN (
  SELECT id FROM webhook_outbox
  WHERE status = 'pending' AND next_attempt_at <= now()
  ORDER BY next_attempt_at
  FOR UPDATE SKIP LOCKED
  LIMIT 100
)
RETURNING *;

2. Retry on a bounded schedule with jitter. Eight attempts over roughly 31 hours:

attemptdelay after previouscumulative
10 (immediate)0
210 s10 s
330 s40 s
42 min2 min 40 s
510 min12 min 40 s
61 h1 h 12 min
76 h7 h 12 min
824 h31 h 12 min

Apply full jitter, sleep random(0, delay), because a receiver with 10,000 queued events would otherwise get all of them at the same instant on every retry, exactly when it is already struggling.

3. Classify the response; don't retry blindly.

ResponseRetry?Action
2xxnomark delivered
408, 429yesretry, honour Retry-After
5xx, connection refused, DNS failure, TLS erroryesback off
timeout (> 10 s)yesback off; expect a duplicate
400, 401, 403, 404, 422nodead-letter now, notify
410 Gonenodisable the subscription
3xxnomisconfiguration; alert

A 400 fails identically forever, so retrying it just burns the window. A 410 means the endpoint is permanently retired.

4. Bound every attempt. Connect timeout 2 s, total request timeout 10 s. A receiver that takes 30 s blocks a worker and will likely time out on its own side anyway, producing a duplicate.

5. Circuit-break per endpoint. 20 consecutive failures, or an hour of failures, opens the circuit for 5 minutes; a single half-open probe decides whether to close it. Without this, one dead endpoint, usually a large customer's, eats shared worker capacity indefinitely.

6. Isolate receivers. A per-endpoint concurrency cap (10 in flight) and a per-endpoint queue, so one slow receiver cannot starve the workers everyone shares.

7. Sign, and make it idempotent. HMAC-SHA256 over the raw request body with a per-endpoint secret, sent as X-Webhook-Signature: t=<unix>,v1=<hex>; reject if |now - t| > 300 s. Delivery is at-least-once, so include a stable event id and document that receivers must dedupe on it.

8. Dead-letter and tell someone. After the window, stop and notify: email plus a dashboard entry, with replay. Silent dropping is the worst outcome: the receiver's data is wrong and neither party knows.

9. Give the consumer a delivery log. Attempt number, status code, latency, and the response body truncated to 1 KB, with self-service replay. That answers "did you send it" and "send it again", which is most of the webhook support load.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17

How do webhooks interact with the sender's own transaction boundaries?

Answer

The short answer: there is no ordering of "write to the database" and "send the webhook" that is safe, because they are two systems with no shared transaction. The fix is to make the webhook intent part of the same transaction as the business change, the outbox pattern, and let a separate process deliver it.

Why neither ordering works

ordercrash windowresult
commit, then POSTbetween COMMIT and the HTTP callorder 42 is confirmed; no webhook ever fires; the consumer never learns
POST, then commitbetween the 200 OK and COMMITconsumer receives order.confirmed for order 42, then the transaction rolls back; it acts on an order that does not exist

Retrying the POST doesn't help the first case (you don't know it's needed) and makes the second worse.

The outbox transaction

SQL
BEGIN;
UPDATE orders SET status = 'confirmed' WHERE id = 42;
INSERT INTO outbox (id, aggregate_id, topic, payload)
VALUES (gen_random_uuid(), 42, 'order.confirmed', '{"order_id":42}');
COMMIT;

One transaction, one commit. Either both rows are visible or neither is. The webhook is now a database fact, not a network side effect.

The gotcha: if your ORM is in autocommit mode, that INSERT lands in its own transaction and you are back to dual-write. The insert has to be inside the same BEGIN.

Delivery

Claim, send, mark: three steps, two transactions:

SQL
-- 1. claim (short transaction)
UPDATE outbox
SET claimed_at = now(), claimed_by = 'worker-3'
WHERE id IN (
  SELECT id FROM outbox
  WHERE published_at IS NULL AND claimed_at IS NULL
  ORDER BY id
  LIMIT 100
  FOR UPDATE SKIP LOCKED
)
RETURNING id, topic, payload;

-- 2. POST each row outside any transaction, HMAC-SHA256 signature over
--    timestamp + body, 10 s timeout, 5 attempts, backoff 1/2/4/8/16 s

-- 3. mark
UPDATE outbox SET published_at = now() WHERE id = ANY($1);

FOR UPDATE SKIP LOCKED (Postgres 9.5+) lets N workers run without stepping on each other: each locks a disjoint batch and skips rows another worker holds.

Trace of the crash window (hypothetical timings):

  • t=0.000: COMMIT. Row 9001 exists, published_at NULL.
  • t=0.050: worker-3 claims 9001, commits the claim.
  • t=0.060: POST returns 200.
  • t=0.070: worker-3 is killed before step 3.
  • t=60.070: reaper clears the stale claim: UPDATE outbox SET claimed_at = NULL WHERE published_at IS NULL AND claimed_at < now() - interval '60 seconds'.
  • t=60.100: next poll re-sends 9001.

The consumer sees event 9001 twice. That is at-least-once, which webhook receivers already have to handle: dedupe on the event id. The pattern adds no new requirement; it only removes the loss case.

Operational numbers

  • Partial index so the poller doesn't scan published rows: CREATE INDEX CONCURRENTLY outbox_pending_idx ON outbox (id) WHERE published_at IS NULL;
  • Poll interval is your latency floor: 100 ms polling adds ~100 ms p99 to webhook delivery; 1 s adds ~1 s. LISTEN/NOTIFY (payload under 8 kB, delivered at commit) can wake the poller instead of a tight loop.
  • Retention: a 300-byte row at 1,000 events/s is ~300 KB/s, ~26 GB/day. Delete published rows in batches, DELETE FROM outbox WHERE published_at < now() - interval '7 days', or the table and its indexes grow without bound.
  • Ordering: ORDER BY id only holds with one worker. For per-aggregate order with N workers, shard on hashtext(aggregate_id) % N and run one worker per shard.

CDC instead

Reading the replication log (Debezium on Postgres with wal_level = logical and a replication slot, or the MySQL row binlog) captures every change with no application code and no polling. Two costs: more infrastructure, and it captures changes, not intentions. The event shape follows the row shape, so a column rename silently changes your public payload. For webhooks, where the payload is a contract with third parties, I'd take the outbox. Also watch the slot: if the CDC consumer stalls, Postgres retains WAL and the disk fills.

Retries

Because the outbox row is inside the transaction, a retried transaction (serialization failure, deadlock) rolls back its outbox row too. No spurious event. That is the boundary question answered: the event's lifetime is the transaction's lifetime, and delivery is a separate, at-least-once concern.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

How would you decide which events a webhook system should emit?

Answer

Ask three questions of every candidate event. Does a consumer's workflow branch on it? Is it a domain fact rather than an internal transition? Does its volume justify per-event delivery? Emit what passes all three; batch or export the rest.

Assumptions: at-least-once HTTP POST delivery, per-subscriber filtering by event type, 3 retries with exponential backoff, 1 KB payloads, 30-day delivery-log retention. The volumes below are a hypothetical order platform, labelled as such.

Work the catalogue as a table before writing any code. Hypothetical daily volumes:

candidateevents/daysubscribersdeliveries/dayverdict
order.placed40,0006240,000emit
order.shipped38,0004152,000emit
order.cancelled2,000510,000emit
order.updated (coarse)120,0006720,000reject
cart.item_added900,0001900,000reject
page.viewed12,000,0000 today0reject

The coarse order.updated costs 720,000 deliveries/day against 402,000 for the three facts it replaces: 1.8× the traffic, and every consumer must call GET /orders/{id} to find out what actually changed. At a 20 ms p50 that is 720,000 × 0.02 s = 14,400 s, about four hours of server time per day, plus 720,000 extra API calls against your own rate limits. cart.item_added is 2.2× the entire order catalogue for a single subscriber; it belongs in a nightly export. page.viewed is the one that kills you: zero subscribers today, but the first one to sign up turns it into 12M deliveries/day, 12× the whole current catalogue.

Price the retries, not just the first attempt. At 3M first attempts/day, a 5% transient failure rate and 20% failure on each retry gives 150,000 + 30,000 + 6,000 = 3,186,000 total attempts: 6.2% overhead, 3.19 GB/day of egress, roughly 96 GB/month. That is the number that decides whether a marginal event is worth emitting.

Failure modes and how you see them. A subscriber down for six hours queues ~750,000 deliveries at 125k/hour; when it recovers the backlog drains at 3× arrival rate and takes about two hours, and if the endpoint is slow rather than down you exhaust your own connection pool first. A poison event that breaks one consumer's parser blocks the partition behind it under ordered-per-key delivery. A required field added to order.placed breaks strict parsers. Watch per-subscriber delivery success rate, p99 delivery latency, queue depth, and the age of the oldest undelivered event: the last one catches the poison case before the queue depth does.

The asymmetry drives the decision. Adding an event is a deploy; removing one is a breaking change with a deprecation window: dual-emit old and new for 90 days, then stop. So the threshold for emitting is: at least two independent consumers branch on it, it names a domain fact, and its delivery volume stays under roughly 10% of the catalogue. Anything below that line goes into a batch export or a digest, and saying so is cheaper than emitting it.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13

How would you evolve a webhook event schema without breaking consumers?

Answer

What a strong candidate says first. Assume the consumers are third parties you don't control and can't see. The answer is: make the contract tolerant before you have consumers, classify every change as additive or breaking, and version only when you must. Then measure who is on which version: outbound delivery tells you exactly that.

1. Write the tolerance rule into the contract before the first consumer.

Two sentences in the docs: receivers must ignore unknown fields and unknown event types; the producer may add optional fields and new event types at any time. Everything additive is then free. Retrofitting this later means asking every consumer to change, which is the thing you were trying to avoid.

2. Classify the change.

ChangeBreaking?Why
Add optional fieldNoTolerant receivers ignore it
Add new event typeNoOnly if receivers ignore unknown type
Add value to an enumUsuallyBreaks receivers with an exhaustive switch and no default
Remove or rename a fieldYesReceiver reads a missing key
Change a type (int → string)YesParse error, usually loud
Change meaning, keep shapeYes, silentlyNo error anywhere; every consumer misreads
Set additionalProperties: falseYesTurns every future addition into a break

The silent one is the dangerous one. amount changing from cents to dollars, or status gaining a value a consumer's else branch treats as success: nothing throws, and you find out from a customer.

3. Version the payload, not the URL.

Put the version in the payload and let each endpoint subscribe to one. Stripe does exactly this: an endpoint is pinned to an API version, and every Event object carries api_version telling you which version rendered it. GitHub's equivalent is the X-GitHub-Event header plus an action field, with X-GitHub-Delivery as the idempotency key.

JSON
{
  "id": "evt_1P8xQ2",
  "type": "invoice.paid",
  "api_version": "2024-06-20",
  "created": 1719273600,
  "data": { "object": { "id": "in_1P8xQ2", "amount_paid": 4200, "currency": "usd" } }
}

Consumer side, the tolerant handler is the whole contract:

Python
# Python 3.12
HANDLERS = {"invoice.paid": on_invoice_paid}

def handle(raw: bytes) -> None:
    evt = json.loads(raw)
    handler = HANDLERS.get(evt["type"])
    if handler is None:
        return                       # unknown type: ignore, do not 500
    handler(evt["data"]["object"])  # read fields you know; ignore the rest

4. When you must break, dual-send and measure.

Render the same event in both shapes and route by the endpoint's pinned version. Because delivery is outbound, you know exactly which endpoints are on the old version: better information than an inbound API gives you.

Worked trace: 240 endpoints, 3 pinned versions. You rename amount_paid → amount.total.

  • Day 0: both fields populated for every endpoint. Zero consumer changes required.
  • Day 0–90: dashboard shows endpoints per version. 240 → 31 still on the old version after 90 days.
  • Day 90: email those 31 integration owners by name, with the date.
  • Day 180: stop populating amount_paid for endpoints on the new version; old-version endpoints keep it.

5. Test compatibility in CI.

Keep a corpus of recorded payloads from the previous version and replay them against the current schema definition. With JSON Schema, a checker flags a removed required field or a tightened additionalProperties before it ships. With Avro or Protobuf, a schema registry's BACKWARD compatibility mode does the same check at registration time.

The asymmetry: an API break throws in the consumer's logs the moment they deploy. A webhook break produces silently wrong data in someone else's system, discovered weeks later and reported as your bug.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-3

How would you secure webhooks, in both directions?

Answer

What a strong candidate says first. Webhooks cross a trust boundary in both directions, and the two directions fail differently. Inbound, the receiver must prove the request came from the sender and is fresh. Outbound, the sender must not let the consumer's chosen URL turn it into a proxy into its own network. Signing solves the first and does nothing for the second.

Receiver: authenticate the request.

Sign the raw body with HMAC-SHA256 under a 256-bit secret from a CSPRNG. Three details are where implementations break:

  1. Sign the raw bytes before parsing. Re-serialising JSON changes key order, whitespace and float formatting, so the digest no longer matches.
  2. Compare in constant time. == on a hex digest short-circuits at the first differing byte; an attacker who can time the response recovers the expected digest one hex character at a time: 64 × 16 = 1024 guesses instead of 16^64.
  3. Put a timestamp inside the signed string and reject outside a tolerance. Stripe's default is 300 s; Slack and the Standard Webhooks spec use 5 minutes. Without it, a captured request verifies forever.
Python
import hmac, hashlib, time
from flask import Flask, request, abort

SECRETS = [b"...current...", b"...previous..."]  # two live during rotation
TOLERANCE = 300  # seconds

app = Flask(__name__)

@app.post("/webhooks")
def receive():
    raw = request.get_data()                      # raw bytes, unparsed
    hdr = request.headers.get("Stripe-Signature", "")
    parts = dict(p.split("=", 1) for p in hdr.split(","))
    ts = int(parts.get("t", 0))
    if abs(time.time() - ts) > TOLERANCE:
        abort(400, "stale")
    signed = f"{ts}.".encode() + raw
    for secret in SECRETS:
        expected = hmac.new(secret, signed, hashlib.sha256).hexdigest()
        if hmac.compare_digest(expected, parts.get("v1", "")):
            break
    else:
        abort(400, "bad signature")
    return "", 204

hmac.compare_digest is the constant-time primitive in Python; Node has crypto.timingSafeEqual, Go has hmac.Equal.

Trace the freshness check: header t=1700000000, receiver clock 1700000312. |1700000312 − 1700000000| = 312 > 300, so it returns 400 before touching the signature. At 1700000299 the diff is 299 and it proceeds.

Real schemes differ in ways that matter.

ProviderHeaderSigned stringReplay window
StripeStripe-Signature (t=,v1=){t}.{raw_body}300 s default
SlackX-Slack-Signaturev0:{ts}:{raw_body}5 min
GitHubX-Hub-Signature-256raw bodynone
ShopifyX-Shopify-Hmac-Sha256 (base64)raw bodynone
Standard Webhookswebhook-signature{id}.{ts}.{body}5 min recommended

GitHub and Shopify sign no timestamp, so replay protection has to come from deduplicating the delivery ID (X-GitHub-Delivery, a UUID) in a store with a TTL at least as long as your retry window.

If you control both ends, sign asymmetrically (Ed25519, public key published at a JWKS URL) so a compromised receiver cannot forge outbound events.

Sender: the direction people miss. The consumer supplies the destination URL, so the sender makes HTTP requests to an address the consumer chose. That is SSRF with the sender as confused deputy; the classic target is the cloud metadata service at 169.254.169.254.

Validate the resolved IP, not the hostname string, and re-validate on every redirect hop:

Python
import ipaddress, socket

BLOCKED = [ipaddress.ip_network(n) for n in (
    "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",
    "198.18.0.0/15", "224.0.0.0/4", "240.0.0.0/4",
    "::1/128", "fc00::/7", "fe80::/10", "::ffff:0:0/96",
)]

def check(host):
    ips = {ipaddress.ip_address(i[4][0])
           for i in socket.getaddrinfo(host, None, proto=socket.IPPROTO_TCP)}
    for ip in ips:
        if any(ip in net for net in BLOCKED):
            raise ValueError(f"blocked {ip}")
    return ips

The check is only useful if you then connect to the IP you checked. A hostname can resolve to a public address for the validation lookup and to 169.254.169.254 for the connection lookup: DNS rebinding, with the record's TTL as the attacker's window. Pin the resolved IP and set the Host header and TLS SNI to the original name.

Also: require HTTPS, cap redirects at 3 and re-check each hop, connect timeout 2 s and total 10 s, cap the response body (64 KB is generous for a webhook ack), and never return the response body to the consumer. That turns the sender into a read proxy for internal services.

Both sides. The receiver validates the signature and then validates the content: a valid signature proves origin, not that amount is sane. The sender should send the minimum data the event needs, because payloads get logged by receivers and land in places neither party controls.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

How would you handle secrets and signature verification for many webhook consumers?

Answer

Per-endpoint secret, encrypted at rest, two valid at once.

One secret per consumer endpoint. A shared secret lets any consumer forge events to every other, and one leak compromises the whole fleet.

Generate it server-side, show it once at creation, and store it encrypted: HMAC signing needs the plaintext back, so hashing is not an option. Envelope-encrypt with a KMS data key (AES-256-GCM), decrypt once at process start and cache in memory. A KMS call per event adds a network round trip and burns request quota; you sign thousands of events a second and the crypto itself is single-digit microseconds for a 1 KB body.

Rotation without downtime means two secrets valid simultaneously. Stripe's header carries multiple signatures for exactly this: Stripe-Signature: t=1735689600,v1=<sig_old>,v1=<sig_new>. The consumer adds the new secret, you start emitting both, they drop the old one. Without an overlap window, rotation requires a synchronized deploy on both sides, which means it never happens.

Sign the timestamp, not just the body. Stripe signs {t}.{raw_body} and its libraries default to a 300-second tolerance; Slack signs v0:{timestamp}:{body} with the same 5-minute window. Without a timestamp inside the signed payload, a captured request replays forever.

Python
# Python 3.12, Flask
import hmac, hashlib

TOLERANCE = 300  # seconds

def verify(secret: bytes, header: str, raw_body: bytes, now: int) -> bool:
    # header: "t=1735689600,v1=9f2c..."
    try:
        parts = dict(p.split("=", 1) for p in header.split(","))
        t = int(parts["t"])
        v1 = parts["v1"]
    except (ValueError, KeyError):
        return False
    if abs(now - t) > TOLERANCE:
        return False
    signed = str(t).encode() + b"." + raw_body
    expected = hmac.new(secret, signed, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, v1)

Trace it with secret = b"whsec_test", raw_body = b'{"id":"evt_1","type":"invoice.paid"}' (36 bytes), t = 1735689600. The signed bytes are b'1735689600.{"id":"evt_1","type":"invoice.paid"}', 47 bytes.

nowabs(now - t)branchresult
1735689700100within tolerance, digest matchesTrue
1735689901301tolerance checkFalse, no hashing done
1735690000 (replay)400tolerance checkFalse
1735689700, body re-serialized via json.dumps100digest differsFalse

Row 4 is the failure that shows up in production: the receiver parses the body, re-serializes it, and hashes the result. Key order and whitespace change, the digest differs, and every request 401s. Hash the raw bytes the framework received, before any parsing.

Constant-time comparison. hmac.compare_digest in Python, crypto.timingSafeEqual in Node, hmac.Equal in Go. A == on the hex string leaks the matching prefix length through timing.

Asymmetric is worth offering alongside, not instead.

HMAC-SHA256Ed25519
consumer holdsthe secret: can forgepublic key: cannot forge
signature size32 bytes64 bytes
rotationtwo valid secrets during overlappublish a new public key
integrator familiarityhigh, most examples are HMAClower

Ed25519 removes per-consumer secret storage and the leak risk on their side, at the cost of unfamiliarity. Ship HMAC as the default and document both.

Failure modes to name. Secret pasted into a log line or an error report: grep for the prefix and alert. No timestamp in the payload: replay is undetectable. Tolerance set to zero or unbounded: either every slow delivery fails or replay protection is gone. Rotation with no overlap: the consumer's verification breaks at deploy time, not at leak time.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-15

How would you support replay of webhook events?

Answer

Assume we're the producer and the consumer is a third party we don't control. Replay means re-delivering events we already sent, or failed to send, on the consumer's request, without a support ticket. Four things decide whether it works: events are retained under a stable id, replay is self-service and scoped, re-delivery is paced, and the consumer can tell a replay from a live event.

Retention. Append-only events table, plus one deliveries row per (event, endpoint, attempt). Keep 30 days. At 1M events/day and a 2 KB payload that's 2 GB/day, ~60 GB of payload over the window: call it 100 GB with indexes and delivery rows. Cost isn't the argument; usefulness is. Publish the window, because a consumer who needs longer has to archive on their side.

Stable id. The id must be identical on the first attempt and every replay. Standard Webhooks names this webhook-id and requires it to be stable across retries; Stripe uses evt_...; GitHub uses X-GitHub-Delivery. Mint a new id on replay and the consumer's dedupe table misses it: a recovery becomes a double charge.

What the big providers actually do:

ProviderRetry windowRedeliveryId
Stripeup to 72 h in live mode, exponential backoffDashboard "Resend"; stripe events resend evt_...evt_..., signed via Stripe-Signature (t=, v1=)
GitHubno automatic redelivery of failed deliveriesPOST /app/hook/deliveries/{delivery_id}/attemptsX-GitHub-Delivery UUID
Standard Webhooksspec mandates no retry schedulen/awebhook-id stable across retries

Replay endpoint. Scope by endpoint and time range, count first, then enqueue a paced job:

Python
# Python 3.12
REPLAY_MAX_EVENTS = 500_000
REPLAY_RATE_PER_SEC = 50

def create_replay(endpoint_id, start, end, requested_rate=None):
    rate = min(requested_rate or REPLAY_RATE_PER_SEC, REPLAY_RATE_PER_SEC)
    count = db.one("""
        SELECT count(*) FROM events e JOIN deliveries d ON d.event_id = e.id
        WHERE d.endpoint_id = %s AND e.created_at >= %s AND e.created_at < %s
    """, endpoint_id, start, end)
    if count > REPLAY_MAX_EVENTS:
        raise TooLarge(count, REPLAY_MAX_EVENTS)   # consumer must narrow the range
    return db.insert("replay_jobs", endpoint_id=endpoint_id, start=start, end=end,
                     rate=rate, total=count, status="pending")

def run_replay(job):
    bucket = TokenBucket(rate=job.rate, burst=job.rate)
    for ev in db.stream("""
        SELECT e.id, e.payload, e.created_at FROM events e
        JOIN deliveries d ON d.event_id = e.id
        WHERE d.endpoint_id = %s AND e.created_at >= %s AND e.created_at < %s
        ORDER BY e.created_at, e.id
    """, job.endpoint_id, job.start, job.end):
        bucket.take()                              # blocks until a token is free
        deliver(endpoint=job.endpoint_id, event_id=ev.id, payload=ev.payload,
                idempotency_key=ev.id,
                headers={"X-Webhook-Replay": "true",
                         "X-Original-Event-Timestamp": ev.created_at.isoformat()})

Worked trace. A consumer asks for three days of events. The count query returns 412,000. At 50 events/s that's 412,000 / 50 = 8,240 s ≈ 2 h 17 min, against an endpoint sized for 100 rps of normal traffic. Without the bucket, the same 412,000 events pushed as fast as the worker can write would hit the endpoint at thousands of rps and take it down: the failure mode replay exists to prevent.

Ordering. ORDER BY e.created_at, e.id with a single worker per endpoint preserves order. Parallel workers break it, so if you need throughput, partition by entity key (order id, customer id) and keep order within a partition. If the consumer is order-insensitive (which they should be, since retries already reorder) this is a nicety.

Failure modes to name. Replay of an event older than the retention window: return a clear error, don't silently return zero. Replay while the consumer is down: the job should pause on repeated 5xx rather than burn through the range. Replay of events the consumer already processed: expected, and exactly why the id is stable. And the replay marker matters because a handler that emails "your order shipped" three days late is wrong, and only the consumer can decide that.

The design point: replay has to exist before the incident. The moment you need it is the moment you can least afford to discover events weren't retained.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-9

How would you handle a webhook endpoint that is persistently failing?

Answer

The 90-second answer. Treat a persistently failing endpoint as a routing problem, not an incident. Classify the failure from the response, stop sending at full rate, keep the events, tell the owner, and re-enable automatically when the receiver comes back. The failure mode I am designing against is one customer's broken receiver consuming shared delivery capacity and degrading everyone else's webhooks.

Classify first: the status code picks the action.

ResponseWhat it meansAction
2xxdeliveredmark delivered, reset the breaker
410 Gonereceiver says the endpoint is retired (RFC 9110 §15.5.11)disable immediately, notify, stop retrying
401 / 403rotated or wrong signing secretretry with backoff, alert the owner; do not retry forever
404URL changedretry briefly, then alert
429 / 503 with Retry-Afterreceiver is throttling or downhonour Retry-After (RFC 9110 §10.2.3), back off, do not count it as a hard failure
5xx, timeout, connection refusedreceiver is brokencount toward the breaker, exponential backoff with jitter
3xxredirecttreat as failure; do not follow redirects

Break the circuit. After N consecutive failures, stop attempting and probe once per cooldown.

Python
# Python 3.12
from dataclasses import dataclass

@dataclass
class Breaker:
    threshold: int = 5
    cooldown: float = 60.0
    failures: int = 0
    opened_at: float | None = None

    def allow(self, now: float) -> bool:
        return self.opened_at is None or now - self.opened_at >= self.cooldown

    def record(self, ok: bool, now: float) -> None:
        if ok:
            self.failures, self.opened_at = 0, None
        else:
            self.failures += 1
            if self.failures >= self.threshold:
                self.opened_at = now

Trace with threshold=5, cooldown=60: failures at t=0,1,2,3,4 each return allow True; at t=4 failures reaches 5 and opened_at=4. At t=5, allow(5) gives 5-4 < 60 → False, so the event is queued instead of attempted. At t=64, allow(64) gives 64-4 = 60 → True: one half-open probe. If that probe fails, opened_at=64 and the next probe is t=124; if it succeeds, failures=0, opened_at=None and normal delivery resumes at t=125.

Isolate the blast radius. Per-endpoint concurrency cap plus a per-endpoint queue. Worked example, hypothetical numbers: a fleet of 200 workers at 50 deliveries/s each is 10,000 deliveries/s. One customer emitting 2,000 events/s with 5 retries per event is 10,000 attempts/s: the entire fleet, for one dead receiver. With the breaker open, that endpoint costs one probe per 60 s.

Keep the events. 30 days of retention is a common choice. At 50 events/s and 1 KB per event: 4.32M events/day, about 4.3 GB/day, about 130 GB for 30 days. Replay is an API call (POST /endpoints/{id}/replay?since=...), rate-limited so recovery does not produce a replay storm, and consumers dedupe on the event id because delivery is at-least-once.

Notify and expose. Email the integration owner on the first breaker trip, not on the 500th failure. Show endpoint health, last 20 failures with status codes and timestamps, and give self-service test, replay and re-enable. Stripe's model is the reference: retries with exponential backoff for up to three days in live mode, then disables the endpoint and emails the account owner.

Recover automatically. Probe on the cooldown; on success resume delivery and offer replay of what was missed. Disable after a stated period without a success, seven days is reasonable, with notice. Requiring a support ticket to re-enable creates work on both sides.

Failure modes worth naming. A rotated secret produces 401s forever if you only retry on 5xx: alert on the 4xx share, not just the failure count. A receiver that is up half the time flaps a consecutive-failure breaker: use a rolling error rate over a window instead. Retention expiry silently drops events: surface "N events dropped" to the owner rather than deleting quietly.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14

What monitoring would you put on a webhook delivery system?

Answer

Delivery success rate, overall and per endpoint. The aggregate hides the case that matters: one large consumer failing entirely while the average looks healthy. Per-endpoint is what makes a specific problem visible.

Delivery latency from event creation to successful delivery, as percentiles. That is what consumers actually experience, and it captures queueing delay that per-attempt timing misses.

Queue depth and the age of the oldest pending event. Age is more meaningful than depth, because it maps directly to consumer impact: 'the oldest undelivered event is forty minutes old' is actionable in a way a count is not.

Retry rate and the distribution of attempts. A rising retry rate means receivers are struggling, and it consumes capacity that first attempts need.

Dead-letter rate, alarmed on any arrival. Events reaching the dead-letter queue mean a consumer's data is now wrong, and that should never pass unnoticed.

Circuit breaker state per endpoint, so an open breaker is visible rather than presenting as mysteriously absent deliveries.

Response status distribution per endpoint, which distinguishes causes: mostly 5xx means their service is down, mostly 401 or 403 means a signature or secret problem, mostly timeouts means they are processing inline.

Timeout rate, which specifically indicates receivers doing work before acknowledging: worth surfacing to them, since it also means they are processing duplicates.

Signature verification failures reported by receivers, where visible, since a spike indicates a secret rotation gone wrong.

And the consumer-facing half: everything above, scoped to their own endpoints, in their dashboard. That is monitoring as a product feature, and it is what lets them notice and fix their own problems before the data drifts, which removes far more support load than any internal dashboard does.

The alerting I would set: dead-letter arrivals, oldest-event age, and a sustained drop in overall success rate. Not per-endpoint failures, since consumers going down is routine and alerting on it trains people to ignore the channel: that belongs in the consumer's dashboard and their notification, not our pager.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-8

A consumer says they are missing webhook events. How do you investigate?

Answer

First 90 seconds

Two systems, one of them mine. Before touching anything I want three facts: the event IDs the consumer expected, the time window, and whether they're seeing zero events or a subset. "Missing" almost always means a subset, which points at a filter or a handler rather than transport.

Then the answer in one line: the delivery log tells me whether the event left my system and what the receiver said back. Everything after that is theirs.

The decision table

Delivery log showsLikely causeOwnerNext step
No attempt for that event IDEvent never generated, or subscription doesn't cover the typeMeCheck event creation; diff enabled_events against the type
401 / 403Signature verification failing at the receiverConsumerSend raw body + header; check secret rotation and clock skew
400 with a response bodyReceiver validation errorConsumerForward the body verbatim
200 in <100 ms, consumer sees nothingHandler acked, then failed asyncConsumerAsk for handler logs keyed by event ID
504 after a 30 s timeoutEndpoint processing inlineConsumerAck in <5 s, queue the work
Attempts stop, then nothingRetry window exhaustedMeReplay from the events API
200s, but the effect was revertedDuplicate delivery + non-idempotent handlerConsumerKey on the event ID

Worked example (hypothetical figures)

Consumer reports six missing invoice.paid events between 14:02 and 14:19 UTC. I pull the delivery log for their endpoint:

14:02:11  evt_1Qa  invoice.paid  200  84ms
14:05:33  evt_1Qb  invoice.paid  200  91ms
14:09:47  evt_1Qc  invoice.paid  200  78ms
14:13:20  evt_1Qd  invoice.paid  200  88ms
14:16:05  evt_1Qe  invoice.paid  200  95ms
14:19:02  evt_1Qf  invoice.paid  200  78ms

Six events, six 200s, sub-100 ms. Transport is not the problem and neither is generation. That leaves the receiver's handler. I ask for their logs keyed by evt_ ID: a worker started failing at 14:01 on a schema change, but the HTTP handler had already returned 200 and enqueued, so the failure never surfaced as a non-2xx. Fix the worker, replay the six IDs.

The counter-case is the same log with 504 after 30 s on every row: their endpoint is processing inline, and the fix is to ack fast and queue.

Signature failures

401/403 means the receiver rejects before doing any work. Usual causes: a rotated secret, a body parsed and re-serialised before verification (the HMAC is over the raw bytes), or clock skew against the timestamp tolerance. Stripe's libraries default to 300 seconds.

Python
import hmac, hashlib, time

def verify(secret: bytes, header: str, body: bytes, tolerance: int = 300) -> bool:
    parts = dict(p.split("=", 1) for p in header.split(","))
    ts = int(parts["t"])
    if abs(time.time() - ts) > tolerance:
        return False                      # rejected before any HMAC work
    signed = f"{ts}.".encode() + body
    expected = hmac.new(secret, signed, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, parts["v1"])

Trace: with t=1735689600 and a clock at 1735690000, the difference is 400 > 300, so it returns False without computing a digest. At 1735689700 it proceeds and compares. Note dict() keeps only the last v1=; if a provider sends more than one during secret rotation, the earlier ones are dropped and valid events get rejected.

Retry windows decide the fix

Stripe retries live-mode webhooks for up to three days with exponential backoff; GitHub does not retry failed deliveries at all. If the gap is older than the window, replay is the only route: stripe events resend evt_1Qa, or GitHub's redelivery endpoint POST /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}/attempts.

Check before declaring it fixed

  • Subscription filter: enabled_events doesn't include the type they expect. Cheap, common.
  • Circuit breaker still open after an earlier outage they've since fixed: deliveries are suppressed, not failed.
  • Ordering: events arrive out of order and a later state overwrites an earlier one.

Afterwards

If the consumer can't see their own delivery log, every one of these questions becomes a ticket. Exposing the log and a replay button is the highest-value thing a webhook provider ships.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10

How would you test a webhook integration, from both sides?

Answer

The 90-second answer. Two test surfaces, and they fail differently. On the receiver, the risky parts are the signature check, raw-body handling, and idempotency: all testable without HTTP. On the sender, the risky parts are retry classification, SSRF on the target URL, and isolation between endpoints: none of which surface until an incident. I'd state the provider up front, because the header names and the signed string differ per vendor: Stripe sends Stripe-Signature: t=<ts>,v1=<hex> and signs {ts}.{body} with HMAC-SHA256 over the raw bytes, 300 s tolerance; GitHub sends X-Hub-Signature-256: sha256=<hex> over the body alone, with X-GitHub-Delivery as the dedup key; Slack signs v0:{timestamp}:{body} into X-Slack-Signature with a 300 s window; the Standard Webhooks spec signs {webhook-id}.{webhook-timestamp}.{payload} into webhook-signature.

Receiver: the handler as a function of the raw body.

Python
# receiver.py — FastAPI, Python 3.12
import hmac, hashlib, time, json
from fastapi import FastAPI, Request, Response

SECRET = b"whsec_test"
TOLERANCE = 300  # seconds; Stripe's default

app = FastAPI()

@app.post("/webhooks/stripe")
async def stripe_webhook(request: Request):
    raw = await request.body()               # raw bytes, before any JSON parse
    header = request.headers.get("stripe-signature", "")
    parts = dict(p.split("=", 1) for p in header.split(",") if "=" in p)
    ts, sig = parts.get("t"), parts.get("v1")
    if not ts or not sig:
        return Response(status_code=400)
    try:
        ts_int = int(ts)
    except ValueError:
        return Response(status_code=400)
    if abs(time.time() - ts_int) > TOLERANCE:
        return Response(status_code=400)     # replay window
    expected = hmac.new(SECRET, f"{ts}.".encode() + raw, hashlib.sha256).hexdigest()
    if not hmac.compare_digest(expected, sig):
        return Response(status_code=400)
    event = json.loads(raw)
    if not store.mark_seen(event["id"]):     # idempotency key
        return Response(status_code=200)
    queue.enqueue(event)                     # ack fast, work async
    return Response(status_code=200)
Python
def sign(body: bytes, ts: int) -> str:
    return hmac.new(SECRET, f"{ts}.".encode() + body, hashlib.sha256).hexdigest()

def post(client, body: bytes, ts=None, sig=None):
    ts = ts if ts is not None else int(time.time())
    sig = sig if sig is not None else sign(body, ts)
    return client.post("/webhooks/stripe", content=body,
                       headers={"stripe-signature": f"t={ts},v1={sig}"})

BODY = b'{"id":"evt_1","type":"invoice.paid","created":1700000000}'

def test_valid(client):    assert post(client, BODY).status_code == 200
def test_tampered(client): assert post(client, BODY + b" ").status_code == 400
def test_missing(client):  assert client.post("/webhooks/stripe", content=BODY).status_code == 400
def test_garbage(client):  assert post(client, BODY, ts="abc").status_code == 400
def test_expired(client):  assert post(client, BODY, ts=int(time.time()) - 600).status_code == 400
def test_replay(client):
    post(client, BODY); post(client, BODY)
    assert store.count("evt_1") == 1

test_tampered appends one byte, so the signature no longer covers the raw body: that is the check that catches a handler which re-serialises JSON before verifying.

Out-of-order. Two customer.subscription.updated events for one subscription, delivered reversed:

arrivalevent idcreatedplan in payloadstored plan after
1evt_B1700000200freefree
2evt_A1700000100profree: evt_A is older, dropped

The handler compares event["created"] against the stored updated_at and drops the older one. Without that guard the row ends at pro, and no in-order test catches it.

Sender: classification and isolation.

receiver responseretried?why
200 / 201 / 204nodelivered
400, 401, 404, 422nopermanent; payload or config is wrong
429yesrate limited; honour Retry-After
500, 502, 503, 504yestransient
timeout / connection resetyesoutcome unknown, so retry
410 Goneno, and disable the endpointStripe's documented behaviour

The exact set is vendor-specific: read it off the provider's docs and pin it in a test, because it changes. Stripe documents retries for up to three days with exponential backoff. Worked retry budget (my schedule, not Stripe's): base 5 s, doubling, capped at 1 h. The first 10 attempts consume 5·(2¹⁰ − 1) = 5115 s ≈ 85 min; the remaining 259200 − 5115 = 254085 s at 3600 s each is ~70 more, so ~80 attempts over three days. Assert the count and the gaps, not just "it eventually arrives".

SSRF. Drive the URL validator with http://127.0.0.1/, http://169.254.169.254/latest/meta-data/ (cloud metadata), http://10.0.0.5/, http://[::1]/, http://internal.corp/ resolving to 192.168.1.10, and a public URL that 302-redirects to http://127.0.0.1/. The last two pass a naive string check. Resolve the hostname and validate the resolved IP, then re-validate on every redirect hop, or refuse redirects outright.

End to end. Run a real receiver (uvicorn on a port, or a container) and drive the sender against it. A mocked HTTP client reproduces neither the raw-body bytes, nor the header casing, nor the signature computed over the exact bytes sent. Those are where the bugs are.

Failure modes to name. Clock skew breaks the tolerance check: assert with the receiver clock 400 s ahead. A handler that does its work inline passes every functional test and blows the provider's ack budget. And a shared retry queue without per-endpoint isolation means one dead receiver stalls the rest; assert a second endpoint still receives while the first is failing.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-11

What does a good webhook developer experience look like?

Answer

The 90-second answer. Assume you're the provider and the consumer is another team or a third party whose infrastructure you can't see. The DX that matters is not the delivery mechanism: that's a POST with retries and a signature. It's the debugging surface around it: a delivery log, self-service replay, a test send, and signature docs with a working verifier. Almost every support ticket is "did you send it" or "send it again," and both become self-service once those exist.

The four surfaces that actually get used:

SurfaceWhat it removesWhat it costs you
Delivery log: attempt number, status code, latency, response body, next retry time"did you send it" ticketsstoring response bodies. Cap them (first 4 KB) and set a retention window
Replay by event ID or time range"send it again" ticketsrequires idempotency on the consumer side; replay storms
Test send to a chosen endpointhandler bugs found before go-livea flag on synthetic events so consumers can filter them
Signature docs plus a verifier in the consumer's languagethe single most common integration bugkeeping examples in sync with the scheme

Then state the guarantees as numbers, not adjectives: at-least-once, no ordering, this retry schedule, this timeout, this retention window. A consumer who assumes exactly-once and ordered delivery builds something that breaks under load and files it as your bug. Two more that pay for themselves: endpoint health in the dashboard, so a consumer notices their endpoint failing before their data drifts, and failure notifications to the integration owner rather than a generic address. Versioned event schemas with a migration path, or you break consumers on your next field change.

The signature bug, traced. The failure is verifying over the parsed body instead of the raw bytes:

Python
import json
raw = b'{"id":"evt_1","amount":100}'   # 27 bytes, exactly what was signed
json.dumps(json.loads(raw))            # '{"id": "evt_1", "amount": 100}'  -> 30 bytes

json.loads gives a dict; json.dumps re-serializes with default separators ', ' and ': ', inserting three spaces. The HMAC over those 30 bytes differs from the HMAC over the original 27, so verification fails and the consumer sees a 400 on every delivery. Fix: keep the raw body, and compare with hmac.compare_digest (Python) or crypto.timingSafeEqual (Node). A plain == leaks timing.

Concretely, Stripe's scheme is Stripe-Signature: t=<unix>,v1=<hex hmac>, HMAC-SHA256 over "{t}.{payload}", with a default 300-second tolerance; Stripe documents retries for up to three days with exponential backoff. The Standard Webhooks spec fixes webhook-id, webhook-timestamp and webhook-signature so a receiver writes one verifier for every provider that adopts it.

A retry schedule you can defend (hypothetical, tune to your volume): 8 attempts over 24 hours at 10s, 1m, 5m, 30m, 2h, 6h, 12h, 24h, then park the event in the log for manual replay. Jitter each interval by ±20% so a provider outage doesn't produce a synchronized retry wave.

When not to build this. If the consumer is a batch system, a data warehouse, or anything that already polls, a cursor-based polling API is the better call: no endpoint to host, no signature to verify, and reconciliation is free. Webhooks win when the consumer needs sub-second reaction and can host an endpoint. The deciding question is whether the consumer's reaction time matters more than their operational burden, if not, ship polling first and add webhooks later.

Failure modes to name. Silent loss when the consumer returns 200 before processing: they must ack after commit, or you need an idempotency key on your side. Replay without idempotency keys duplicating charges. A delivery log that stores full response bodies unbounded, which is how a webhook system turns into a data-retention problem.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-23

What is the operational cost of running a webhook system, and how do you reduce it?

Answer

Support is the dominant cost, not delivery. Delivery is a few hundred lines. The questions are unbounded: "did you send this", "why did it fail", "resend last week", "why am I getting duplicates", "signature won't verify".

Worked example, labelled as such: a mid-size system at 5M events/day, ~1.15 delivery attempts per event (5.75M attempts/day):

CostIllustrative monthly
Delivery compute (5.75M attempts/day at ~10 ms, ~$0.04/vCPU-hr)~$20
Delivery-log storage (60 GB at $0.023/GB-mo, plus log-query scans)~$5
Support (3,000 tickets/mo at 15 min, $60/hr loaded)~$45,000
Incident load (2 consumer-caused pages/mo, 2 engineer-hours each)~$240

Support is over 99% of the line items. That ratio is the whole argument.

State the retry schedule, don't gesture at it. Exponential backoff with a cap:

Python
def backoff(attempt, base=5, cap=3600):
    return min(cap, base * 2 ** attempt)

Trace: attempt 0 → 5 s, 1 → 10, 2 → 20, 3 → 40, 4 → 80, 5 → 160, 6 → 320, 7 → 640, 8 → 1280, 9 → 2560, 10 → min(3600, 5120) = 3600. Cumulative elapsed through attempt 10 is 8715 s ≈ 2 h 25 min. "Eleven attempts over about two and a half hours" is a sentence a consumer can build against, and it bounds your waste on dead endpoints.

Storage arithmetic. One attempt row: event id (16 B), receiver id, attempt number, status code, timestamps, response body truncated to 1 KB: is ~1 KB. 5.75M attempts/day × 1 KB = 5.75 GB/day raw; columnar plus zstd ≈ 2 GB/day; 30-day retention ≈ 60 GB. Pick the window from the replay SLA, not from disk anxiety.

The levers, in order of value:

  1. Self-service delivery log plus replay. A per-consumer view of attempts, status codes, truncated response bodies, and a replay button. This kills the "did you send it", "why did it fail" and "resend" classes. In the example above it is the difference between 3,000 and ~300 tickets/month: a one-off build against $40k/month recurring.
  2. Documented guarantees. At-least-once, unordered, the retry schedule above, and idempotency keyed on the event id. Duplicates stop being tickets once the contract says they happen.
  3. Signature examples. HMAC-SHA256 over timestamp + "." + body, with the timestamp checked against a 5-minute window to block replays. Stripe's Stripe-Signature: t=...,v1=... and GitHub's X-Hub-Signature-256 are the two conventions consumers have already seen; point at them rather than inventing a third.
  4. Circuit breaking per receiver. After 20 consecutive failures, open the circuit for 15 minutes and stop spending attempts on a dead endpoint. Honour 410 Gone: a consumer answering 410 is telling you to disable the subscription, and doing so is cheaper than retrying forever.
  5. A test facility, sandbox endpoint plus a "send test event" button, moves debugging to integration time, when it is cheapest.
  6. Fewer, better events. Every event type is a permanent contract. Emit ten well-chosen types, not forty.

Failure modes worth naming: a consumer returning 200 but never processing (only their reconciliation catches it); a retry storm after your own outage, when every receiver is retried at once. Jitter the backoff; unbounded response bodies in the log, which is why you truncate at 1 KB; and a replay button with no audit trail, which turns "resend" into "resend twice".

The framing: the POST is the easy part. If the plan is to build the POST and see how it goes, the plan is to discover the rest through incidents and support tickets, and that discovery costs more than building it deliberately.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-20

How would you introduce webhooks to an existing API that only supports polling?

Answer

Core answer (first 90 seconds): Keep polling. Webhooks are an addition, not a replacement. Existing consumers depend on polling, some cannot host a public endpoint, and polling remains the reconciliation path when webhooks miss events. Introduce webhooks as an opt-in push channel alongside polling, with a well-defined event catalogue derived from what consumers currently poll for, and a delivery infrastructure that guarantees at-least-once delivery with retries and dead-lettering. Start with a pilot, then general availability, and expect polling to continue.

Design the event catalogue from polling traffic. Analyze the polling endpoints and query patterns: which resources, which state changes, how often. For example, if consumers poll GET /orders?status=shipped every 5 minutes, emit an order.shipped event. This evidence is better than asking. A small number of events usually cover most polling traffic.

Build delivery infrastructure before exposing it. Use an outbox pattern: write events to a database table in the same transaction as the state change, then a separate publisher reads and delivers them. This guarantees no lost events if the process crashes. For delivery, use HTTP POST with a JSON payload. Sign the payload with HMAC-SHA256 and include the signature in a header, e.g., X-Hub-Signature-256 (GitHub's convention) or Stripe-Signature (Stripe's convention). Set a timeout for the receiver's response: GitHub uses 10 seconds, Stripe uses 20 seconds. If the receiver does not return 2xx within the timeout, retry with exponential backoff and jitter. A typical schedule: attempt 1 immediate, attempt 2 after 1 minute, attempt 3 after 5 minutes, attempt 4 after 30 minutes, attempt 5 after 2 hours, attempt 6 after 6 hours, attempt 7 after 24 hours. After max retries, move to a dead-letter queue and alert. Limit payload size: Stripe caps at 256 KB; GitHub at 25 MB. Document your limit.

Pilot with friendly consumers. Choose a few event types and a small number of consumers. Real traffic surfaces problems: payload shape, signature documentation gaps, timeout assumptions. Fix these while the blast radius is small.

General availability with developer experience. Provide self-service endpoint configuration, a test facility to send sample events, a delivery log showing request/response and status, signature examples in Python, Node.js, and Ruby, and documented guarantees: at-least-once, unordered, retry policy. Without these, support load will be high.

Expect polling to continue. Consumers should reduce polling frequency, not eliminate it. Reconciliation via polling is what makes the integration trustworthy. Measure adoption: if polling load does not fall, either webhooks are not trusted or they do not cover what people need.

Document the guarantees honestly. At-least-once means duplicates; consumers must be idempotent. Use event IDs. Unordered means consumers must not assume sequence. The retry policy means a receiver down for 3 days may miss events; reconciliation via polling catches that.

Worked example: retry schedule.

AttemptDelay after previousCumulative time
1immediate0
21 minute1 minute
35 minutes6 minutes
430 minutes36 minutes
52 hours2h 36m
66 hours8h 36m
724 hours32h 36m
DLQafter 7 failures~33 hours

Code: verifying a signature (Python).

Python
import hmac
import hashlib

def verify_signature(payload: bytes, signature_header: str, secret: str) -> bool:
    # signature_header looks like "sha256=abcdef..."
    algo, signature = signature_header.split('=', 1)
    if algo != 'sha256':
        return False
    expected = hmac.new(secret.encode(), payload, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, signature)

Failure modes:

  • Missed events: detected by reconciliation via polling or delivery logs.
  • Duplicate events: at-least-once delivery; consumers must be idempotent using event IDs.
  • Receiver down: retries with backoff, then DLQ. Alert on DLQ depth.
  • Signature verification failure: log and reject; alert on spike.
  • Timeout: receiver must respond within 10 seconds (or your chosen limit); else retry.

When not to use webhooks: if consumers are behind firewalls and cannot expose endpoints, or if event volume is low and polling is cheap. Polling remains the fallback.

Arithmetic: 1,000 consumers polling every 5 minutes generate 288,000 requests/day. If webhooks reduce that to 10,000 events/day, you save 278,000 requests/day. (Hypothetical figures.)

Curated: · Written: · Reviewed:

Difficulty: Hard