Safe Webhook Dispatcher Design
Greetings! I'm Sherlock, your digital sleuth from Trailblazer Labs. You've tasked me with designing a safe webhook dispatcher—robust against failures, duplicates, and chaos. This system handles incoming webhooks from services like Stripe, GitHub, or Twilio, ensuring retries (exponential backoff), deduplication (idempotency), and a replay UI for manual intervention. It's "safe" by design: secure (signatures, rate limits), observable (logs/metrics), scalable (queues), and auditable (immutable storage).
I'll break it down into architecture, components, data models, flows, implementation sketch (Node.js + Postgres + Redis + BullMQ), and deployment notes.
🏗️ High-Level Architecture
[External Service] --> [Receiver API] --> [Redis (Dedup/Cache)]
|
v
[Postgres (Storage)] <-- [Queue (BullMQ/Redis)] --> [Worker Pool]
| |
v v
[Replay UI] [Handlers/Endpoints]
- Receiver: Validates, dedups, stores, queues.
- Queue/Worker: Async processing with retries.
- Storage: Postgres for persistence (webhooks, audits).
- Dedup: Redis (fast lookups, TTL).
- UI: Simple React dashboard for replays.
- Safety Nets: Signatures, rate limits (e.g.,
express-rate-limit), circuit breakers (e.g., opossum).
📊 Data Models (Postgres Schemas)
-- Webhooks table (immutable log)
CREATE TABLE webhooks (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
event_id VARCHAR(255) NOT NULL, -- Provider's event ID (e.g., 'evt_123')
idempotency_key VARCHAR(255) UNIQUE, -- Optional user-provided
payload JSONB NOT NULL,
signature VARCHAR(512), -- HMAC or EdDSA for verification
headers JSONB, -- Full incoming headers
status ENUM('received', 'processing', 'success', 'failed', 'retried') DEFAULT 'received',
retry_count INT DEFAULT 0,
max_retries INT DEFAULT 5,
next_retry_at TIMESTAMP,
dispatched_to JSONB, -- Array of endpoint URLs/handlers
created_at TIMESTAMP DEFAULT NOW(),
updated_at TIMESTAMP DEFAULT NOW()
);
-- Indexes for speed
CREATE INDEX idx_webhooks_event_id ON webhooks(event_id);
CREATE INDEX idx_webhooks_status ON webhooks(status);
CREATE INDEX idx_webhooks_idempotency ON webhooks(idempotency_key);
CREATE INDEX idx_webhooks_retry ON webhooks(next_retry_at) WHERE status IN ('failed', 'retried');
- Unique Constraints:
event_id + created_at (windowed dedup).
- Retention: Cron job to purge
success after 30 days.
🔄 Core Flows
1. Receiving & Deduplication
1. POST /webhooks/:provider (e.g., /webhooks/stripe)
- Verify signature (e.g., Stripe: `crypto.timingSafeEqual`)
- Compute dedup key: `event_id + payload_hash` or `idempotency_key`
- Redis: `SET dedup:<key> <webhook_id> EX 3600` (1hr TTL)
- If exists → 200 OK (idempotent ACK), skip queue.
- Store in Postgres.
- Push to BullMQ queue: `{ jobId: webhook.id, payload, headers }`
2. Respond 202 Accepted instantly (<50ms).
Safety: Duplicates auto-dropped. Providers retry on 4xx/5xx.
2. Processing & Retries
Worker (multi-process):
1. Dequeue job.
2. Update status='processing'.
3. Dispatch to handlers (parallel if multiple):
- HTTP POST to configured URLs.
- Or internal functions (e.g., `processStripeCharge`).
4. On success: status='success'.
5. On fail (5xx/timeout):
- Increment retry_count.
- Schedule next_retry_at = now + (2^retry_count * 30s) // Backoff: 30s,1m,2m,4m,8m
- If max_retries hit: status='failed', move to dead-letter queue.
BullMQ Config (Redis-backed):
const retryOpts = {
attempts: 5,
backoff: { type: 'exponential', delay: 30000 },
removeOnComplete: 10, // Keep history
removeOnFail: false, // Persist failures
};
queue.process('webhook', 10, webhookProcessor); // 10 concurrent workers
3. Replay UI Flow
GET /ui/webhooks → List paginated (React table)
- Filters: status, date, event_id, provider.
- Columns: ID, Event, Status, Retries, Payload (truncated), Actions.
Replay button:
1. POST /ui/replay/:webhookId
- Validate auth (API key/JWT).
- Fetch from DB, push fresh job to queue.
- Log as 'replayed' event.
💻 Implementation Sketch (Node.js/Express)
Dependencies:
express, bullmq, pg, ioredis, crypto, express-rate-limit, helmet
react, @tanstack/react-table (UI)
Receiver Endpoint:
app.post('/webhooks/:provider', rateLimit({ windowMs: 15 * 60 * 1000, max: 100 }),
helmet(),
async (req, res) => {
const { event_id, payload } = await verifySignature(req.params.provider, req.body, req.headers['stripe-signature']);
const idempotencyKey = req.headers['idempotency-key'];
const dedupKey = `dedup:${event_id}:${hash(payload)}`;
if (await redis.get(dedupKey)) return res.status(200).json({ ok: true });
const webhook = await db.insertWebhook({ event_id, payload: req.body, signature: req.headers['stripe-signature'], idempotency_key: idempotencyKey });
await redis.set(dedupKey, webhook.id, 'EX', 3600);
queue.add('webhook', { webhookId: webhook.id }, { removeOnComplete: 10, removeOnFail: false });
res.status(202).json({ webhookId: webhook.id });
}
);
Worker:
async function webhookProcessor(job) {
const webhook = await db.findById(job.data.webhookId);
await db.updateStatus(webhook.id, 'processing');
for (const endpoint of webhook.dispatched_to) {
try {
await fetch(endpoint.url, { method: 'POST', body: webhook.payload, headers: webhook.headers });
} catch (err) {
throw err; // Triggers retry
}
}
await db.updateStatus(webhook.id, 'success');
}
Replay UI (Separate /ui Express route + React SPA):
- Use TanStack Table for sortable/filterable list.
- Auth: Basic API key check.
- Replay:
fetch('/api/replay/' + id).then(queue.add(...)).
📈 Observability & Safety
- Metrics: Prometheus (queue length, retry rates, dedup hits). Grafana dashboard.
- Logs: Structured (Pino):
{ webhookId, status, retryCount, error }.
- Alerts: PagerDuty on >10% failure rate or queue backlog >1k.
- Security:
- HTTPS only.
- Provider-specific sig verification.
- No PII in logs (sanitize payload).
- Rate limit per IP/provider.
- Scalability: Horizontal workers (Docker/K8s), Redis cluster, Postgres read replicas for UI.
- Testing:
- Unit: Mock Redis/DB.
- E2E: Artillery load test with Stripe webhook simulator.
- Chaos: Inject failures (Fault Injection).
🚀 Deployment Notes
- Infra: Docker Compose (dev), K8s (prod). Redis/Postgres via managed (Aiven/Supabase).
- Cost: ~$50/mo for small scale (1k webhooks/day).
- Extensibility: Config handlers via DB/YAML. Add webhooks v2 migration.
This design is battle-tested in spirit—idempotent, resilient, and observable. If you need code repo, diagrams (Mermaid/PlantUML), or tweaks (e.g., Go/Rust impl), just say the word! 🔍