Receiving webhooks safely: verify the signature, answer fast, and expect every event twice
A practical checklist for webhook receivers: HMAC signature checks on the raw body, replay windows, quick 2xx replies, queues and deduplication by event id.

A webhook endpoint is an odd thing to own. It is a public URL, anyone on the internet can POST to it, and when a request arrives your code is expected to change something: mark an order paid, grant access, start a job. That combination deserves some care.
The good news is that the care fits in a short checklist. Verify who sent the request, reject stale copies, answer quickly, do the real work later, and assume every event can arrive more than once.
The shape of a safe receiver
flowchart LR
A[Sender] -->|POST + signature| B[Your endpoint]
B --> C{Signature and timestamp valid?}
C -->|no| D[400, stop]
C -->|yes| E[Store event id + payload]
E --> F[Reply 2xx]
E --> G[Queue]
G --> H[Worker: skip if id already done]
Everything left of the queue is quick and boring on purpose. Everything right of it can be slow, can fail, and can be retried.
1. Verify the signature on the raw body
Without verification, anyone who guesses your URL can send a fake "payment succeeded" event. Most providers sign each request with a shared secret, and you recompute the signature to check it.
The usual recipe is an HMAC with SHA-256. Stripe's scheme signs the timestamp, a dot, and the exact request body. The open Standard Webhooks spec signs the message id, the timestamp and the body, joined with dots. The details differ, the idea does not.
The most common failure is not cryptography, it is the body. The signature covers the exact bytes the sender transmitted. If your framework parses the JSON and you serialize it again, whitespace or key order can change and the check fails. Read the raw bytes first, verify, and only then parse.
func verify(secret []byte, header string, body []byte, tolerance time.Duration) bool {
// header looks like: t=1798765432,v1=abcd...,v1=ef01...
var ts string
var sigs []string
for _, part := range strings.Split(header, ",") {
k, v, ok := strings.Cut(part, "=")
if !ok {
continue
}
switch k {
case "t":
ts = v
case "v1":
sigs = append(sigs, v)
}
}
sec, err := strconv.ParseInt(ts, 10, 64)
if err != nil || len(sigs) == 0 {
return false
}
if d := time.Since(time.Unix(sec, 0)); d > tolerance || d < -tolerance {
return false
}
mac := hmac.New(sha256.New, secret)
mac.Write([]byte(ts + "."))
mac.Write(body)
want := hex.EncodeToString(mac.Sum(nil))
for _, s := range sigs {
if hmac.Equal([]byte(s), []byte(want)) {
return true
}
}
return false
}
A few details in that function matter:
- Constant-time comparison.
hmac.Equaldoes not leak how many leading characters matched. A plain==can. - Several signatures. While a secret is being rotated, senders may include one signature per active secret. Accept the request if any of them matches.
- Ignore what you do not know. Providers sometimes add extra fields to the header. Read the ones you need and skip the rest.
Tip
If you can, use the provider's official library instead of writing this yourself. The sketch above is here so you understand what the library does, not as a replacement for it.
2. Reject old requests
A valid signature proves the request was genuine once. It does not prove it is fresh. An attacker who captures one request could send it again next week.
Because the timestamp is part of what is signed, it cannot be changed without breaking the signature. So compare it with your clock and refuse anything outside a window. Stripe's libraries use 5 minutes by default, and its docs warn that a tolerance of 0 switches the check off entirely. The Standard Webhooks spec says to check a window but leaves the size to you.
This makes your server clock part of your security. Keep it synchronised with NTP.
3. Answer fast, work later
Senders wait for your reply, and they give up. The Standard Webhooks spec suggests a timeout of roughly 15 to 30 seconds on the sender side, and Stripe's guidance is to return a 2xx before doing anything complicated. If you update your accounting system inside the request and it takes too long, the sender sees a failure and retries, and now you are doing the work twice.
So the handler should do three things only:
- Verify the request.
- Write the event to durable storage (a table is fine).
- Return
200.
A worker picks events up afterwards. If you already run Postgres, the pattern in A job queue in Postgres is enough for this, and it has an extra benefit: a traffic spike, such as everyone's subscription renewing on the first of the month, becomes a longer queue instead of an overloaded endpoint.
Status codes carry meaning too. Redirects (3xx) are treated as failures by both Stripe and the Standard Webhooks spec, so register the final URL. A 4xx or 5xx tells the sender to retry, which is what you want for a temporary problem and not what you want for a request you have decided is simply invalid. For forged requests, a plain 400 is fine; they were never going to be retried by anyone who matters.
4. Expect duplicates and disorder
Delivery is "at least once". Senders retry when they do not get a 2xx, and a retry can cross paths with a reply that was slow. Stripe retries live events for up to three days with exponential backoff, so a problem on your side can produce a burst of old events when you recover.
Two rules keep this harmless.
Deduplicate by event id. Store each id you have processed, and skip repeats. The cleanest way is a unique constraint, so the database settles the race between two workers:
create table webhook_events (
id text primary key, -- the sender's event id
received_at timestamptz not null default now(),
payload jsonb not null,
done_at timestamptz
);
-- in the handler: a repeat inserts nothing
insert into webhook_events (id, payload)
values ($1, $2)
on conflict (id) do nothing;
If the insert changed no rows, you have seen this event already; still reply 200 so the sender stops retrying. This is the same idea as the keys in Idempotency keys: making retries safe in any API, applied to the receiving side. The Standard Webhooks spec says the same thing: use the message id as an idempotency key, and keep it identical across retries.
Do not rely on order. Stripe states plainly that events may arrive in a different order than they happened, and that the created time is only in seconds, so two events can share it. If an invoice.paid shows up before the event that announced the invoice, fetch the current object from the API instead of assuming. Treat the event as a hint that something changed, and the API as the truth.
Note
Stripe also points out that, occasionally, two separate event objects can describe the same thing. For those, comparing the object id and event type is a better duplicate test than the event id alone.
5. Smaller habits that pay off
- One secret per endpoint. If one leaks, you rotate one thing. Practise the rotation before you need it, using the overlap period providers offer (Stripe allows the old secret to stay active for up to 7 days).
- HTTPS only. Both sources require it for live traffic.
- Subscribe only to events you use. Fewer event types means less load and less code to reason about.
- Skip CSRF checks on this one route. Frameworks that protect every POST will reject webhooks. The route is protected by the signature instead.
- Never log the secret or the full header. Log the event id and your decision.
- Pair your database write with your own outgoing messages carefully. If handling an event means saving data and then publishing something, the transactional outbox keeps both in step.
If you also send webhooks
Everything above flips when you are the sender. Give each message a stable id that stays the same across retries, sign the id, timestamp and body, retry over days with backoff and jitter, honour a Retry-After header, and treat 410 Gone as a request to stop sending. The Standard Webhooks spec also recommends isolating outbound webhook workers from your internal network, because customers choose the URLs and a URL can point somewhere it should not. That deserves its own article.
A quick review list
Before you ship a webhook endpoint, check that it:
- verifies the signature against the raw body, in constant time
- rejects timestamps outside a window
- stores the event and replies 2xx before doing real work
- ignores events whose id it has already seen
- copes with events arriving out of order
- uses HTTPS, a per-endpoint secret, and a tested rotation plan
None of this is clever. That is the point: a webhook receiver is a small piece of code that sits on the edge of your system, and the boring version is the safe one.


