Backend Security··2 min read

Stopping Webhook Replay Attacks and Duplicate Processing With HMAC-SHA256 Timestamp Windows and Redis SETNX

Shafikul Islam

Shafikul Islam

Backend & Cloud Infrastructure Engineer · Infrastructure & Cloud Team Lead

Stopping Webhook Replay Attacks and Duplicate Processing With HMAC-SHA256 Timestamp Windows and Redis SETNX

Why HMAC Signature Verification Alone Is Not Enough

If your webhook endpoint verifies X-Signature: sha256=... against the raw JSON body and immediately processes the event, your API is still vulnerable to two failure modes:

  1. Replay Attacks: Anyone who captures a valid signed request from a proxy log can resend that exact HTTP payload hours later, and the signature will still match.
  2. Concurrent Webhook Retries: If your endpoint takes 4 seconds to respond, the sender may fire a retry while the first request is still running, executing the business logic twice.

1. Signing Timestamp + Raw Body Together

Following the Stripe/Svix webhook security model, the HMAC-SHA256 signature must cover both the Unix timestamp and the raw payload bytes (timestamp + "." + raw_body), and reject any request older than 300 seconds:

func VerifyWebhookEnvelope(headerTs, headerSig string, body []byte, secret []byte) error {
    ts, err := strconv.ParseInt(headerTs, 10, 64)
    if err != nil {
        return ErrInvalidTimestamp
    }
    if math.Abs(float64(time.Now().Unix()-ts)) > 300 {
        return ErrTimestampOutsideWindow
    }

    mac := hmac.New(sha256.New, secret)
    mac.Write([]byte(headerTs))
    mac.Write([]byte("."))
    mac.Write(body)
    expected := hex.EncodeToString(mac.Sum(nil))

    if !hmac.Equal([]byte(expected), []byte(headerSig)) {
        return ErrInvalidSignature
    }
    return nil
}

2. Atomic Deduplication Within the 300s Window via Redis SETNX

Rejecting requests older than 5 minutes bounds how long you need to remember processed event IDs. Instead of querying PostgreSQL on every duplicate retry, we claim the event_id atomically in Redis with a 600-second TTL:

claimed, err := rdb.SetNX(ctx, "webhook:dedup:"+eventID, "IN_FLIGHT", 10*time.Minute).Result()
if err != nil || !claimed {
    // Already processed or currently in-flight; return 200 OK to stop upstream retries
    w.WriteHeader(http.StatusOK)
    return
}

If downstream database processing fails transiently, the worker deletes the Redis key before returning HTTP 500 so legitimate backoff retries can succeed.

Infrastructure & PostgreSQL Advisory

Scaling Infrastructure or Diagnosing P95 Latency?

I help engineering teams diagnose PostgreSQL indexing bottlenecks, concurrency limits, and K3s/Docker deployments. Book a 20-minute call with me to review your setup.

Related Technical Articles