Resilient Webhook Receiver Design
As Sherlock Holmes might deduce from scattered clues, a resilient webhook receiver must verify authenticity, thwart replays, and enforce order amid network chaos. This design ensures at-least-once delivery with idempotency , signature verification , replay protection , and strict in-order processing per event stream.
Key Assumptions
Webhooks are POST JSON payloads from a trusted provider (e.g., Stripe, GitHub).
Payload includes:
json Copy code
{
"stream_id": "source-123", // Identifies stream (e.g., per-user or per-tenant)
"sequence": 42, // Monotonic increasing integer per stream
"event_id": "uuid-v4-unique", // Globally unique ID
"timestamp": "2023-10-01T12:00:00Z", // ISO 8601
"data": { ... } // Event payload
}
Signature header: X-Webhook-Signature: hmac-sha256=base64-hmac-of-raw-body.
Shared secret stored securely (e.g., env var or Vault).
Tech stack: Python (Flask), Redis (for fast lookups/buffering), Celery (async queue for processing).
Resilience: Idempotent handlers, retries, dead-letter queue (DLQ).
Architecture Overview
code Copy code
Inbound Webhook → Flask Endpoint
↓ (1. Signature)
Verified? → No: 4xx
↓ (2. Replay Check)
Seen? → Yes: 200 (idempotent ACK)
↓ (3. Order Check & Buffer)
In-order? → Buffer in Redis → Retry later
↓ (4. Queue)
Celery Task → Process → Mark Processed
↓ (Failure)
DLQ → Manual Review
Redis Keys :
Key Type Purpose TTL seen:event:{event_id}String Replay check 24h stream:{stream_id}:expectedString (int) Next expected sequence None stream:{stream_id}:bufferSorted Set (score=seq) Out-of-order events: {event_id: json_payload} 1h stream:{stream_id}:processed_maxString (int) Highest processed seq None
1. Signature Verification
Compute HMAC-SHA256 of raw body using shared secret.
Compare with header (constant-time to prevent timing attacks).
Tolerates minor clock skew (±5min).
python Copy code
import hmac
import hashlib
import time
from flask import Flask, request, abort
app = Flask(__name__)
SECRET = "your-shared-secret".encode()
def verify_signature(payload: bytes, signature: str) -> bool:
expected = "hmac-sha256=" + hmac.new(SECRET, payload, hashlib.sha256).hexdigest()
return hmac.compare_digest(expected, signature)
2. Replay Protection
Check event_id in Redis set.
If seen, ACK 200 (idempotent—no reprocessing).
Add on accept (TTL prevents storage bloat).
python Copy code
import redis
import json
from datetime import datetime, timedelta
r = redis.Redis(host='localhost', port=6379, db=0)
def check_replay(event_id: str) -> bool:
return r.exists(f"seen:event:{event_id}")
def mark_seen(event_id: str):
r.setex(f"seen:event:{event_id}", 86400, "1") # 24h TTL
3. Ordering & Buffering
Fetch expected seq for stream_id.
If seq == expected: Process immediately.
If seq > expected + WINDOW (e.g., 100): Reject (gap too large).
Else: Buffer in sorted set. Poll buffer periodically.
On process: Advance expected to processed_max + 1.
Windowed Reordering : Allows minor out-of-order (e.g., network jitter).
python Copy code
WINDOW_SIZE = 100
def get_expected(stream_id: str) -> int:
return int(r.get(f"stream:{stream_id}:expected") or 0)
def buffer_event(stream_id: str, seq: int, event_json: str):
r.zadd(f"stream:{stream_id}:buffer", {event_json: seq})
def try_process_next(stream_id: str):
expected = get_expected(stream_id)
buffered = r.zrangebyscore(f"stream:{stream_id}:buffer", expected, expected)
if buffered:
event_json = buffered[0].decode()
r.zrem(f"stream:{stream_id}:buffer", event_json)
process_event(json.loads(event_json)) # Celery task
r.set(f"stream:{stream_id}:expected", expected + 1)
try_process_next(stream_id) # Recurse for chain
Periodic Poller (Celery beat task, every 5s):
python Copy code
# Fetch all streams, call try_process_next(stream_id)
4. Full Endpoint
python Copy code
@app.route('/webhook', methods=['POST'])
def webhook():
raw_body = request.get_data()
signature = request.headers.get('X-Webhook-Signature')
if not verify_signature(raw_body, signature):
abort(401)
event = json.loads(raw_body)
event_id, stream_id, seq, ts = event['event_id'], event['stream_id'], event['sequence'], event['timestamp']
# Replay check
if check_replay(event_id):
return '', 200
# Timestamp skew check
ts_dt = datetime.fromisoformat(ts.replace('Z', '+00:00'))
if abs((datetime.utcnow() - ts_dt).total_seconds()) > 300:
abort(400)
expected = get_expected(stream_id)
if seq < expected:
return '', 200 # Already processed
elif seq > expected + WINDOW_SIZE:
abort(400, "Sequence gap too large")
mark_seen(event_id)
event_json = json.dumps(event)
if seq == expected:
# Queue directly
process_event.delay(event) # Celery
r.set(f"stream:{stream_id}:expected", expected + 1)
else:
buffer_event(stream_id, seq, event_json)
return '', 200
5. Async Processing (Celery)
python Copy code
from celery import Celery
celery = Celery('webhook', broker='redis://localhost:6379/1')
@celery.task(bind=True, max_retries=5)
def process_event(self, event):
try:
stream_id = event['stream_id']
seq = event['sequence']
# Your business logic: idempotent! (e.g., UPSERT DB by event_id)
# Update processed_max
current_max = int(r.get(f"stream:{stream_id}:processed_max") or 0)
r.set(f"stream:{stream_id}:processed_max", max(current_max, seq))
except Exception as exc:
if self.request.retries < 5:
raise self.retry(countdown=60 * (2 ** self.request.retries))
# DLQ: r.lpush('dlq', json.dumps(event))
Resilience Enhancements
Idempotency : Handlers use event_id as DB key.
Retries : Celery exponential backoff.
Monitoring : Prometheus metrics (e.g., buffer size, reject rate).
Scaling : Multiple Flask instances → Redis fan-out.
Failures : Health checks, circuit breakers (e.g., tenacity).
Security : Rate limiting (e.g., Flask-Limiter), HTTPS only.
Testing : Mock Redis, inject out-of-order payloads.
This design handles 99.9% of real-world issues: duplicates, delays, partitions. Deploy with Docker/K8s for HA. Questions on implementation? The game is afoot!