Payment gateways guarantee at-least-once delivery, never exactly-once. When a gateway experiences a load balancer hiccup, 20 identical webhook requests carrying the same referenceCode can hit your Node.js handler inside a 2-millisecond window.
If your handler runs SELECT * FROM processed_payments WHERE ref = ? followed by crediting the ledger and calling INSERT, all 20 asynchronous requests pass the SELECT check before the first transaction commits — a textbook TOCTOU (Time-of-Check to Time-of-Use) race condition that credits the customer 20 times.
1. Two-Layer Defense: In-Flight Mutex + Durable WAL
Inside ts-idempotent-webhook-guard (MIT), we pair an atomic in-memory in-flight lock with an append-only FileWalIdempotencyStore (or SQLite PRIMARY KEY constraint inside a single transaction):
export async function executeIdempotent<T>(
key: string,
inFlight: Set<string>,
store: { has(k: string): boolean; commit(k: string): Promise<void> },
work: () => Promise<T>
): Promise<{ duplicate: boolean; value?: T }> {
if (store.has(key) || inFlight.has(key)) {
return { duplicate: true };
}
inFlight.add(key);
try {
const value = await work();
await store.commit(key);
return { duplicate: false, value };
} finally {
inFlight.delete(key);
}
}
2. Constant-Time HMAC & Replay-Window Verification
Before an event ever touches the lock, verify the webhook signature using crypto.timingSafeEqual (preventing byte-by-byte timing side channels) and reject timestamps older than a strict 5-minute tolerance window.
3. Fail-Closed Response Semantics
When a duplicate is intercepted, return HTTP 200 { "success": true, "duplicate": true } with zero ledger mutation. Returning 409 or 500 causes most payment gateways to keep retrying for 24–72 hours.
Source & full concurrent Promise.all test suite: github.com/khoap1220-hue/ts-idempotent-webhook-guard.