Production Webhook Pipelines: HMAC Verification, Fast Ack, Deduplication, and Ordering
Published
2 min read
Messaging and payment providers deliver inbound messages, delivery receipts, and billing events via HTTP webhooks. Treating a webhook endpoint like a slow synchronous controller causes provider timeouts, retry storms, duplicate AI replies, and corrupted status transitions.
The Five Rules of Reliable Webhook Ingestion
| Rule | Why It Matters | Implementation Detail |
|---|---|---|
| 1. Verify HMAC on raw bytes | Prevents forged events and replay tampering | Compute HMAC-SHA256 over raw body; compare with timingSafeEqual |
| 2. Acknowledge fast (< 1-2s) | Providers retry aggressively if HTTP 200 is slow | Persist or enqueue work asynchronously, then return 200 OK |
| 3. Deduplicate by provider event ID | Providers guarantee at-least-once delivery, not once | Unique constraint on (provider, externalEventId) |
| 4. Handle out-of-order statuses | read receipt can arrive before delivered or sent | Enforce monotonic state rank (queued < sent < delivered < read) |
| 5. Isolate poison payloads | One malformed event must not block a whole webhook batch | Process entries independently; log schema mismatches without 500-looping |
Timing-Safe Signature Verification
ts
import { createHmac, timingSafeEqual } from "node:crypto";
export function verifyHmacSha256Signature(
rawBody: Buffer,
headerSignature: string | null,
secret: string
): boolean {
if (!headerSignature || !headerSignature.startsWith("sha256=")) {
return false;
}
const expected = Buffer.from(
`sha256=${createHmac("sha256", secret).update(rawBody).digest("hex")}`,
"utf8"
);
const actual = Buffer.from(headerSignature, "utf8");
return expected.length === actual.length && timingSafeEqual(expected, actual);
}
Monotonic Status Transitions
When delivery receipts arrive out of order, a naive UPDATE messages SET status = $newStatus can overwrite read backward to delivered, breaking campaign funnels and UI read indicators. Assign each status an integer rank and update only when new_rank > current_rank (while still recording timestamps for every observed transition).
Next: combine signals, timers, and monotonic webhooks to build responsive customer journeys in Engineering Reply-Aware Follow-Up Sequences.
Was this helpful?