Foundations · L2Webhooks and async APIs

Webhooks and async APIs

Webhooks arrive late, twice, out of order, or from someone pretending to be the sender. Here is how to build both ends so none of that hurts.

L2 SeniorFoundations19 min read
Fact-checked by AI against cited sources · Human review pendingLast reviewed 9 Nov 2026 · How we check content
Section 1 of 8

What broke

On 15 August 2023, at 16:58 UTC, an internal GitHub job queue started to fall behind. That queue processes webhooks. 1

The cause was a large and lasting spike in webhook deliveries. Customers waited up to 4.5 hours for some webhooks. GitHub fixed it by blocking events from the sources of the extra load. Then the backlog drained slowly. 1

Think about what that means for a receiver. Your CI bot or deploy tool waits for a push event. The event does not come for hours. Nothing is broken on your side, so no alert fires.

When the backlog drains, you could get hundreds of old events close together. Your handler must not run them all twice, run them in the wrong order, or fall over.

Webhooks fail in four ways: late, twice, out of order, and fake. This lesson shows how to build both ends so each failure is boring.

Section 2 of 8

The idea in simple words

A webhook is the reverse of an API call. You do not ask the provider "did anything change?" again and again. The provider calls your URL when something happens. You first met them in REST API design.

The provider's promise is weak. Most providers retry, so delivery is at-least-once: an event can come late, twice, or before an older event. Some, like GitHub, do not retry at all, so an event can also be lost. 5 Anyone on the internet can also post to your URL.

The key idea. Treat each webhook as a signed hint, not as the truth. Check who sent it, save it, answer fast, skip repeats, and read the current state before you act.

Section 3 of 8

How it works

Step through one delivery that times out and comes back. Use Next and Back, or the ← and → keys.

A webhook times out, comes again, and the event id stops double work Sender Your endpoint Seen event ids POST invoice.paidid evt_42 · signed mark paid · 12 ssave evt_42evt_42 200 OKtimeout · failed retry, latersame id evt_42 evt_42 seen?yes200 OKskip the work✓ done once SeniorPath
  1. The sender posts an invoice.paid event to your endpoint. The event has an id, evt_42, and a signature.
  2. Your endpoint checks the signature and does the work inline. It takes 12 seconds. When it finishes, it saves evt_42 as seen. This is the slow pattern from step 3. It shows why the id check still matters.
  3. The sender stopped waiting before your answer came. It marks the delivery as failed. It cannot know that the work happened.
  4. After a backoff, the sender tries again. The body has the same event id, evt_42. With Stripe, the timestamp and signature are new.
  5. Your endpoint finds evt_42 in the seen list. It answers 200 and skips the work. The invoice is marked paid once.
Step 1 of 5

The receiver

1. Verify the signature. The sender signs each request with an HMAC: a hash of the body made with a secret only you and the sender know. GitHub puts it in X-Hub-Signature-256, as sha256= plus a hex digest of the payload. 3 Shopify uses X-Shopify-Hmac-Sha256. 7

Compute the HMAC over the raw body, byte for byte. If your framework parses and rewrites the JSON first, the check fails. 2 Compare in constant time. GitHub says: "Never use a plain == operator." 3

2. Reject old timestamps. A valid signature alone does not stop a replay attack. Someone can copy a real request and send it again. So Stripe signs a timestamp too. Its header, Stripe-Signature, holds t= and v1=. The signed text is the timestamp, a dot, then the body. 2

Stripe's libraries reject anything older than 5 minutes by default. Each retry gets a new timestamp and signature, so real retries still pass. 2 Standard Webhooks also signs a timestamp. It uses three headers: webhook-id, webhook-timestamp and webhook-signature. It signs the id, timestamp and body together, and leaves the tolerance to you. 9

Here is a manual Stripe-style check in Node. In real code, prefer the provider's library.

import { createHmac, timingSafeEqual } from "node:crypto";

const TOLERANCE_SEC = 300; // 5 minutes

export function verify(raw: Buffer, header: string, secret: string) {
  const parts = header.split(",").map((p) => p.split("="));
  const t = parts.find(([k]) => k === "t")?.[1];
  const sigs = parts.filter(([k]) => k === "v1").map(([, v]) => v);
  if (!t || sigs.length === 0) return false;

  const age = Math.abs(Date.now() / 1000 - Number(t));
  if (!(age <= TOLERANCE_SEC)) return false; // too old: maybe a replay

  const expected = createHmac("sha256", secret)
    .update(`${t}.`).update(raw).digest();
  return sigs.some((s) => {
    const got = Buffer.from(s, "hex");
    return got.length === expected.length && timingSafeEqual(got, expected);
  });
}

3. Answer 2xx fast, then work. GitHub wants a 2xx within 10 seconds, or it marks the delivery failed. 4 Shopify gives you five seconds. 8 So verify, save the event to a queue, and answer. A worker does the real work. Stripe says a queue also protects you from spikes, like the start of the month when all subscriptions renew. 2

4. Skip repeats by event id. Save each processed id and skip ids you have seen. 2 Use X-GitHub-Delivery on GitHub, X-Shopify-Webhook-Id on Shopify, and webhook-id in Standard Webhooks. 4 7 9 Insert the id with a unique constraint, in the same transaction as the work. This is the idempotency key idea, from the other side.

5. Do not trust order. Stripe does not promise order. It also says not to use the created time to order events. 2 Shopify says a products/update can come before products/create. 7 So store a version or updated_at with your copy, and ignore anything older. Or fetch the current object from the API.

6. Prefer thin events. A thin event says only "object X changed". You then fetch the object. Stripe recommends thin events for new endpoints. Its SDK has a method, fetchRelatedObject(), that gets the latest version of the object. 2 Fetching also fixes ordering: you always act on the current state.

The sender

1. Never lose an event. Write the event to a transactional outbox in the same transaction as the change. A delivery worker reads the outbox and sends.

2. Retry for days, with backoff and jitter. Standard Webhooks gives an example schedule of ten tries over about three days. The first is at once. The waits after that are 5 s, 5 min, 30 min, 2 h, 5 h, 10 h, 14 h, 20 h and 24 h. 9 Stripe retries for up to three days in live mode. 2 Shopify retries eight times in four hours. 8 GitHub does not redeliver failed deliveries automatically. 5 See backoff and jitter.

3. Isolate each endpoint. Our advice: give each endpoint its own queue, or a cap on in-flight requests. Then one customer's slow server cannot hold workers that others need. Use a timeout too. Standard Webhooks suggests 15 to 30 seconds. 9

GitHub faced a related problem in 2023. A spike from some sources slowed everyone, and it blocked events from those sources. Afterwards, it improved its ability to manage load sources. 1

4. Disable dead endpoints. After long, steady failure, tell the customer by email and stop sending. On 410 Gone, disable the endpoint at once. 9 Shopify removes a subscription that keeps failing. 8

5. Offer replay. Customers recover from outages by asking for events again. Stripe lets you resend from the Dashboard for 15 days, and from the CLI for 30 days. 2 A GitHub redelivery keeps the same X-GitHub-Delivery value, so dedupe still works. 4

6. Rotate secrets with an overlap. When Stripe rolls a secret, the old one can stay valid for up to 24 hours. Meanwhile it sends one signature per secret. 2 Standard Webhooks puts a space-separated list of signatures in one header for the same reason. 9

7. Block SSRF. Customers type in URLs, and your servers call them. An attacker can use this for server-side request forgery. 9 Check that the resolved IP is not private. Do not follow redirects. 10 Send through a proxy that filters internal IPs, from a subnet that cannot reach internal services. 9

Async APIs

Webhooks are one way to report a slow job. Another is 202 Accepted: the job was accepted, but is not done. RFC 9110 says the body should point to a status monitor. 11 The client polls that URL. A third way is streaming, such as Server-Sent Events, which keeps one connection open.

Section 4 of 8

Trade-offs

OptionWho keeps the connectionWorks if the client has no public URL?Main costUse it when
202 + status URL (polling)The client asks again and again.Yes Wasted calls, and a delay between checks.Jobs of seconds or minutes, browser or mobile clients.
WebhooksThe sender calls you.No You need a public HTTPS endpoint.Signatures, retries, dedupe, SSRF guards.Server-to-server events between companies.
Streaming (SSE, WebSocket)One long open connection.Yes Reconnects, and missed events while offline.Live screens that must update in a second.

Simple rule: use webhooks for the push and a periodic reconciliation job for the truth. Shopify says your app should not rely only on webhooks. 7

Section 5 of 8

At work: how a senior uses this

  • Ask of every handler: "What happens if this event comes twice, late, or before the one it depends on?"
  • Ask: "If we miss a whole day of events, how do we catch up?" Have a backfill or reconcile job ready. On GitHub, which does not retry, you write a script that finds failed deliveries and redelivers them. 5 You can only redeliver deliveries from the past 3 days. 6
  • Log and alert on signature failures. A sudden rise means a broken deploy, a rotated secret, or an attack.
  • Measure the age of events in your webhook queue, not only errors. Late events are silent.
  • As a sender, add a delivery log per endpoint that customers can see and replay from. 9
  • In design reviews of a sender, ask: "Can one customer's slow endpoint delay everyone else?"
  • For payments, read the payment lifecycle. The webhook is often the only place you learn a payment settled.
Section 6 of 8

With AI

What to ask the agent

"Write an Express route for Stripe webhooks. Read the raw body, verify the signature with the official library, insert the event id with a unique constraint, push the event to a queue, and return 200. Do no other work in the route."

"Review this webhook sender. Find every place where one slow endpoint can block deliveries to other endpoints, and every way a customer URL can reach our internal network."

"Write tests for this handler: duplicate event, old timestamp, wrong signature, and an update event that arrives before its create event."

What to check yourself

  • The signature is checked on the raw bytes, before any JSON parsing or body middleware.
  • The compare is constant-time, such as crypto.timingSafeEqual or Python's hmac.compare_digest. 3
  • The timestamp tolerance is not 0. Stripe warns that 0 turns the recency check off. 2
  • The dedupe insert and the work share one transaction. A check-then-insert in two steps lets two copies through.
  • The handler does not set a state straight from the payload. It fetches the object or compares versions.
  • The sender's HTTP client blocks private IPs on every request and does not follow redirects.
Section 7 of 8

Check yourself

1. Your framework parses the JSON body and you compute the HMAC over the re-serialised object. Real Stripe events now fail the signature check. Why?

Show answer

The bytes changed. The signature covers the raw body, so you must check it before any parsing. Stripe needs the raw request body for verification, and any change to it makes verification fail.

2. A request has a valid Stripe signature, but its timestamp is two hours old. What should your endpoint do?

Show answer

Reject it. It may be a replayed copy, and real retries come with a fresh timestamp. The timestamp is signed, so an attacker cannot change it. Stripe makes a new timestamp and signature for each retry.

3. Your endpoint gets invoice.paid before invoice.created for the same invoice. What is the best response?

Show answer

Fetch the current invoice from the provider's API and act on that. Stripe does not promise order and suggests using the API to get missing objects.

4. Your handler needs 20 seconds to do its work. GitHub waits about 10. What should you change?

Show answer

Verify, save the event to a queue, and answer 2xx at once. A worker does the rest. GitHub expects a 2xx within 10 seconds and suggests a queue to process payloads in the background.

5. A customer sets their webhook URL to an address that resolves to 169.254.169.254. What should your sender do?

Show answer

Block it. Webhook calls must not reach internal or metadata addresses. This is SSRF. OWASP says attackers use it to steal credentials from cloud metadata services.

Your progress is saved only in this browser. Export it to keep it safe.

Was this clear?
Report a mistake (opens GitHub in a new tab)
Section 8 of 8

Go deeper

Show 11 sources and related lessons
  1. GitHub Availability Report: August 2023 (opens in a new tab)
    The official report on the 15 August 2023 incident, when webhooks were delayed by up to 4.5 hours.
  2. Stripe documentation: Receive Stripe events in your webhook endpoint (opens in a new tab)
    Signatures with a timestamp, the 5-minute tolerance, retries for up to three days, duplicates, ordering, thin events and secret rolling.
  3. GitHub Docs: Validating webhook deliveries (opens in a new tab)
    The X-Hub-Signature-256 header, HMAC-SHA256 over the raw payload, and why you never compare with a plain ==.
  4. GitHub Docs: Best practices for using webhooks (opens in a new tab)
    Answer within 10 seconds, use a queue, and use X-GitHub-Delivery to spot repeats.
  5. GitHub Docs: Handling failed webhook deliveries (opens in a new tab)
    GitHub does not retry failed deliveries for you, and how to script redelivery with the REST API.
  6. GitHub Docs: Redelivering webhooks (opens in a new tab)
    How to redeliver a failed delivery, and the 3-day limit.
  7. Shopify Dev Docs: About webhooks (opens in a new tab)
    No ordering promise, the X-Shopify-Webhook-Id header, and why you also need reconciliation jobs.
  8. Shopify Dev Docs: Troubleshoot webhooks (opens in a new tab)
    The five-second response limit, eight retries in four hours, and removal of subscriptions that keep failing.
  9. Standard Webhooks: Open source tools and guidelines for sending webhooks easily, securely and reliably, version 1.0.0 (GitHub, standard-webhooks/standard-webhooks) (opens in a new tab)
    A shared design for senders, with headers, signing, a multi-day retry schedule, status code handling, thin payloads and SSRF advice.
  10. OWASP Cheat Sheet Series: Server Side Request Forgery Prevention Cheat Sheet (opens in a new tab)
    How to defend a server that calls URLs its users give it, such as webhook URLs.
  11. Fielding, Nottingham and Reschke, RFC 9110: HTTP Semantics (IETF, 2022), section 15.3.3 (opens in a new tab)
    What 202 Accepted means, and why its body should point to a status monitor.

Real incident: GitHub, 15 Aug 2023: GitHub webhooks delayed by up to 4.5 hours

Related: REST API design · Idempotency, retries and timeouts · The payment lifecycle · Sagas, outbox and CDC · Queues vs logs and delivery guarantees · Backoff, jitter and retry budgets · OWASP Top 10 and secure coding · Rate limiting · Reconciliation

Term

See full entry

Jump to a section

  1. 1What broke
  2. 2The idea in simple words
  3. 3How it works
  4. 4Trade-offs
  5. 5At work
  6. 6With AI
  7. 7Check yourself
  8. 8Go deeper