How to Handle High-Concurrency Webhooks Without Dropping a Single Event
Traffic spikes shouldn't break your payment syncs or drop critical customer events. Learn how to architect a fault-tolerant, high-concurrency webhook ingestion pipeline using async queues, idempotency keys, and Dead Letter Queues—built for mission-critical B2B reliability.
On this page
- Why Synchronous Webhook Processing Fails at Scale
- The 4-Pillar Architecture for Zero-Loss Webhook Reliability
- 1. Instant Ingestion & Fast 200 OK Acknowledgment
- 2. Strict Idempotency & Deduplication
- 3. Controlled Concurrency via Background Workers
- 4. Exponential Backoff & Dead Letter Queues (DLQ)
- Production-Ready Implementation (Node.js + Express + BullMQ/Redis)
- Step 1: High-Speed Ingestion Endpoint (ingestion.js)
- Step 2: Idempotent Background Worker (worker.js)
- Production Checklist Before Going Live
- Frequently Asked Questions (FAQs)
- 1. What HTTP status code should a webhook endpoint return under high load?
- 2. How do you prevent duplicate webhook processing during retries?
- 3. Why should you never parse JSON before verifying a webhook signature?
- 4. What is the best message broker for high-concurrency webhook ingestion?
- 5. How do Dead Letter Queues (DLQs) protect webhook reliability?
- 6. How fast must a webhook receiver respond before timing out?
- Architecting Mission-Critical Systems with Causly
In modern B2B SaaS and enterprise software, webhooks are the nervous system connecting payment gateways (like Stripe or Razorpay), CRMs, and internal microservices. Under normal traffic, a simple REST endpoint that receives a payload and writes directly to your primary database works fine.
Until a traffic spike hits.
When thousands of webhook events arrive simultaneously—during a flash sale, a batch sync, or an upstream retry storm—synchronous architectures buckle. Database connection pools exhaust, API timeouts cascade, and your server returns 502 Bad Gateway or 504 Gateway Timeout. Once upstream providers exhaust their retry limits, critical business events vanish permanently.
Here is how to architect a zero-loss, high-concurrency webhook ingestion pipeline engineered for mission-critical reliability.
Why Synchronous Webhook Processing Fails at Scale#
Most webhook implementations fail during concurrency spikes because they couple event ingestion with business logic execution inside a single HTTP request lifecycle.
| Architectural Flaw | Production Consequence |
|---|---|
| Synchronous DB Writes | Heavy database locks slow down HTTP response times beyond provider timeout thresholds (typically 3–5 seconds). |
| Missing Signature Verification | Spoofed payloads bypass security or waste compute resources before validation. |
| No Idempotency Control | Network timeouts trigger upstream retries, resulting in duplicate invoices, double wallet credits, or corrupted state. |
| Lack of Fallback Queues | Unhandled exceptions crash worker threads and permanently discard payload data. |
To guarantee zero dropped events, your system must acknowledge receipt within milliseconds and offload all heavy processing asynchronously.
The 4-Pillar Architecture for Zero-Loss Webhook Reliability#
1. Instant Ingestion & Fast 200 OK Acknowledgment#
Your public-facing webhook endpoint should do only three things:
-
Verify the cryptographic signature (HMAC-SHA256) using the raw request body.
-
Push the raw payload into a durable, high-throughput message broker (such as Redis Streams, RabbitMQ, or Apache Kafka).
-
Return an immediate 200 OK or 202 Accepted HTTP status—ideally in under 50 milliseconds.
By decoupling ingestion from processing, your HTTP layer stays completely immune to database latency spikes.
2. Strict Idempotency & Deduplication#
Distributed systems guarantee at-least-once delivery, never exactly-once. If a provider doesn't receive your 200 OK fast enough, it will send the exact same event again.
Every incoming webhook contains a unique event identifier (e.g., evt_12345 or X-Request-ID). Before executing any business logic, your background worker must atomically check and lock that event_id in a fast key-value store (like Redis) or via a UNIQUE database constraint. If the ID already exists, safely ignore the duplicate.
3. Controlled Concurrency via Background Workers#
Instead of letting incoming HTTP traffic dictate your database load, pull events from your queue using a controlled pool of background workers. You can tune worker concurrency and rate limits to match the exact throughput capacity of your PostgreSQL or Supabase instance—preventing connection exhaustion even when 50,000 events hit your queue in ten seconds.
4. Exponential Backoff & Dead Letter Queues (DLQ)#
Transient failures—such as a third-party API blip or temporary network drop—should trigger automatic retries with exponential backoff and jitter (e.g., retrying after 2s, 4s, 8s, 16s).
If an event fails after maximum retry attempts (due to a malformed schema or edge-case bug), route it into a Dead Letter Queue (DLQ). A DLQ isolates poison payloads without blocking healthy traffic and allows engineers to inspect, patch, and replay failed events with zero data loss.
Production-Ready Implementation (Node.js + Express + BullMQ/Redis)#
Below is a clean, battle-tested pattern separating fast HTTP ingestion from idempotent background processing.
Step 1: High-Speed Ingestion Endpoint (ingestion.js)#
This endpoint verifies the webhook signature using the raw buffer, enqueues the job in Redis, and immediately responds to the sender.
import express from 'express';
import crypto from 'crypto';
import { Queue } from 'bullmq';
import IORedis from 'ioredis';
const app = express();
const connection = new IORedis(process.env.REDIS_URL, { maxRetriesPerRequest: null });
// Initialize durable queue with automatic exponential backoff
const webhookQueue = new Queue('webhook-events', {
connection,
defaultJobOptions: {
attempts: 5,
backoff: {
type: 'exponential',
delay: 2000, // 2s -> 4s -> 8s -> 16s -> 32s
},
removeOnComplete: 1000,
removeOnFail: false, // Retain failed jobs in DLQ for inspection & replay
},
});
// Capture raw body for accurate HMAC signature verification
app.post(
'/webhooks/provider',
express.raw({ type: 'application/json' }),
async (req, res) => {
try {
const signature = req.headers['x-webhook-signature'];
const expectedSignature = crypto
.createHmac('sha256', process.env.WEBHOOK_SECRET)
.update(req.body)
.digest('hex');
// Timing-safe comparison prevents timing attacks
if (!signature || !crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expectedSignature))) {
return res.status(401).json({ error: 'Invalid webhook signature' });
}
const payload = JSON.parse(req.body.toString('utf8'));
const eventId = payload.id;
if (!eventId) {
return res.status(400).json({ error: 'Missing event ID' });
}
// Enqueue with jobId = eventId to prevent duplicate queueing at the broker level
await webhookQueue.add(
payload.type,
{ eventId, payload },
{ jobId: eventId }
);
// Acknowledge immediately (< 50ms)
return res.status(202).json({ received: true, eventId });
} catch (err) {
console.error('Webhook ingestion error:', err);
return res.status(500).json({ error: 'Internal ingestion failure' });
}
}
);
app.listen(3000, () => console.log('High-concurrency webhook listener active on port 3000'));
Step 2: Idempotent Background Worker (worker.js)#
The worker processes events at a controlled concurrency rate and guarantees each event is processed strictly once.
import { Worker } from 'bullmq';
import IORedis from 'ioredis';
const connection = new IORedis(process.env.REDIS_URL, { maxRetriesPerRequest: null });
const worker = new Worker(
'webhook-events',
async (job) => {
const { eventId, payload } = job.data;
const idempotencyKey = `processed:webhook:${eventId}`;
// Atomic check-and-set: Ensure event hasn't already been committed
const isNewEvent = await connection.set(idempotencyKey, '1', 'NX', 'EX', 60 * 60 * 24 * 7);
if (!isNewEvent) {
console.log(`Skipping duplicate event: ${eventId}`);
return { status: 'duplicate_ignored' };
}
try {
// Execute core business logic / database transaction here
await processBusinessLogic(payload);
return { status: 'processed', eventId };
} catch (error) {
// Roll back idempotency lock if processing failed so retry can execute cleanly
await connection.del(idempotencyKey);
throw error; // Triggers BullMQ exponential backoff retry
}
},
{
connection,
concurrency: 20, // Process up to 20 events concurrently without overwhelming DB
}
);
async function processBusinessLogic(payload) {
// Replace with transactional DB updates, billing syncs, or internal triggers
console.log(`Executing business logic for event type: ${payload.type}`);
}
worker.on('failed', (job, err) => {
if (job.attemptsMade >= job.opts.attempts) {
console.error(`[ALERT - DLQ] Event ${job.data.eventId} permanently failed after max retries:`, err.message);
// Trigger Slack/PagerDuty alert for manual replay
}
});
Production Checklist Before Going Live#
-
Verify Raw Payloads: Never parse JSON before verifying HMAC signatures—whitespace changes alter hashes and break validation.
-
Set Alert Thresholds on Queue Depth: Monitor queue lag and Dead Letter Queue size so engineering teams catch downstream outages early.
-
Build a One-Click Replay Endpoint: Store raw payloads securely so failed DLQ events can be re-injected safely after bug fixes.
-
Isolate Database Pools: Keep background worker database connections separate from user-facing API pools so heavy webhook bursts never degrade frontend latency.
Frequently Asked Questions (FAQs)#
1. What HTTP status code should a webhook endpoint return under high load?#
A high-concurrency webhook endpoint should return 202 Accepted or 200 OK immediately (ideally in under 50ms) once the signature is verified and the payload is safely pushed to a durable message queue. Returning 202 Accepted signals to the sender that the event was received for asynchronous processing without forcing the provider to wait for database writes.
2. How do you prevent duplicate webhook processing during retries?#
Prevent duplicates by implementing idempotency keys. Extract the unique event identifier (such as event.id or X-Request-ID) and perform an atomic check-and-set in Redis (SET key value NX) or enforce a UNIQUE database constraint before running business logic. If the ID already exists, acknowledge and discard the duplicate event.
3. Why should you never parse JSON before verifying a webhook signature?#
Cryptographic signatures (HMAC-SHA256) are computed against the exact raw byte stream sent by the provider. Parsing the body into a JSON object and re-stringifying it can alter whitespace or key ordering, causing signature verification to fail and legitimate webhooks to be rejected with 401 Unauthorized.
4. What is the best message broker for high-concurrency webhook ingestion?#
For low-to-medium scale (up to 10,000 events/sec), Redis with BullMQ or Redis Streams provides ultra-low latency and simple deployment. For enterprise-grade streaming (100,000+ events/sec) requiring long-term event replay and strict partition ordering, Apache Kafka or AWS SQS + EventBridge is the standard choice.
5. How do Dead Letter Queues (DLQs) protect webhook reliability?#
A Dead Letter Queue isolates events that repeatedly fail processing after exhausting exponential backoff retries (e.g., due to downstream API outages or malformed payloads). Instead of dropping data or blocking active worker threads, the DLQ stores the raw payload safely so engineers can inspect, fix, and replay failed events later.
6. How fast must a webhook receiver respond before timing out?#
Most third-party providers enforce strict timeouts between 3 and 10 seconds (for example, Stripe enforces a 20-second hard limit, while Slack and GitHub expect responses within 3–5 seconds). Decoupling HTTP ingestion from background workers ensures consistent sub-50ms response times regardless of traffic spikes.
Architecting Mission-Critical Systems with Causly#
Building fault-tolerant, zero-loss infrastructure shouldn't slow down your core product roadmap. Causly is a specialized software engineering, SaaS, and AI automation partner that helps B2B companies design, build, and scale mission-critical systems.
From architecting high-throughput event pipelines and resilient backend APIs to building custom SaaS products and enterprise workflow automations, our engineering team eliminates single points of failure before they impact your customers.
Dealing with dropped webhooks, brittle third-party integrations, or database bottlenecks under load?
Partner with Causly to audit your current architecture or build a production-grade, zero-loss backend tailored to your stack.
Get new posts by email
High-signal notes on AI, automation and building systems. No spam.