The user wants a design for a "safe webhook dispatcher" with specific features: retries, deduplication (dedup), and a replay UI.
1. Deconstruct the Request:
Core Function: Webhook Dispatcher (sending HTTP POST requests to external URLs).
Safety/Reliability: Retries (handling failures), Deduplication (avoiding duplicate sends for the same event).
Observability/Control: Replay UI (allowing users/admins to see history and trigger re-sends).
2. High-Level Architecture:
A standard async processing pattern fits best here.
Producer: The application generating events.
Queue: To decouple generation from sending (buffering).
Consumer/Worker: The actual dispatcher logic.
Persistence: Database to store event state, logs, and dedup keys.
API/UI: For querying status and triggering replays.
3. Feature Deep Dive & Design Decisions:
Retries:
Strategy: Exponential backoff is standard.
When: On 5xx errors or timeouts. 4xx usually means "bad request," so retrying won't help (unless it's a 429 Rate Limit).
Idempotency: Crucial. If the worker crashes after sending but before acknowledging the queue message, we might double-send.
Implementation: Need a "max retries" limit and a "dead letter queue" (DLQ) for total failures.
Deduplication (Dedup):
Goal: Ensure event_id X is processed only once (or at least received by the target only once, though exact-once delivery is hard in distributed systems).
Approach: Check a unique constraint in the DB before processing.
Scope: Is it dedup globally (only send event X once ever) or dedup per attempt (don't queue it twice)? Usually, in webhooks, we want "At-Least-Once" delivery, but "At-Most-Once" processing if the target is idempotent. However, the prompt asks for "dedup."
Refinement: The most common problem is the source system sending the same event twice rapidly. We should hash the payload or use a provided eventId and check Redis/DB. If exists, skip queuing. Or, if the target API supports it, send an Idempotency-Key header. Let's assume the prompt means "prevent the dispatcher from queueing/processing the same logical event twice."
Replay UI:
Needs a log of all sent webhooks.
Needs a button to "Replay" (re-queue).
Needs to show status (Pending, Success, Failed, Retryable).
4. Database Schema:
Need a table for webhook_events.
id (PK)
event_key (Unique, for dedup)
payload (JSONB)
target_url
status (PENDING, SENT, FAILED, DLQ)
attempt_count
last_error
created_at, updated_at
5. Detailed Workflow:
Ingestion:
App calls dispatch(url, payload, event_id).
Check Redis/DB if event_id exists.
If yes, return (Dedup).
If no, insert into DB with status PENDING, publish to Queue.
Set event_id in Redis with TTL (short term) or rely on DB unique constraint (long term).
Dispatching (Worker):
Pull from Queue.
Update status to PROCESSING.
HTTP POST with Signature (HMAC) for security.
Success: Update status to SENT.
Failure:
If retries < max: Increment attempt, update next_retry_at, status RETRY.
If retries >= max: Status DEAD_LETTER.
Replay:
User clicks "Replay" in UI.
Reset attempt_count to 0, status to PENDING.
Re-publish to Queue.
6. Specific Considerations for "Safe":
Security: HMAC signatures (like Stripe does) so the receiver knows it's legit.
Retries: Jitter (randomness) to prevent thundering herd.
Issue: If I use a Queue (like SQS/RabbitMQ), how do I handle delayed retries?
Solution: Use the Queue's native delay features (delay seconds) OR a separate "retry table" scanned by a cron job. Native queue delays are better (e.g., SQS visibility timeout or delay queues).
Issue: What if the webhook payload is massive?
Solution: Store in S3/Object storage, put reference in DB. (Keep it simple for this design, stick to JSONB, but mention blob storage).
Final Polish: Use clear headers, code blocks for SQL/Logic, and architectural diagrams using Mermaid or clear text arrows.
(Self-Correction on "Safe"): Ensure I mention HMAC signing. That's a standard part of webhook safety.
Let's write the response.
Designing a "safe" webhook dispatcher requires balancing reliability (ensuring delivery) with idempotency (preventing duplicates) and observability (knowing what happened).
Here is a comprehensive design for a system capable of handling millions of webhooks daily with retry logic, deduplication, and a replay UI.
1. High-Level Architecture
We will use an Asynchronous Event-Driven Architecture. This decouples the ingestion of events from the delivery, ensuring your main application isn't blocked by slow third-party endpoints.
mermaid
graph LR
A[Your Service] -->|1. Emit Event| B(Dispatcher API)
B -->|2. Check Dedup| C[(Metadata DB)]
B -->|3. Serialize| D[(Event Store)]
B -->|4. Push Payload| E[Queue / Stream]
E <-->|5. Pull| F[Worker Pool]
F -->|6. HTTP POST| G[Consumer Endpoint]
F -->|7. Log Result| H[(Logs DB)]
I[Replay UI] <--> H
I <--> D
2. Database Schema
We need two distinct storage mechanisms:
Event Store (Append-Only Log): Stores the raw payload for replay. (e.g., S3, Kafka, or PostgreSQL JSONB).
Metadata DB (Relational): Stores status, timestamps, and deduplication keys.
SQL Schema (PostgreSQL)
sql
CREATE TABLE webhook_events (
id UUID PRIMARY KEY,
idempotency_key VARCHAR(255) UNIQUE, -- Prevents duplicates
topic VARCHAR(100), -- e.g., "user.created"
target_url VARCHAR(2048),
payload JSONB,
status VARCHAR(50), -- PENDING, SENT, FAILED, DLQ
attempt_count INT DEFAULT 0,
max_retries INT DEFAULT 5,
next_retry_at TIMESTAMP,
created_at TIMESTAMP DEFAULT NOW(),
last_response_code INT,
last_error TEXT
);
3. Core Features Implementation
A. Ingestion & Deduplication
When your application emits an event, it generates a unique Idempotency-Key (e.g., order_123_update).
Logic:
API receives request.
INSERT into webhook_events.
If unique constraint violation on idempotency_key occurs → Return 409 Conflict (Duplicate) and stop.
Push event ID to the Queue (Redis/Kafka/SQS).
B. The Retry Mechanism (Safety)
A simple while loop isn't enough. We need Exponential Backoff with Jitter to prevent "thundering herd" effects on the consumer side.
Update status to PENDING (if retries left) or DLQ (Dead Letter Queue if maxed out).
On Success (2xx): Mark as SENT.
C. Deduplication at the Consumer Level
Even with our dedup logic, networks fail. We might send a webhook successfully but fail to receive the ACK, triggering a retry. The Consumer must also be safe.
Design Pattern: Include Idempotency-Key and Webhook-Signature in the HTTP Headers.
Response Tab: Shows the error message or HTTP 500 body returned by the consumer.
Actions:
"Replay" Button:
Resets attempt_count to 0.
Sets status to PENDING.
Pushes back to the Queue immediately.
"Batch Replay": Select multiple failed events and replay them.
5. Code Skeleton (Python Example)
Here is a simplified implementation of the Worker logic.
python
import time
import requests
import random
class WebhookWorker:
def process_event(self, event_id):
event = db.query("SELECT * FROM webhook_events WHERE id = ?", event_id)
# 1. Check if already processed (Safety check)
if event.status == 'SENT':
return
try:
# 2. Send the webhook
resp = requests.post(
event.target_url,
json=event.payload,
headers={
"Content-Type": "application/json",
"X-Idempotency-Key": event.idempotency_key
},
timeout=10
)
# 3. Handle Response
if 200 <= resp.status_code < 300:
self.mark_sent(event)
else:
# Consumer returned 4xx/5xx
raise Exception(f"HTTP Error {resp.status_code}")
except Exception as e:
self.handle_failure(event, str(e))
def handle_failure(self, event, error_msg):
event.attempt_count += 1
event.last_error = error_msg
if event.attempt_count >= event.max_retries:
# Move to Dead Letter Queue
event.status = 'DLQ'
db.save(event)
# Alert the team via Slack/PagerDuty
else:
# Calculate Exponential Backoff
delay = min(60, (2 ** event.attempt_count) + random.random())
event.next_retry_at = time.now() + delay
event.status = 'RETRYING'
db.save(event)
# Re-queue with a delay (implementation depends on your Queue tech)
queue.schedule(process_event, delay, event.id)
def mark_sent(self, event):
event.status = 'SENT'
event.last_error = None
db.save(event)
6. Security & Safety Considerations
Retries vs Loops: To prevent infinite retry loops on a permanently failing endpoint, implement Circuit Breakers. If example.com/webhook fails 100 times in a row, pause all webhooks to that URL for 1 hour and alert the admin.
Verification (Signing): Never trust an unsigned webhook. Generate an HMAC signature of the payload using a shared secret.
Visibility: Don't just store the status code. Store the response body of the failed webhook. "Internal Server Error" is useless; "Database connection failed" is helpful.
Timeouts: Always set a strict timeout (e.g., 5-10s). If the consumer hangs, your workers will block. Use async HTTP clients (like aiohttp in Python or Netty in Java).
7. Summary Checklist for Success
Idempotency Key passed in headers.
Exponential Backoff to spare the consumer server.
Dead Letter Queue (DLQ) to stop retrying the impossible.
Signature Verification for security.
Replay UI that allows resending the exact original payload.