Skip to content

Webhooks: when the server calls you

Polling and the open channels of the last two lessons connect a client to a server that it can reach. Between two servers there is a simpler arrangement. You give the provider an address, and when something happens on its side, it sends a request to that address. That request is a webhook. Stripe describes it this way: after you register an endpoint, Stripe sends data to it in real time when events happen on your account, as an HTTPS request with a JSON payload. It is how you hear about a payment that a customer’s bank confirmed after your request was answered, or about a dispute.

Mental model. Polling is calling the pizzeria every five minutes to ask if your order is ready. A webhook is giving them your number and waiting for the call. And since a call that goes to voicemail is tried again, you may get the same call twice.

The roles are reversed from a normal API call. The provider is the client and you are the server, with a public endpoint that anyone on the internet can also call. The rest of this lesson follows from those two facts: the provider retries when it does not hear a success, and anyone can post to your endpoint.

An open endpoint accepts requests from anyone, so a forged “payment succeeded” would be believed unless the receiver can tell. Both Stripe and GitHub sign each delivery with an HMAC computed from a secret that only the provider and the receiver know.

GitHub puts the HMAC hex digest of the payload in the X-Hub-Signature-256 header, prefixed with sha256=. Stripe puts a timestamp and the signature in Stripe-Signature, as t=…,v1=…, and signs the string made of the timestamp, a dot and the raw body. The receiver recomputes the HMAC with its copy of the secret and compares. Three details decide whether the check is any good:

  • Use the raw body. Stripe’s documentation says that it needs the raw body of the request, and that a framework which changes it makes verification fail. Parsing the JSON and writing it out again changes spacing and key order, and so changes the HMAC.
  • Compare in constant time. GitHub tells receivers to use a constant-time comparison such as crypto.timingSafeEqual, to mitigate timing attacks, and not a plain equality test.
  • Refuse an old timestamp. An attacker who captures a genuine request can send it again, with its valid signature, which is a replay attack. Because the timestamp is part of what is signed, it cannot be changed, and the receiver can refuse a delivery that is too old. Stripe’s libraries accept a difference of 5 minutes by default, and it warns against a tolerance of 0, which turns the check off.

A webhook is a request with a timeout. GitHub’s guidance is that the server should answer with a 2xx within 10 seconds of receiving a delivery, and it suggests a queue: the server answers when it receives the webhook and processes the payload in the background. Stripe likewise asks for a quick successful status before any complex logic that could cause a timeout.

The reason is the provider’s retry. A delivery that is not acknowledged in time is treated as failed and is sent again, so a slow handler makes the provider send the same event to a receiver that is still busy with it. The usual shape of a receiver is short: check the signature, save the event or put it in a queue, answer 2xx, and let a worker do the rest. RFC 9110 has the status for this: 202 Accepted means that the request was accepted for processing and not completed. The provider only asks for a 2xx; the point is that the receiver answers before the work, whichever one it picks.

This is the queue of the messaging module in front of your own handler, and it brings the at-least-once questions with it.

Providers promise to try, not to deliver once. Stripe says that it attempts delivery for up to three days with exponential backoff in live mode, so a receiver that was down on Friday may receive Friday’s events on Monday. The same documentation says that endpoints can occasionally receive the same event more than once, and that it does not guarantee delivery of events in the order in which they were generated. GitHub offers a unique X-GitHub-Delivery header for each delivery, and advises redelivering the webhooks that were missed once a server is back.

Two rules follow, and both are the idempotent consumer of the idempotency module:

  • Record the event ids that were processed, and ignore the ones that are seen again. Stripe gives exactly this advice. It also says not to use the creation time to tell whether an event was handled, since different events can have the same second.
  • Do not depend on the order. Stripe suggests fetching the current state of the object from its API when an event arrives first that you needed second. The event is a notification that something changed; the API holds the truth.

The code is the whole receiver: a signature in the form Stripe documents, a tolerance of 5 minutes, and a set of event ids. It uses a fake clock, so the output is the same on every run.

C# exampleVerify the signature, refuse an old timestamp, ignore a repeated event
webhook-receiver.cs
// A webhook receiver: check the signature on the raw body, refuse an old timestamp, answer at once,
// and ignore an event id that was already handled, because the sender retries until it sees a 2xx.
using System.Security.Cryptography;
using System.Text;
using ShardCraft.Playground;
var clock = new FakeClock();
var secret = "whsec_demo";
var receiver = new WebhookReceiver(secret, clock, TimeSpan.FromMinutes(5));
string Sign(long timestamp, string body)
{
var mac = HMACSHA256.HashData(Encoding.UTF8.GetBytes(secret), Encoding.UTF8.GetBytes($"{timestamp}.{body}"));
return $"t={timestamp},v1={Convert.ToHexStringLower(mac)}";
}
var now = clock.UtcNow.ToUnixTimeSeconds();
var body = """{"id":"evt_1","type":"invoice.paid","amount":2500}""";
Console.WriteLine($"first delivery -> {receiver.Handle(body, Sign(now, body))}");
Console.WriteLine($"sender retries -> {receiver.Handle(body, Sign(now, body))}");
Console.WriteLine($"body was changed -> {receiver.Handle(body.Replace("2500", "9999"), Sign(now, body))}");
Console.WriteLine($"wrong secret -> {receiver.Handle(body, "t=" + now + ",v1=" + new string('0', 64))}");
clock.Advance(TimeSpan.FromMinutes(6));
var other = """{"id":"evt_2","type":"invoice.paid","amount":700}""";
Console.WriteLine($"replayed, 6 min -> {receiver.Handle(other, Sign(now, other))}");
Console.WriteLine($"fresh signature -> {receiver.Handle(other, Sign(clock.UtcNow.ToUnixTimeSeconds(), other))}");
Console.WriteLine($"effects: {string.Join(", ", receiver.Effects)}");
class WebhookReceiver(string secret, FakeClock clock, TimeSpan tolerance)
{
private readonly HashSet<string> _seen = [];
public List<string> Effects { get; } = [];
public string Handle(string rawBody, string header)
{
// 1. Split "t=...,v1=..." and recompute the signature over "timestamp.body", the raw bytes that were sent.
var parts = header.Split(',').Select(p => p.Split('=', 2)).ToDictionary(p => p[0], p => p[1]);
var expected = HMACSHA256.HashData(Encoding.UTF8.GetBytes(secret), Encoding.UTF8.GetBytes($"{parts["t"]}.{rawBody}"));
var received = Convert.FromHexString(parts["v1"]);
// 2. Compare in constant time, and refuse a timestamp outside the tolerance (a replayed delivery).
if (!CryptographicOperations.FixedTimeEquals(expected, received)) return "400 bad signature";
var age = clock.UtcNow - DateTimeOffset.FromUnixTimeSeconds(long.Parse(parts["t"]));
if (age > tolerance) return $"400 too old ({age.TotalMinutes:0} min)";
// 3. The sender may deliver an event more than once: remember the ids, apply each event once.
var id = rawBody.Split("\"id\":\"")[1].Split('"')[0];
if (!_seen.Add(id)) return "200 duplicate, ignored";
Effects.Add(id);
// 4. A real receiver would queue the work here and answer 2xx before doing it.
return "200 accepted";
}
}
Output
first delivery -> 200 accepted
sender retries -> 200 duplicate, ignored
body was changed -> 400 bad signature
wrong secret -> 400 bad signature
replayed, 6 min -> 400 too old (6 min)
fresh signature -> 200 accepted
effects: evt_1, evt_2

This is the exact code that produced this output, run with the .NET SDK when the site was built. Nothing runs in your browser.

The first delivery of evt_1 is accepted. When the sender retries it, the receiver answers 200 and does nothing: duplicate, ignored. A body changed from 2500 to 9999 under the same signature is refused, and so is a signature made with the wrong secret. Then 6 minutes pass. A delivery of evt_2 that still carries the old timestamp is refused as too old, and the same event with a fresh signature is accepted. At the end the receiver has applied 2 events, evt_1 and evt_2. The code in the page is never run in the browser: the output was produced by a CI run of the same file.

Check your understanding: webhooks

This quiz needs JavaScript to check your answers.

Question 1 of 3

A receiver parses the JSON of each webhook, builds the object again and computes the HMAC over its own JSON text. The check fails on every genuine delivery.

What is wrong?

Choose one answer.

Question 2 of 3

A receiver does 40 s of work for each webhook before it answers. The sender waits 10 s, treats the delivery as failed and sends it again.

What should the receiver do?

Choose one answer.

Question 3 of 3

An attacker records a genuine, correctly signed webhook and posts it to the endpoint again 20 minutes later. The receiver accepts a difference of 5 minutes between the timestamp and its clock.

What happens to the replayed request?

Choose one answer.

The provider keeps trying for a while, and then stops: after three days Stripe gives up on an event, and GitHub’s advice is to redeliver the missed webhooks yourself once you are back. During the outage nothing arrives, and nothing tells you that something is missing. A receiver that depends on webhooks alone can stay wrong about what happened during the outage. One protection is to reconcile from time to time: call the provider’s API for what changed since the last event you know, which is polling used as a safety net under the webhooks. Stripe’s documentation also says that the API can be used to retrieve any missing object. Webhooks give you speed, and the API gives you completeness.

  • A webhook is a request that the provider sends to your endpoint when an event happens. It replaces polling between servers.
  • Verify an HMAC signature over the raw body, compare it in constant time, and refuse a timestamp outside a tolerance: Stripe’s default is 5 minutes.
  • Answer 2xx first, within GitHub’s 10 seconds, and let a queue and a worker do the work.
  • Delivery is at least once, with retries for up to three days at Stripe, and order is not guaranteed: record the event ids you have applied, and fetch the current state when an event comes early.
  • Back webhooks with a periodic check against the provider’s API for what was missed during an outage.

Next: synchronous or asynchronous, the choice behind every call.

Your progress

Built by GhaziAlibi.

© ShardCraft. All rights reserved.