Webhooks Done Right: HMAC Signatures, Replay Windows, and Retry-Safe Receivers

A webhook flips the API relationship you are used to. Instead of your code calling a provider, the provider calls you — over plain HTTPS POST, to an endpoint you expose on the public internet. That endpoint has no login form, no session, no API key from the caller. Unless you treat every incoming request as hostile, anyone who discovers or guesses the URL can inject fake “payment succeeded” events into your system. The entire trust model of a webhook integration rests on one thing: a signature computed with a shared secret.

Getting that right is mostly a checklist, but it is a checklist with real failure modes behind each item — replayed deliveries, silently broken signatures caused by your own framework, and race conditions between verification and business logic. This post walks through the receiver side: how the common signing schemes work, how to verify them in Go, and how to build an endpoint that survives both attackers and legitimate duplicate deliveries.

Read the raw body, or the signature dies

The first trap is your own framework. An HMAC signature is computed over the exact bytes the sender transmitted. Most web frameworks parse the JSON body into an object before your handler runs, and if you re-serialize that object to check the signature, it will not match — key order, whitespace, and escaping all differ. The signature check must happen against the raw request body, read before any parsing.

In Go’s net/http, this is easy because r.Body is the raw stream until you choose to decode it. In frameworks with body-parsing middleware, you usually need a way to disable parsing for the webhook route, or to read the raw bytes first and stash them for later. If your webhook verification “works locally but fails in production,” a proxy or middleware rewriting the body or stripping headers is the usual culprit.

The two signing schemes you will actually meet

Most providers use one of two schemes. The simplest is a single HMAC over the raw body, sent as a header. GitHub’s webhooks work this way: configure a secret, and every delivery carries an X-Hub-Signature-256 header containing sha256= followed by the hex-encoded HMAC-SHA256 of the payload:

func sign(secret, body []byte) string {
    mac := hmac.New(sha256.New, secret)
    mac.Write(body)
    return "sha256=" + hex.EncodeToString(mac.Sum(nil))
}

func verifyGitHub(secret, body []byte, header string) bool {
    return hmac.Equal([]byte(sign(secret, body)), []byte(header))
}

This scheme authenticates the payload but says nothing about when it was signed. A delivery you once sent over plain HTTP, or a signature leaked from any proxy log, remains valid forever. An attacker who captures a valid body-plus-signature pair can replay it at any time and it will verify cleanly.

The second scheme fixes that by putting a timestamp inside the signed material. Stripe’s webhooks are the canonical example. The Stripe-Signature header carries a timestamp and one or more signatures, comma-separated:

Stripe-Signature: t=1733160000,v1=5f7b...

The signed payload is the timestamp and the body joined with a period — <t>.<body> — and the signature is the HMAC-SHA256 of that string with the endpoint’s secret. Because the timestamp is part of what is signed, an attacker cannot replay an old delivery with a freshened timestamp without invalidating the signature. The receiver then enforces a tolerance window: if the signed timestamp is more than a few minutes old (five minutes by default in Stripe’s libraries), the delivery is rejected even though the signature itself is perfectly valid.

func verifyStripe(secret []byte, body []byte, header string, tolerance time.Duration) error {
    var ts int64
    var sigs []string
    for _, part := range strings.Split(header, ",") {
        k, v, _ := strings.Cut(strings.TrimSpace(part), "=")
        switch k {
        case "t":
            ts, _ = strconv.ParseInt(v, 10, 64)
        case "v1":
            sigs = append(sigs, v)
        }
    }
    if ts == 0 || len(sigs) == 0 {
        return errors.New("malformed signature header")
    }
    if time.Since(time.Unix(ts, 0)) > tolerance {
        return errors.New("signature timestamp outside tolerance window")
    }

    signed := fmt.Sprintf("%d.", ts)
    mac := hmac.New(sha256.New, secret)
    mac.Write([]byte(signed))
    mac.Write(body)
    expected := hex.EncodeToString(mac.Sum(nil))

    for _, s := range sigs {
        if hmac.Equal([]byte(expected), []byte(s)) {
            return nil
        }
    }
    return errors.New("signature mismatch")
}

One warning that trips people up: the comparison must be constant-time, because a normal string equality check leaks how many leading bytes of the signature matched. Go’s crypto/hmac.Equal handles this; in other ecosystems the equivalent is crypto.timingSafeEqual or your framework’s secure_compare. The same concern applies to the simple GitHub-style scheme.

Verification is necessary but not sufficient

A valid signature proves the sender sent this payload at some point. It does not prove this is the first time you are seeing it. Providers retry aggressively: your endpoint answered 500, the connection dropped after your handler committed the transaction but before the response reached the sender, or a load balancer timed out. Every one of those produces a legitimate duplicate delivery. If your handler double-processes it — charging the customer twice, double-counting the signup — the bug is yours, not the sender’s.

The standard fix is an event ID plus a deduplication store. Every webhook payload carries an event identifier; the receiver records processed IDs and skips ones it has already handled. The check-and-record must be atomic (a unique constraint on an events table is the simplest durable version), because retries can arrive while the first attempt is still being processed by a second worker.

Note the division of labor here: the timestamp tolerance handles malicious replays, and the deduplication store handles legitimate retries. You need both, and they are not interchangeable — a tight tolerance window will eventually reject a real retried delivery, since senders legitimately retry events hours later after prolonged outages, and generate a fresh signature and timestamp on each attempt.

Acknowledge fast, process later

Senders expect a quick 2xx and treat anything else — including a timeout — as a failed delivery that goes back into the retry queue. If your handler does the full business flow inline (update the database, call third-party services, send emails), a slow downstream dependency converts into hundreds of redundant retries, which then further overload the very dependencies that made you slow. It is a self-amplifying loop.

The robust shape is: verify, deduplicate, enqueue, respond. The handler commits the raw event to a durable queue and returns 200; a separate worker processes the queue with your normal retry and observability machinery. This also decouples your endpoint’s availability from your processing pipeline — the sender only needs your ingest to be up.

func webhookHandler(store *EventStore, q *Queue) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        body, err := io.ReadAll(r.Body)
        if err != nil || len(body) == 0 {
            http.Error(w, "bad request", http.StatusBadRequest)
            return
        }
        if err := verifyStripe(secret, body, r.Header.Get("Stripe-Signature"), 5*time.Minute); err != nil {
            http.Error(w, "invalid signature", http.StatusBadRequest)
            return
        }

        var evt WebhookEvent
        if err := json.Unmarshal(body, &evt); err != nil {
            http.Error(w, "bad payload", http.StatusBadRequest)
            return
        }

        // Returns false if this event ID was already recorded.
        inserted, err := store.RecordOnce(r.Context(), evt.ID, body)
        if err != nil {
            http.Error(w, "storage error", http.StatusInternalServerError)
            return
        }
        if !inserted {
            w.WriteHeader(http.StatusOK) // duplicate: already queued or processed
            return
        }

        if err := q.Enqueue(r.Context(), evt.ID, body); err != nil {
            http.Error(w, "queue error", http.StatusInternalServerError)
            return
        }
        w.WriteHeader(http.StatusOK)
    }
}

Return 4xx for verification failures — the sender should not retry a request you consider hostile or malformed — and 5xx only for failures on your side that you genuinely want retried.

Secrets, rotation, and endpoint hygiene

Two last pieces of operational hygiene. First, use a distinct secret per endpoint. When a secret leaks — and eventually one will, through a log line that printed headers or a config file that got shared — a per-endpoint secret contains the blast radius, and rotating it means updating one consumer instead of every consumer you have. When you do rotate, briefly accept both the old and new secrets during the overlap window, or you will reject deliveries until the sender’s secret update propagates.

Second, remember what the signature does and does not protect. It authenticates the payload; it does nothing for the URL itself. An endpoint URL that leaked without its secret is useless to an attacker — every request they send fails verification. That asymmetry is the whole point: treat the URL as public, treat the secret as the credential, and put the verification before any parsing, any processing, and any side effect.

Most webhook disasters are not exotic attacks. They are frameworks mangling a raw body, handlers double-charging on a retried delivery, or a tolerance window of zero quietly disabling the recency check. The checklist above covers all three, and once it is in place, the same handler skeleton works for nearly every provider you will integrate with.

Leave a Reply

Your email address will not be published. Required fields are marked *