Home
Guides

Webhook Security with HMAC: Verify, Block Replays, Handle Retries

Engineer checking webhook signature verification

To secure a webhook endpoint, verify an HMAC signature on every request: recompute the hash of the raw request body with your shared secret, compare it to the signature header in constant time, reject stale timestamps, and make your handler idempotent so the sender's retries can never repeat a side effect. Get those four things right and your endpoint can safely accept events that trigger real actions, such as an AI agent replying to a customer email.

This guide walks through each step with code, the mistakes that make valid signatures fail, and how retries and backoff interact with your security checks. It is written for developers who receive webhooks from email, payments or agent platforms and want a handler they can trust in production.

TL;DR

  • HMAC proves two things: the sender holds the shared secret, and the body was not changed in transit.
  • Compute the HMAC over the raw bytes of the body, before any JSON parsing, and compare with a constant-time function.
  • Add an authenticated timestamp check and a short-lived store of processed event IDs to stop replays.
  • Keep secrets in a secrets manager, use one per integration, and rotate with an overlap window.
  • Retries create duplicates by design, so return a 2xx fast, queue the work, and process each event ID once.

Table of Contents

What HMAC does for a webhook

A webhook is an HTTP request that a provider sends to a URL you publish. Anyone who learns that URL can send a request to it, so the URL alone proves nothing. HMAC (hash-based message authentication code) closes that gap. OWASP's webhook guidance describes it as the way a subscriber confirms a delivery came from the legitimate publisher and that the body was not altered on the way.

The mechanics are simple. You and the provider share a secret. For each delivery, the provider hashes the request body with that secret and puts the result in a header. You repeat the calculation and compare. An attacker who does not know the secret cannot produce a matching value for a forged or edited body.

It is also the common choice. A study of 100 webhook providers found HMAC on 65% of them, which means the pattern you learn here transfers across most of the providers you will integrate with. Header names, hash encodings and what exactly gets signed differ per provider, so always read the provider's own signing page for those details.

What HMAC does for a webhook

How to verify an HMAC signature, step by step

The verification routine is the same everywhere. What goes wrong is nearly always in the details of each step.

1. Capture the raw body

The signature covers bytes, not objects. OWASP's guidance is to calculate the HMAC from the raw, unparsed body and to do so before your framework parses or re-serialises the JSON, because any change to the bytes invalidates the signature. Parsing and then calling JSON.stringify will reorder keys, change whitespace or alter number formatting, and your hash will no longer match.

In Express, that means mounting a raw body parser on the webhook route only:

app.post("/webhooks/email", express.raw({ type: "application/json" }), handler);

2. Recompute the HMAC with your secret

Use the hash the provider documents, commonly SHA-256. Check whether the provider signs the body alone or a string such as the timestamp, a dot and the body. GitHub's documentation shows the body-only style with a hex digest. Other providers prepend a timestamp to the signed string, which also gives you replay protection.

import crypto from "node:crypto";

function expectedSignature(rawBody, secret) {
  return crypto.createHmac("sha256", secret).update(rawBody).digest("hex");
}

3. Compare in constant time

A plain === comparison can leak, through timing differences, how many leading characters matched. Use a constant-time function, as OWASP advises. Both buffers must be the same length, so check length first.

function verify(rawBody, header, secret) {
  const expected = Buffer.from(expectedSignature(rawBody, secret));
  const received = Buffer.from(header || "");
  return expected.length === received.length &&
    crypto.timingSafeEqual(expected, received);
}

The Python equivalent is hmac.compare_digest(expected, received).

4. Reject before doing any work

If verification fails, return a 4xx immediately and do nothing else: no database write, no queue message, no call to an agent. Log the failure with the delivery ID and source IP so you can spot probing, but never log the secret or the computed signature.

5. Acknowledge fast, process later

Once the signature is valid, Twilio's webhook guidance recommends returning HTTP 200 straight away and queuing long-running work asynchronously. A handler that calls a language model, sends an email and writes to three tables before responding invites timeouts, and a timeout is exactly what triggers a retry.

Why valid signatures fail

When a signature that should match does not, the cause is usually one of these.

SymptomLikely causeFix
Every request failsBody was parsed and re-serialisedCapture raw bytes on the webhook route
Fails only on some payloadsMiddleware changes encoding or strips whitespaceVerify before any middleware touches the body
Fails after a deployWrong environment secretOne secret per environment and integration
Hex versus base64 mismatchProvider encodes the digest differentlyMatch the documented encoding exactly
Fails only in stagingProxy or gateway rewrites the bodyVerify at the first hop that sees raw bytes
Header present but never matchesProvider signs timestamp.body, not body aloneRebuild the signed string as documented

Before blaming the algorithm, log the length of the raw body you received and compare it with the content length the provider reports. A mismatch tells you something in front of your code is altering the request.

Block replays with timestamps and event IDs

HMAC alone does not stop replay. An attacker who captures one valid request can resend it, and the signature will still match because the body is identical. OWASP's guidance pairs the signature with two controls.

An authenticated timestamp. The timestamp must be inside the signed content, otherwise an attacker can change it freely. Reject any request whose timestamp falls outside a short tolerance window that you choose, for example a few minutes. Keep your server clocks synchronised with NTP, or valid requests will be rejected.

A cache of processed event IDs. Store the event ID of every delivery you accept for at least as long as your timestamp window, and skip any ID you have already seen. A Redis key with a time-to-live works well. This also protects you from the provider's own duplicate deliveries, which leads to the next topic.

Block replays with timestamps and event IDs

Store and rotate secrets properly

The signature is only as strong as the secret behind it. OWASP's guidance is to keep signing secrets in a secrets manager and never hard-code them in source or configuration files. Three practical rules follow.

  1. One secret per integration. If a single provider secret leaks, you rotate one integration rather than all of them. In a multi-tenant product, a secret per tenant endpoint limits the damage further.
  1. Rotate with an overlap window. Accept signatures from both the old and new secret for a defined period, then retire the old one. Rotating with a hard cut-over drops every in-flight delivery.
  1. Never log it. Redact the secret and the signature header from request logs and error trackers.

If you issue webhooks to your own customers, make the secret visible once at creation, store only what you need to sign, and give customers a rotation button.

Retries and backoff: what the sender does and what you must do

Providers retry because networks fail. Twilio's documentation notes that when your handler returns a non-2xx status or times out, it might retry the webhook depending on its retry settings. Every provider has its own schedule, so read theirs rather than assuming one.

Most retry schedules share a shape: delays grow after each failed attempt (exponential backoff), a random offset (jitter) spreads attempts out so a recovering receiver is not hit by a synchronised wave, and delivery stops after a cap on attempts or total time. If you are the one sending webhooks, build those three properties in, and honour a Retry-After header when a receiver sends one.

For a receiver, the useful points are these:

  • Signal intent with the status code. A 5xx, 408 or 429 tells most senders to try again. A clear 4xx for a bad signature tells them the request is wrong. Do not return 200 for failures you want retried, and do not return 500 for requests you want dropped.
  • Expect the same event more than once. A retry sends the same payload, usually with the same event ID, and the timestamp may or may not be refreshed. Check how your provider signs retries, because a stale timestamp on a retry can collide with your replay window. Size the window with the provider's schedule in mind.
  • Do not hold the connection open. Slow handlers turn a transient hiccup into a retry storm.
  • Plan for outages. After a long outage of your own, the backlog arrives in a burst. Queue it and process at a pace your downstream systems can bear.

If you want to go deeper on the sender side, the Qubrics guide to an email retry strategy covers safer resending, and the piece on email rate limiting shows how to queue and retry without tripping provider limits.

Make your handler idempotent

Because retries and replays produce duplicates, your handler must be idempotent: processing the same event twice must have the same effect as processing it once. OWASP's recommendation is to keep a persistent record of processed event IDs and skip repeats, and to protect internal state changes against duplicate execution.

A reliable pattern:

  1. Verify the signature and timestamp.
  1. In one database transaction, insert the event ID into a table with a unique constraint.
  1. If the insert fails because the ID exists, return 200 and stop.
  1. Otherwise enqueue the job and return 200.
  1. Make the job itself safe to re-run, for example by using the event ID as the idempotency key on any outbound call.

The unique constraint matters more than an in-memory check. Two retries arriving at the same moment on different servers will both pass a "have I seen this?" read, and only the database enforces a single winner.

For an AI agent, this is more than tidiness. An inbound-email webhook that fires twice can make an agent send two replies to the same customer. Deduplicating at the door is cheaper than trying to recall a message.

Webhook security for email events

Email webhooks carry some of the most sensitive payloads you will handle: message content, sender addresses, attachments and bounce details. Everything above applies, plus a few email-specific points.

  • Treat the content as untrusted even when the signature is valid. HMAC proves who sent the request, not that the email inside is safe. A valid signature on an inbound message still means arbitrary text from the internet, which matters when an agent reads it.
  • Separate event types. Inbound messages, delivery results and bounces deserve different handlers and, ideally, different secrets or endpoints.
  • Keep an audit trail. When something goes wrong at 2 am you want the event ID, the signature result and the outcome in one place. Delivery logs make that straightforward, and the Qubrics article on email delivery logs for developers shows what to record.

Qubrics has written up the full pattern for signing, idempotency and replay on email webhooks, and a separate guide on reliable inbound processing. For bounces specifically, see the bounce handling guide. If you are weighing push against pull, SSE versus webhooks compares the two patterns.

Where Qubrics fits

Qubrics provides persistent mailboxes for receiving mail and uses the Sending API to send through configured providers. Webhooks deliver signed inbound and delivery events. The Mailbox API provides a live stream for received-message updates, and the Management API exposes delivery logs. You can start on Free at US$0 per month per team or move to Pro at US$7 per month per team. See the pricing page for usage fees and plan details. To see how inbound mail reaches your agent, look at inbound mailboxes.

Our perspective

Most webhook incidents we hear about are not broken cryptography. They are a handler that parsed the body before hashing it, a secret shared across every environment, or a retry that ran an agent action twice.

That is why we think of email events as a pipeline rather than a single endpoint. When a persistent Qubrics mailbox receives a message, a webhook can notify your handler. Verify the event and deduplicate it before applying the update. Use the Management API to check delivery logs and review webhook delivery attempts separately.

For agents, the stakes are higher than for a typical SaaS integration. An agent acts on what it reads, so verification, replay protection and idempotency are the difference between an agent that replies once and one that replies three times. Build those checks first, then let the agent loose.

Sources

Frequently Asked Questions

Is HMAC enough to secure a webhook?

It is the foundation, not the whole answer. HMAC proves the sender knows the secret and the body is intact, but it does not stop a captured request being replayed. Add a signed timestamp check, event ID deduplication, HTTPS and proper secret storage.

Why does my HMAC verification fail even with the right secret?

The most common cause is hashing a re-serialised body instead of the raw bytes. Capture the raw body before any JSON parsing, and confirm you are matching the provider's hash algorithm, encoding (hex or base64) and signed string format.

How should I handle webhook retries?

Return a 2xx as soon as the signature is valid and the event is queued, and return a 5xx only when you want the sender to try again. Expect duplicates and deduplicate on the event ID. Check your provider's documentation for its retry schedule and cut-off.

How often should I rotate a webhook secret?

Rotate on a regular schedule your security policy sets, and immediately if a secret may have leaked. Use an overlap window in which both the old and new secrets are accepted so no deliveries are lost.

Do I need idempotency if I already check timestamps?

Yes. Timestamp checks block old replays, but legitimate retries inside the window still produce duplicates. A unique constraint on the event ID is the reliable guard.