Ch.35: System Design: Webhooks That Survive Failure

Outline

Transcript

0:00 Take a payment service that sends one `payment.succeeded` webhook. The merchant commits the order, but its acknowledgement disappears. Call that delivery `D7A`. Because the service saw no response, it retries `D7A`, so the merchant ships twice: a duplicate shipment. Oh, that's ugly: one payment event, two shipments. Meanwhile, one failed customer builds a retry backlog that delays healthy customers. One timeout, two failures to contain. The sender never gets to know which side of that timeout it is on.

0:27 We will trace how webhooks survive through durable capture, fair delivery and receiver deduplication, then replay the outage. Now turn that incident into four functional requirements. The merchant registers an HTTPS endpoint, chooses event types and proves control before production traffic starts. When the payment commits, the platform materializes one delivery per matching endpoint. Every request carries stable event and delivery identifiers plus a signature the receiver can verify. Stable is doing a lot of work there.

0:57 A retry must reuse `D7A` so the receiver has something dependable to deduplicate. The merchant can see each attempt and its next state. Right. When support opens `D7A`, it sees the original event, endpoint and attempt history; an authorized replay keeps that lineage. But that still proves only what our side did. Durable attempts live here; idempotent effects live there. Now that the sender contract is clear, what must remain true under load? First, the non-functional requirements. Never acknowledge a source event until it is durably captured.

1:30 After capture, provide at-least-once attempts for 24 hours: duplicates are possible, loss after acceptance is not. For healthy endpoints, start 99% within 10 seconds. At our fictional peak, every event fans out to three destinations before retries even begin. And, honestly, retries haven't even clocked in yet. Do we copy the body three times? No. At 64 kilobytes, three copies would triple the large writes. Store one body, keep delivery rows small and reserve capacity so one outage cannot delay fresh traffic.

2:03 So fan-out grows the rows, not the payload writes. The URL is another boundary: it must never turn our fleet into a path toward loopback, private networks, link-local addresses or cloud metadata services. And record every attempt and replay, while payment processing and customer business logic stay outside this system. Okay, that's a much smaller contract than “exactly once.” Now let's test it against `D7A`. With the guarantees stated, follow `D7A` from payment commit to receiver. It starts beside the payment in one durable commit, then waits for a fair scheduler.

2:37 One worker signs the stored body and sends it through restricted egress. Suppose the acknowledgement never arrives. An engineer investigating `D7A` needs four answers: which endpoint, which body hash, which signing version and what did the network report? Right, because without them, honestly, a timeout is just a mystery. The delivery holds the first three. Each network try gets an attempt row with the observed result and next action. And support cannot debug “the network did something.” Those facts turn the timeout into evidence.

3:07 Two boundaries protect the path: the outbox keeps payment and delivery intent together, while the egress guard keeps an untrusted destination away from our internal network. The uncertain timeout sits between them. That gives us one path to test, starting at the first boundary. That complete map exposes the hardest boundary. `D7A` reaches the merchant, but its reply never returns. Did delivery succeed? The receiver records the shipment and writes HTTP 200, but the connection breaks before our dispatcher reads it.

3:37 The merchant committed; the sender only sees a timeout. So can the sender's database prove that remote commit? No. Honestly, from the sender's view, it is unknown. Retrying may duplicate the effect; stopping may drop the notification if the merchant rolled back. Our database cannot observe that remote transaction atomically with its own attempt record. Hold on. So our side cannot carry exactly-once across the HTTP boundary? Right. We promise durable retries under one stable delivery ID. The receiver inserts `D7A` and the shipment in one local transaction.

4:12 A retry finds the ID and returns success without shipping again. That answer sets up the sender-side question: how does `D7A` survive before the first network call? Before any network attempt, how do a committed payment and its webhook become one durable fact? The tempting version is: commit the payment, then call the webhook system. What happens if the service crashes between those writes? Yeah. Payment first can leave a payment with no webhook; webhook first can announce a payment that later rolls back.

4:42 Either ordering has a crash gap; AWS documents the transactional outbox for it. The more interesting failure comes after the handoff. Yeah, neither ordering gets to cheat the crash. So the same transaction stores the payment change and a pending outbox record. Now suppose the relay publishes and dies before moving its checkpoint. It may publish again; the stable event ID makes that repeat recognizable. Then the durable log decouples capture from customer health. One canonical event record holds the protected body reference and hash.

5:16 The planner creates delivery rows that point to it instead of cloning the body into every endpoint queue. Yes. If an event matches three endpoints, we get one event and three delivery identities. Retries add attempts under those deliveries; they do not create new business events. That distinction carries the rest of the design. That fan-out leads to a security question: why is endpoint registration dangerous if the customer only gives us an HTTPS URL? That is server-side request forgery: an attacker supplies a URL so our trusted network makes a request the attacker could not make directly. OWASP, linked in the description, explicitly treats custom webhooks as this case.

5:57 A public-looking host can later resolve privately, or redirect from public to internal. Consider a host that passes registration, then changes to `169.254.169.254`, a metadata address that may expose workload credentials. Require HTTPS, challenge ownership, reject forbidden ranges and redirects, then repeat address checks when connecting because DNS can change. Oh, that's much worse than “validate the URL once.” The callback is now a credential-theft path. So dispatchers get no general network access.

6:26 They call a restricted egress proxy that repeats the checks and pins the approved destination for that connection. Exactly. A later DNS violation disables delivery with a visible reason. An unsafe route becomes a disabled endpoint, not an incident inside our network. Once endpoint trust is enforced, the planner turns event `E7` into work for three eligible endpoints: `A`, `B` and `C`. It inserts deliveries for `A` and `B`, then crashes. How does `C` appear after restart without duplicating the first two?

6:56 Save `[A, B, C]` as a planning snapshot beside `E7` before inserting. Event ID plus endpoint ID is unique. After a crash, the planner replays that snapshot: `A` and `B` are harmless no-ops, `C` is inserted, and only after all three are durable does the log position advance. Oh, so recovery replays a guest list, not a half-finished loop. What if endpoint `D` registers during that crash? `D` is absent from the saved list, so it does not receive already-captured `E7` unless an operator authorizes a backfill. The product rule is crisp: subscription changes affect later planning, never half-finished work.

7:34 Okay, so `C` is recoverable, repeating `A` and `B` does nothing, and only then does the checkpoint move into durable scheduled work. That idempotent planning still leaves three IDs in play. Let's hear it before a retry makes the words blur together. “Webhook ID” is too vague. Think of the event as the business fact, the delivery as its addressed envelope, and each attempt as another knock at the same door. And one envelope can get several knocks. Suppose event `E7` matches endpoints `A` and `B`.

8:06 We create deliveries `D7A` and `D7B`. If `A` times out three times, those are attempts one, two and three under `D7A`. `B` can succeed independently on attempt one. The delivery starts pending, becomes in flight, and then lands in a delivered, retryable, failed or disabled state. A lease with an expiry owns in-flight work so a dead dispatcher cannot hold it forever. For `D7A`, attempt one gets a row and a lease before the send. Suppose it times out, its lease expires and another worker owns the retry.

8:39 If the first worker returns late, its older generation number cannot overwrite the newer state. The timeout result and next retry time commit together. So a timeout may cause another knock, but the retry still carries `D7A`; only the attempt ID changes. Every uncertain network try reaches the receiver under one deduplication key. Those delivery identities lead straight to the authenticity boundary. Now rotate the secret between `D7A`'s first attempt and its retry. The retry signs with version 7 while the receiver temporarily accepts version six during a bounded overlap.

9:15 Right. Each request names one signing version but never exposes the secret. But what exact bytes does the receiver verify? Suppose a proxy parses and reserializes `D7A` before verification. Whitespace or key order may change, so the signature fails. GitHub's guidance requires signing the exact raw body; our envelope also binds the version tag, timestamp and delivery key. Why include the timestamp if the body already has an event time? Event time says when the payment happened. Signature time says how long we will trust this particular request.

9:46 The receiver checks recency and compares the signature in constant time. Exactly. The overlap belongs at verification; the secret belongs in a vault, not the endpoint row. Verify the signature before parsing the body. Authenticity is still separate from idempotency. A perfectly valid duplicate can make the merchant ship twice if every valid request looks new. That authenticity limit leads to the retry decision: now, later or never? Right. The dividing line is whether another attempt could succeed without changing the endpoint. Expected `2xx` means success.

10:20 Network errors, timeouts, `5xx` and bounded `429` may clear on their own, so they can retry. Most other `4xx` needs a request or configuration change, so it stops. Yeah. Our first instinct is to retry a transient failure immediately. Imagine every dispatcher in a region making that choice after one outage: the recovery wave becomes another outage. A retry queue can become an outage copy machine. Delay attempts and randomize them with jitter so they do not wake together. Right, and adding workers just gives the copier more paper.

10:53 Exactly. Keep `D7A` in view, though: how do we stop that copier for one delivery without abandoning it? Respect `Retry-After` only within the remaining attempt budget and our maximum delay. Cap at 12 automatic attempts. A forbidden address stops; a certificate failure pauses delivery until endpoint health is revalidated. For `D7A`'s retryable timeout, randomize the next due time. If `Retry-After` points beyond its original 24-hour expiry, stop at expiry; waiting does not reset a fresh 12-attempt allowance.

11:25 So that policy bounds `D7A`. Does it buy fairness across tenants? I think the common mistake is expecting backoff to buy fairness. We still make that leap, honestly: backoff feels like fairness. But it only spaces one stream; tenant scheduling decides who gets capacity next. Next, backoff bounds one stream; fairness decides who receives capacity. How do we protect an endpoint's neighbors? Imagine tenant Red has an entire retry window of overdue work while tenant Blue just received a fresh event.

11:55 The SRE on call asks, “Why not add more dispatchers?” And could Red register many endpoints to multiply its share? Fair question. More workers raise the ceiling, but they do not decide whose work gets the next slot. Hierarchical fairness means choosing a tenant first and an endpoint inside that tenant second. For intuition, picture 10 eligible slots: Red's quarantined endpoint gets one recovery probe while healthy tenants can fill the other nine. Then selection returns to another eligible tenant instead of draining Red's backlog. Oh, that's the fairness trick.

12:31 Red cannot buy more share by registering more endpoints, and separate fresh and retry pools preserve room for new work. When Red's recent failures cross a threshold, its endpoint moves into quarantine; successful probes reopen it gradually. Right. Fairness is not a queue label; healthy queue age is how we prove it. Retry volume divided by new volume shows amplification. If healthy age rises, reserve more capacity for fresh work or reduce retry shares before adding blind global concurrency. That's the test: rising wait time for Blue means the policy is failing.

13:04 Broken endpoints still probe; healthy customers keep moving. How much ordering can that throughput afford? That fair scheduler raises one final contract question. A customer can reasonably ask, “If you call this a durable queue, why did event two arrive before event one?” Not by default. A retry can delay event one while event two succeeds. Take account `42`: if a customer needs order within that account, offer an optional key, hash it to one partition and allow only its next delivery to advance. If the first delivery keeps failing, later updates for account `42` wait while account `43` continues.

13:41 Who clears that blockage? When the retry window closes, mark the key blocked and require an explicit operator release or replay. Never silently jump the line. Oof. So ordering is permission for one bad event to block its whole key. That's the visible product tradeoff: sequence per key or maximize throughput. I think the API has to make that choice explicit. That ordering choice leads to operator replay. Take an operator returning on day 10. The UI says, “history available, payload expired.” Can I resend it?

14:15 No. History can outlive the request body. Before payload expiry, automatic retries and ordinary manual redeliveries reuse the original delivery ID, so receiver deduplication remains safe. Yeah. Same addressed envelope while the body exists, with a new operator record beside it. Require a reason, actor and scope. For bulk replay, show the estimated count, rate-limit the run and revalidate the endpoint first. Yeah, day 10 is frustrating, but inventing a body would be worse. Our policy lets metadata outlive the encrypted payload.

14:46 The history shows outcomes and redacted fingerprints, never secrets or arbitrary response bodies. So replay is a governed action, not a fresh business event. After payload expiry, the answer is simple: explain yes, resend no. With replay bounded, return to the complete map at the failure that matters. The payment is already captured and planning has produced one merchant delivery, `D7A`. Now its response disappears. Okay, but does `D7A` come back as the same delivery? It does. The scheduler selects `D7A` through the merchant's tenant and endpoint lane.

15:18 The signer attaches a current timestamp, `D7A` itself and an HMAC. The network filter re-resolves the public destination and blocks any route toward internal networks. The receiver commits the shipment, but its HTTP response disappears. Our ledger records a timeout, then the retry scheduler adds a jittered attempt that reuses `D7A`. When it comes back, the receiver finds `D7A` already committed and returns the original result instead of shipping again. Right, so `D7A` can repeat without a second shipment.

15:48 Meanwhile, Red's failed endpoint enters quarantine and its retries receive a capped share. Blue's fresh deliveries keep moving, so one outage does not rewrite everybody's latency. If an operator redelivers later, the operator record stays linked to `D7A` and names who authorized it. Every attempt is explainable, but the remote commit stays unknown unless the receiver confirms through its own idempotent result. Now we can see the outage contained without an exactly-once claim. So neither side gets magic. What does each side actually own?

16:20 The sender owns durable, signed, fairly scheduled attempts and evidence about what it observed. And the receiver owns an atomic deduplication record beside its business effect. That identifier is the handshake across the unknown boundary: the sender repeats one delivery, and the receiver converges on one result. Exactly. That's how a webhook system survives duplicates and retry storms without promising magic. Thanks for listening to Learning Podcasts.