Field note / Engineering+
Webhooks in Depth: Signatures, Replay Protection, and Idempotent Delivery
Receive webhooks safely: verify HMAC signatures on the raw body, reject replays with a timestamp tolerance, and process each event once.
A webhook is a request that another system sends to you, usually because something happened there. A payment succeeded, a repository received a push, a file finished uploading. Your endpoint is public, and anyone who knows the URL can send it a request. So the first question is not "what does the event mean?" It is "did this really come from the provider, and is it fresh?"
The second question is harder. Providers deliver at least once. A delivery can succeed on their side and still look like a failure to them, because your response was slow or the connection dropped. They will send it again. Your handler then sees the same event twice, and if it charges, emails or ships something on each call, the duplicate matters.
This article covers three layers of the receiving side: verifying the signature, rejecting replays, and processing each event once. It is project-neutral and uses the documented behaviour of Stripe, the Standard Webhooks specification and GitHub as examples. The code is a Node.js sketch, and I tested it locally, as described below.
Quick answer
- Verify the signature over the raw request body, before you parse it. Parsing and re-serializing the JSON changes the bytes, and the signature will fail.
- Use a constant-time comparison, and check the length first, because the usual comparison functions throw or leak on mismatched lengths.
- Include a timestamp in the signed content and reject old ones. A valid signature on a captured request is still a replay if it is old enough.
- Expect duplicates and out-of-order delivery. Store the event ID you have processed, and make the handler safe to run twice. The idempotency post covers the mechanics.
- Respond quickly, and do the work afterwards. Acknowledge the delivery, put the event on a queue, and process it there. Slow handlers cause timeouts, and timeouts cause redeliveries.
provider your endpoint
| POST /hooks (raw body) |
| signature: t=..., v1=... |
|-------------------------------->| 1. read the raw bytes
| | 2. check timestamp tolerance
| | 3. recompute HMAC, compare in constant time
| | 4. record event id (or skip if seen)
| 2xx | 5. enqueue work, respond
|<--------------------------------|
| (no 2xx in time: redeliver) | processing happens after step 5
What a webhook signature proves
A signature scheme for webhooks is a message authentication code. The sender and receiver share a secret. The sender computes an HMAC over the content and sends the result in a header. The receiver computes the same HMAC over the content it received and compares. If they match, the message was not changed after the sender signed it, and the sender knows the secret.
It proves two things, and not a third:
- Integrity: the body was not altered in transit.
- Origin: the sender has the secret.
It does not prove that the request is recent. A captured request with a valid signature will verify forever. That is why most schemes include a timestamp in the signed content, and why the receiver must enforce a tolerance on it.
It also does not prove that the event is new. A valid, fresh event can still arrive twice. Deduplication handles that, and it is a separate mechanism.
Stripe's scheme
Stripe sends a Stripe-Signature header with a timestamp and one or more signatures. Its signature page documents the format as t= and v1= entries, with v1 defined as "a signature generated with a hash-based message authentication code (HMAC) with SHA-256". Stripe's webhook signature documentation describes the signed payload as the timestamp, a period, and the unmodified request body, concatenated. Its libraries default to a tolerance of 5 minutes between the timestamp and the current time, and the documentation says not to use a tolerance of 0.
The same page is direct about the body:
Stripe requires the raw body of the request to perform signature verification... Any manipulation to the raw body of the request causes the verification to fail.
The header in the documentation's example has a space after the comma, t=1798765432, v1=..., so a parser must trim the parts. Here is a verifier that follows the documented format. It is the code I tested:
import { createHmac, timingSafeEqual } from 'node:crypto'
const TOLERANCE_S = 300
export function verifySignature(rawBody: string, header: string, secret: string, now: number) {
const parts = Object.fromEntries(
header.split(',').map((p) => p.trim().split('=')),
) as Record<string, string>
const ts = Number(parts.t)
if (!Number.isFinite(ts)) return { ok: false, reason: 'bad timestamp' }
if (Math.abs(now - ts) > TOLERANCE_S) return { ok: false, reason: 'timestamp outside tolerance' }
const expected = createHmac('sha256', secret).update(`${ts}.${rawBody}`).digest()
const received = Buffer.from(parts.v1 ?? '', 'hex')
// timingSafeEqual throws when the lengths differ, so check first.
if (received.length !== expected.length) return { ok: false, reason: 'bad signature length' }
if (!timingSafeEqual(received, expected)) return { ok: false, reason: 'signature mismatch' }
return { ok: true }
}
Three details in that function matter more than the rest.
The body is a string that has not been parsed. The function takes rawBody, not an object. The caller must read the request as bytes or text before any JSON middleware touches it. Frameworks often parse JSON by default. You then need the endpoint to skip the parser or to keep the raw buffer, depending on the framework.
The comparison is constant-time. A normal === on strings can return sooner when the first bytes differ, and in principle that timing reveals how much of the signature was correct. timingSafeEqual takes the same time regardless of where the mismatch is. GitHub's documentation makes the same point: "Never use a plain == operator," and it recommends a constant-time comparison such as crypto.timingSafeEqual.
The length check comes first. timingSafeEqual throws if the two buffers have different lengths. An attacker who sends a short signature would turn that into a 500 response. The guard turns it into a plain rejection.
The Standard Webhooks scheme
Several providers have converged on a shared layout. The Standard Webhooks specification, version 1.0.0, defines three headers: webhook-id, webhook-timestamp and webhook-signature. The signature is computed over the message ID, the timestamp and the body, delimited by full stops, and the spec gives the symmetric form as base64(HMAC-SHA256(key=secret, msg="msg_id.timestamp.payload")). The signature header uses the v1, prefix followed by the base64 value, and the header is space-delimited so that you can rotate secrets without breaking verification.
The difference from Stripe's scheme is that the ID is covered by the signature. A replayed body with a different ID fails verification, and the ID becomes a stable key for deduplication. The spec says to "use the webhook-id header as an idempotency key to prevent accidentally processing the same webhook more than once", and that the ID "remains the same no matter how many times a webhook that has failed is retried."
The spec does not give a numeric tolerance for the timestamp. It says to verify that the timestamp is "within some allowable tolerance of the current timestamp to prevent replay attacks." Five minutes is a common choice, and it is the one Stripe's libraries use, but the choice is yours.
A test for that scheme needs two checks: the same inputs reproduce the signature, and changing the ID breaks it. I ran both in the experiment described below.
GitHub's scheme
GitHub sends X-Hub-Signature-256, which, per the validating deliveries documentation, is "an HMAC hex digest" and "always starts with sha256=." The hash covers the payload, and the webhook events reference describes it as "the HMAC hex digest of the request body."
GitHub's signature has no timestamp. That means a captured delivery verifies indefinitely, so replay protection has to come from somewhere else: an ID you have already processed, or the age of the event as your own system judges it. Whether a redelivery reuses the same delivery ID is something I did not verify, so do not rely on it without checking the current documentation.
GitHub also sets a response window. Its handling deliveries documentation says your server "should respond with a 2XX response within 10 seconds of receiving a webhook delivery," and that otherwise GitHub "terminates the connection and considers the delivery a failure." That is the constraint that shapes the handler design below.
Replay protection
A replay is a valid request sent again. There are two defences, and they cover different cases.
Timestamp tolerance rejects requests whose signed timestamp is too far from your clock. It limits the window in which a captured request can be replayed. The experiment shows it: a correctly signed request 10 minutes old fails with timestamp outside tolerance. Keep the window small enough to be useful and large enough for clock skew and retries. Five minutes is a reasonable start. Remember that a retry from the provider gets a new signature and timestamp, so a retry is not stale for the same reason the original was.
Event ID deduplication handles the case the tolerance cannot. A replay inside the window, or a legitimate redelivery, carries the same event ID. If you have processed that ID, skip the work. This is an idempotency problem, and the idempotency post in this blog covers the atomic claim in detail. The short version: record the ID with an atomic insert, and treat a conflict as "already handled."
const seen = new Set<string>() // in production: a table with a unique constraint on event_id
export function claimEvent(eventId: string): 'process' | 'duplicate' {
if (seen.has(eventId)) return 'duplicate'
seen.add(eventId)
return 'process'
}
The Set is a stand-in. A real handler needs a shared store with an atomic insert, because two servers can receive the same event at the same moment. The in-memory version is enough to show the logic, and the experiment tests exactly that.
The raw body, in practice
The most common reason a correct signature fails is that the body changed before verification. The cause is usually middleware that parsed the JSON and passed the object on. Re-serializing the object does not reproduce the original bytes. Whitespace, key order and number formatting can all differ.
The experiment sends a pretty-printed JSON body, signs it, and then tests two receivers. The first parses the body and re-serializes it before verifying. The second verifies the raw bytes. The first fails and the second passes:
http: verifying after parse+stringify fails parsedFirst=false
http: verifying the raw bytes passes rawFirst=true
The data was the same in both cases. Only the bytes differed. That is the failure to look for when verification fails for a delivery that you believe is genuine. Log the length of the body you verified and check whether a middleware changed it.
Respond fast, process later
Most providers treat a slow response as a failure. GitHub's window is 10 seconds, and Standard Webhooks recommends timeouts of 15 to 30 seconds on the sender side, with a retry schedule that spans multiple days. Stripe documents retries for up to three days in live mode, with exponential backoff.
A handler that charges a card, sends an email and updates three tables can exceed those windows. Then the provider retries an event you were still processing. You now have two live handlers for one event, and no guarantee which finishes first.
The safer shape is to verify, record the event, put the work on a queue, and return 2xx. A worker processes the queue. The queue gives you retries of your own, and your endpoint stays fast. The cost is that processing becomes asynchronous, so the caller can no longer assume the work is done when the response arrives. That is almost always acceptable for webhooks, because the provider never expected synchronous results.
Do not return 2xx before you have durably recorded the event. If the process crashes between the response and the write, the provider believes you have it, and it will not send it again.
Ordering is not guaranteed
Stripe's documentation says it "doesn't guarantee the delivery of events in the order that they're generated." Assume the same of any provider unless it says otherwise.
Consider an invoice.updated event that arrives before the invoice.created event it refers to. If your handler assumes the order, it will fail or write the wrong state. Design the handler to read the current state from the provider or from your own store, rather than applying the event blindly. Compare a version or a timestamp on the object, and ignore updates older than what you have.
What I tested
The experiment is a single Node file with no dependencies, run on Node.js v24.22.1 against localhost. It has 13 checks:
| Check | Result |
|---|---|
| Valid signature verifies | PASS |
| Header with space after comma verifies | PASS |
| Tampered body fails | PASS (signature mismatch) |
| Wrong secret fails | PASS (signature mismatch) |
| Signed but 10 minutes old is rejected | PASS (timestamp outside tolerance) |
| Re-serialized JSON fails verification | PASS (same data, different bytes) |
timingSafeEqual throws on length mismatch | PASS (confirms the guard is needed) |
| Standard-style signature reproduces from the same inputs | PASS |
Changing webhook-id breaks the Standard-style signature | PASS |
Standard-style header starts with v1, | PASS |
| Duplicate delivery processed once | PASS |
| HTTP: verifying after parse and stringify fails | PASS |
| HTTP: verifying the raw bytes passes | PASS |
Thirteen of thirteen passed. What the test does not show:
- The Stripe and GitHub headers against live providers. I checked the formats against their documentation. I did not receive real deliveries.
- Behaviour across several servers. The deduplication is a
Setin one process. - Crash recovery between verification and enqueueing.
- Clock skew and tolerance tuning in a real deployment.
- Timing side channels with a measurement. The constant-time comparison is used because the documentation recommends it, not because I measured leakage.
Tradeoffs and when this does not apply
Signatures are not a substitute for TLS. The HMAC proves the body and the secret. It does not hide the body from someone who can read the traffic. Use HTTPS, and keep the secret out of logs.
A shared secret must be rotated. Standard Webhooks solves this with a space-delimited signature header, so a receiver can accept signatures from the old and new secret during a rotation. Without that, rotation means a window of failed deliveries.
Tolerance too tight breaks legitimate traffic. Clock skew, slow queues and retry delays can all push a valid delivery past a short window. Five minutes is generous for most providers, but measure before you tighten it.
Asymmetric signatures are different. Some providers sign with a private key, so you verify with a public key and never hold the signing secret. The shape of the checks is the same, but the key management is different.
Not every webhook needs this much. An internal service on a private network, with a signed bearer token and an allow-listed source, may not need an HMAC at all. The point is to know what your threat model requires, and to choose deliberately.
Checklist
- Read the raw body before any JSON parser runs, and verify against those bytes.
- Compare signatures in constant time, after checking the length.
- Include the timestamp in the signed content, and reject events outside a tolerance window.
- Record each event ID with an atomic insert, and skip events you have already handled.
- Respond 2xx only after the event is durably stored.
- Keep the handler fast, and do the work on a queue.
- Do not assume ordering. Read current state, or compare versions.
- Log the signature check result without logging the secret or the full body.
FAQ
Should I verify the signature before or after parsing the JSON?
Before. Verify the bytes you received. After verification, parse the body and use the object.
How long should the timestamp tolerance be?
Five minutes is the default in Stripe's libraries and a common choice. Pick a value that covers clock skew and your queue delay, and no larger than you need.
Is an HMAC enough to trust the sender?
It proves the sender knows the secret and that the body is unchanged. It does not prove the sender is the provider unless the secret is only held by the provider and you. Protect the secret, and rotate it if it leaks.
Can I use the event ID as the idempotency key?
Yes. Providers designed their IDs for this. Stripe recommends deduplicating by event ID, and the Standard Webhooks spec describes webhook-id as the idempotency key.
What if I return 500 when my handler fails?
The provider will retry, which is what you want for a transient failure. For a permanent failure, such as a payload you cannot handle, return a 2xx after logging it and sending it to a dead-letter store, or you will receive the same event for days.
Should I process webhooks synchronously?
Only if the work is small and the response window is comfortable. For anything that touches an external system, put the event on a queue and acknowledge it first.
Why does my signature fail only sometimes?
Look for a middleware that changes the body under some conditions, such as a content type you did not expect, or a proxy that normalizes whitespace. Log the body length you verified, and compare it with the length the provider sent.
Final mental model
delivery arrives
|
v
read raw bytes ---> timestamp within tolerance? --no--> reject
| |
| yes
v v
recompute HMAC over "t.body" (or "id.t.body")
|
v
constant-time compare (length checked first) --mismatch--> reject
|
v
event id already recorded? --yes--> acknowledge, do nothing
|
no
v
record id atomically, enqueue work, respond 2xx
|
v
worker processes the event (safe to run again, order not assumed)
A webhook endpoint is a public door. The signature tells you who knocked and that the message arrived unchanged. The timestamp tells you whether it is still current. The event ID tells you whether you have already answered it. Each check answers a different question, and all three are needed.