The user wants to build a "resilient webhook dispatcher" with specific features:
Retries: Handling failures by retrying delivery.
Deduplication (Dedup): Ensuring the same event isn't sent twice (idempotency).
Ordering: Ensuring webhooks for a specific entity (e.g., user ID) arrive in the order they were generated.
Signatures: Securing the payload so the receiver can verify integrity and authenticity.
This is a system design and implementation question. I need to provide a comprehensive guide, likely mixing architecture concepts with code examples (Python is usually a safe bet for this kind of logic, or Go/Java, but Python is very readable for prototypes).
Key Components:
Producer: The system generating events.
Queue/Buffer: To handle backpressure and decouple producers from consumers.
Dispatcher/Worker: The logic that pulls from the queue and sends HTTP requests.
Database: To store state (event logs, signatures, dedup keys).
Feature Breakdown & Strategy:
Retries:
Mechanism: Exponential backoff with jitter.
Trigger: HTTP status codes (5xx, 429) or network timeouts.
DLQ (Dead Letter Queue): Where events go when retries are exhausted.
Deduplication:
Mechanism: Unique Event ID (UUID).
Storage: Redis or a Database. Check if ID exists before processing/sending. Idempotency keys on the receiver side are also relevant, but the dispatcher needs to prevent double-sending if the queue duplicates messages.
TTL: We don't need to keep dedup keys forever.
Ordering:
Constraint: Global ordering kills throughput. We need partition/sequence ordering (e.g., all events for user_123 are ordered).
Mechanism:
Approach A (Simple): Single queue, single worker (Too slow).
Approach B (Kafka/Partitions): Use a partition key (e.g., User ID).
Approach C (DB Sequence): Store a version number per entity in the DB. Only dispatch the next one if the previous is acked. This is complex to implement from scratch.
Approach D (FIFO Queue with Message Group IDs - AWS SQS style): Easiest managed solution.
Implementation Detail: For a custom build, I'll likely use a "Queue per Entity" (too many queues) or a "Lease/Sequence" approach. Actually, the standard way is using a queue that supports partitioning (like Kafka) or a DB-driven state machine.
Simpler approach for code example: Use a monotonic sequence number per entity_id. The worker only processes the event if incoming_seq == last_processed_seq + 1. If it's ahead, re-queue/wait.
Signatures:
Standard: HMAC-SHA256.
Implementation: Hash the payload body + timestamp (to prevent replay attacks) using a shared secret. Include the signature in the header (X-Signature).
Architecture Plan:
Ingestion: API receives payload -> Generate ID -> Sign -> Push to Queue.
Queue: Redis Streams or RabbitMQ (supports ordering/consumer groups) or a generic "Job Queue".
Ordering: This is the trickiest. I will propose a "Sequence Manager" pattern where we track the last acknowledged sequence for a specific ID.
Refining the Ordering Logic:
Strict ordering with retries is hard. If Event 1 fails, Event 2 cannot be sent.
Strategy: If Event 1 fails and enters retry loop, Event 2 waits?
Implementation: Using Kafka is the "pro" answer.
Code Answer: I will simulate a FIFO queue per partition key or a simplified version using a database lock/sequence.
Simpler approach: The "Pending Queue" approach. Fetch events for an entity. Send them serially. If one fails, stop processing that entity for a cooldown period. This is easier to demo than a distributed consensus algorithm.
Let's stick to a Python-based simulation using Redis for state (Dedup/Sequence tracking) and requests for sending.
Components for the Code:
WebhookDispatcher class.
send_webhook method with retry logic.
sign_payload helper.
verify_sequence helper (Redis INCR or Lua script).
Self-Correction/Refinement:
Dedup: Is it just checking if we sent it? Or checking if we processed it? Usually, we store the event ID. If we see it again, we skip.
Ordering: How to handle the "wait"?
If Event 2 arrives, and Event 1 is still retrying, Event 2 must wait.
Solution: Use a "Sequence Lock". A worker picks up a job. Checks Redis: last_seq_for_user_123. If current_job_seq != last_seq + 1, put it back in the queue (or visibility timeout).
Wait, if we are generating the sequence at ingestion, we guarantee order in the queue (mostly). The main issue is when retrying Event 1 while Event 2 is ready.
Strict Order Policy: If Event 1 fails, we pause processing for that specific partition (Entity ID) until Event 1 succeeds or goes to DLQ.
Final Plan for the Output:
Architecture Overview: Visualizing the flow.
Security (Signatures): HMAC implementation.
Resiliency (Retries): Exponential backoff.
Integrity (Dedup & Ordering): The logic using Redis/DB.
Python Prototype: A complete, runnable script demonstrating these concepts.
Code Structure:
Event: Dataclass.
Signature: hmac usage.
Retry: tenacity (standard python library retrying or just write a loop for clarity). I'll write a loop for zero dependencies (except redis/requests) to show the logic clearly.
Ordering: I'll simulate a sequential ID generation.
Let's write the response. Focus on clarity and separation of concerns.
Key takeaway for the user: Don't build this from scratch if you can use managed services (AWS SQS FIFO, Kafka, Convoy/Socketkit). But if you must build it, here is how.
Drafting the Code:
I need a mock Redis or Storage class so the code is runnable without infrastructure.
The Mechanics: Deep dive into the 4 pillars (Retry, Dedup, Order, Sign).
Python Implementation: A robust, copy-pasteable class structure.
(Self-Correction during drafting): Ensure the signature includes a timestamp to prevent replay attacks, not just dedup. I will mention this in the security section.
Let's go.
Building a resilient webhook dispatcher requires shifting from a "fire and forget" mentality to a "guaranteed delivery" system. This involves persisting events, managing state, and implementing backpressure.
Here is a comprehensive guide to architecting and implementing this system.
1. Architecture Overview
A resilient system cannot be synchronous. The API receiving the webhook request should not wait for the destination server to respond.
Ingestion: Accept payload → Persist to DB → Acknowledge User (HTTP 202).
Queueing: A background process watches the DB/Queue for pending events.
Dispatching: The worker attempts to send the webhook.
Resolution:
Success: Mark as delivered, update deduplication log.
We will use Python for the logic examples, Redis for atomic state management (Dedup/Ordering), and a generic SQL DB for persistence.
Feature 1: Security (Signatures)
Before sending, you must sign the payload so the receiver can verify it wasn't tampered with. The industry standard is HMAC-SHA256.
python
import hmac
import hashlib
import time
def sign_payload(secret: str, payload: str, timestamp: int = None) -> str:
"""
Generates a signature in the format: t=<timestamp>,v1=<signature>
Similar to Stripe's webhook signature scheme.
"""
timestamp = timestamp or int(time.time())
# Construct the signed payload string
signed_payload = f"{timestamp}.{payload}"
# Generate HMAC-SHA256
signature = hmac.new(
secret.encode('utf-8'),
signed_payload.encode('utf-8'),
hashlib.sha256
).hexdigest()
return f"t={timestamp},v1={signature}"
# Usage
# headers = {'Webhook-Signature': sign_payload('my_secret', json_payload)}
Feature 2: Resilience (Retries & Backoff)
Simple retries aren't enough. You need Exponential Backoff with Jitter. If a server is down, retrying immediately floods it. Jitter (randomness) prevents the "thundering herd" effect.
python
import random
import time
def calculate_next_retry(attempt: int) -> int:
"""
Calculates delay in seconds.
Strategy: Full Jitter (https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/)
"""
# Base 2 exponential: 2, 4, 8, 16...
cap = 3600 # Max 1 hour wait
base_delay = 2 ** attempt
# Apply jitter: random between 0 and calculated delay
delay = min(cap, base_delay)
return random.randint(0, delay)
Feature 3: Deduplication
Networks fail. If your dispatcher sends a webhook but never receives the ACK (timeout), you might retry an event that was actually processed. This creates duplicate data.
Solution: Idempotency Keys.
Sender generates a unique event_id (UUID).
Receiver uses this ID to check if they already processed it.
Dispatcher Role: Store the event_id in a fast cache (Redis) for a short TTL (Time To Live) to locally filter out accidental double-schedules before they even hit the wire.
python
import redis
r = redis.Redis()
def is_duplicate(event_id: str) -> bool:
"""
Returns True if we have recently scheduled this event ID.
Uses SETNX (Set if Not Exists) for atomicity.
"""
# Key expires in 24 hours (86400 seconds)
was_set = r.set(name=f"dedup:{event_id}", value="1", nx=True, ex=86400)
return was_set is False
Feature 4: Ordering
Webhooks for the same entity (e.g., user_id: 100) must be processed in order (e.g., created before deleted). Global ordering kills performance; you need Partitioned Ordering.
Logic:
Group events by a Partition Key (e.g., user_id).
Only process one event per partition at a time.
If Event #2 arrives, wait until Event #1 is ACKed.
We can implement this using a Redis Stream or a Redis List acting as a queue per partition.
3. The Complete System (Code Prototype)
Here is a simplified WebhookWorker class incorporating all concepts.
python
import json
import requests
import logging
from dataclasses import dataclass
# Configuration
MAX_RETRIES = 5
WEBHOOK_SECRET = "super_secret_key"
@dataclass
class WebhookEvent:
event_id: str
partition_key: str # For ordering (e.g., user_id)
url: str
payload: dict
retry_count: int = 0
status: str = "pending"
class WebhookDispatcher:
def __init__(self):
self.redis = redis.Redis()
def _send_http(self, event: WebhookEvent) -> bool:
"""Handles the raw HTTP transmission and signature."""
payload_str = json.dumps(event.payload)
signature = sign_payload(WEBHOOK_SECRET, payload_str)
headers = {
'Content-Type': 'application/json',
'X-Event-ID': event.event_id,
'X-Signature': signature
}
try:
# Timeout is crucial to prevent hanging workers
resp = requests.post(event.url, data=payload_str, headers=headers, timeout=5)
return 200 <= resp.status_code < 300
except requests.RequestException:
return False
def process_event(self, event: WebhookEvent):
# 1. Deduplication Check (Local safety)
if is_duplicate(event.event_id):
logging.info(f"Duplicate event {event.event_id} skipped.")
return
# 2. Ordering Lock
# We use a Redis lock based on the partition key.
# This ensures sequential processing per user/entity.
lock_key = f"lock:{event.partition_key}"
lock = self.redis.lock(lock_key, timeout=10)
try:
# Acquire lock (blocking wait)
acquired = lock.acquire(blocking=True, blocking_timeout=5)
if not acquired:
# If we can't get the lock, another event for this user is processing.
# Re-queue this event with a delay.
self.requeue_event(event, delay=1)
return
# 3. Execute
success = self._send_http(event)
if success:
logging.info(f"Event {event.event_id} dispatched successfully.")
self.mark_completed(event)
else:
self.handle_failure(event)
finally:
# Release lock safely
try:
lock.release()
except:
pass
def handle_failure(self, event: WebhookEvent):
event.retry_count += 1
if event.retry_count >= MAX_RETRIES:
logging.error(f"Event {event.event_id} failed permanently. Dead Letter Queue.")
self.move_to_dlq(event)
else:
delay = calculate_next_retry(event.retry_count)
logging.info(f"Event {event.event_id} failed. Retry #{event.retry_count} in {delay}s.")
self.requeue_event(event, delay=delay)
# Stub methods for DB interactions
def mark_completed(self, event): pass
def move_to_dlq(self, event): pass
def requeue_event(self, event, delay): pass
4. Scaling & Operations
The code above handles the logic, but to make it production-ready, you need infrastructure:
The Database (Source of Truth):
Store events in a table with columns: id, status (pending, processing, success, failed), next_attempt_at.
Polling Query:SELECT * FROM webhooks WHERE status = 'pending' AND next_attempt_at <= NOW() LIMIT 100;
Visibility Timeouts:
When a worker picks up a job, update its status to processing. If the worker crashes, a "Heartbeat" or timeout mechanism must reset the status to pending so another worker can pick it up.
Dead Letter Queue (DLQ):
If an event fails MAX_RETRIES, do not delete it. Move it to a failed_webhooks table. Build an admin UI to inspect these payloads and manually retry them (crucial for debugging client bugs).
Monitoring:
Monitor two key metrics:
Lag: The time difference between created_at and delivered_at.
Error Rate by Endpoint: If one client is returning 500s, you might want to stop sending to them entirely (Circuit Breaking) to save resources.
5. Summary of the Flow
Receive request →Sign payload.
Check Redis for event_id duplicate. If unique, Save to DB.
Worker polls DB.
Worker acquires Partition Lock (Redis) based on user_id to guarantee order.
Worker sends HTTP POST with Signature header.
On failure: Calculate Jitter Backoff→ Update DB next_attempt_at.