Secure Webhooks Platform Design
This design outlines a scalable, secure webhooks platform for delivering events to user-defined endpoints. It supports retries , signatures , key rotation , replay UI , and quotas . The platform assumes you're the webhook provider (sending events to subscribers), with users managing subscriptions via your API/UI.
High-Level Architecture
code Copy code
┌─────────────────┐ ┌──────────────────┐ ┌──────────────────┐
│ User API/UI │◄──►│ PostgreSQL │◄──►│ Webhook Sender │
│ (Subscriptions, │ │ (Subs, Deliv, │ │ Service │
│ Replay, Quotas)│ │ Keys, Quotas) │ │ (w/ Retry Queue) │
└──────────┬──────┘ └────────┬────────┘ └────────┬──────────┘
│ │ │
│ │ │ HTTP POST
└────────────────────┘ │ (w/ Signatures)
│
┌────────▼────────┐
│ User Endpoints │
│ (HTTPS only) │
└─────────────────┘
Core Components
Database : PostgreSQL for subscriptions, deliveries, signing keys, quotas. Redis for queues/caches (e.g., rate limiting).
Services (e.g., Go/Node.js/Python microservices):
User API : REST/GraphQL for CRUD subscriptions, view/replay deliveries, rotate keys, check quotas.
Webhook Sender : Processes event queue, signs payloads, sends via HTTP client (w/ timeouts/retries), tracks status.
Retry Queue : Redis Streams or BullMQ/RQ for exponential backoff retries.
Frontend UI : React/Vue app for replay/monitoring (auth via JWT/OAuth).
Infra : Kubernetes/Docker, HTTPS (TLS 1.3), Cloudflare/AWS WAF for DDoS/IP filtering. Event ingestion via Kafka for high throughput.
Monitoring : Prometheus/Grafana for delivery rates, failures; Sentry for errors.
Payload Format (JSON)
json Copy code
{
"id": "evt_123abc", // Unique idempotency key
"event": "user.created", // Event type
"timestamp": 1640995200, // Unix timestamp
"data": { /* event payload */ },
"specversion": "1.0" // CloudEvents compliance
}
Sent as POST /webhook (user-defined path) with Content-Type: application/json.
Idempotency: Users check id to dedupe.
Feature Details
1. Signatures (Verification & Tamper-Proofing)
Mechanism : HMAC-SHA256 with per-subscription secret (256-bit, base64-encoded).
Header : X-Webhook-Signature: t=1640995200,v1=abc123def456
t: Timestamp (replay protection: reject if >5min old).
v1: Signature of t=<t>.m=<payload-sha256>,<payload>.
Implementation :
go Copy code
// Sender (pseudo-Go)
payloadHash := sha256(payload)
sigStr := fmt.Sprintf("t=%d,v1=%s", now.Unix(), hmac(secret, fmt.Sprintf("t=%d.m=%s,%s", now.Unix(), payloadHash, payload)))
Users verify similarly (libraries: webhook-signature npm, itsdangerous Py).
Security : Secrets never exposed in API responses. Rotate to invalidate old sigs.
2. Key Rotation
User Flow :
API: POST /subscriptions/{id}/rotate → Generates new secret, stores both (old valid 7 days).
Sender uses latest secret; falls back to old if endpoint returns 401/403 (configurable).
UI shows active/pending secrets, rotation history.
DB Schema (simplified):
sql Copy code
CREATE TABLE signing_keys (
id UUID PRIMARY KEY,
subscription_id UUID REFERENCES subscriptions,
secret_hash TEXT, -- Argon2/phc for storage
version INT,
active_until TIMESTAMP, -- Grace period
created_at TIMESTAMP
);
Automation : Cron job rotates every 90 days; notify users via email/API.
3. Retries
Strategy : Exponential backoff (1s, 5s, 30s, 5m, 1h; max 10 attempts).
Triggers : 4xx/5xx, timeouts (>30s), no response.
Success : 2xx status.
Queue : Redis w/ TTL. Dead Letter Queue (DLQ) after max retries → UI/email alert.
Implementation :
Sender: Use httpx (Py)/axios-retry (JS) or custom.
Track in DB: deliveries table (status: pending/success/failed, retry_count, last_attempt).
Configurable : Per-subscription (max_retries, backoff_factor).
4. Replay UI
UI Dashboard (/dashboard/subscriptions/{id}/deliveries):
Delivery ID Event Status Attempts Timestamp Payload Actions evt_123 user.created Failed 5 2023-10-01 [View] [Replay] [Raw]
Filters: Status, date range, event type. Pagination (100/page).
Replay : Button → API POST /deliveries/{id}/replay queues immediate resend (bypasses quota if admin).
Search/export CSV.
API : GET /subscriptions/{id}/deliveries?status=failed&limit=50.
Security : RBAC (owner-only replays). Audit log all replays.
5. Quotas
Types :
Scope Limit Example Enforcement Account 10k deliveries/month DB check on event enqueue Endpoint 100/hour Redis token bucket (e.g., 100 tokens refill 100/hour) Retries 5/endpoint/day Per-delivery counter
Enforcement :
On event publish: Check account quota → Reject if exceeded (429).
Before send: Endpoint quota → Queue delay/reject.
API: GET /quotas shows usage.
DB/Redis :
sql Copy code
CREATE TABLE quotas (
account_id UUID,
type VARCHAR, -- 'deliveries', 'retries'
limit INT,
usage INT DEFAULT 0,
reset_at TIMESTAMP
);
Redis: quota:{account}:{type} incr/decr.
Security & Best Practices
Endpoint Validation : On subscription create, send challenge payload (user must return X-Challenge: <echo>).
HTTPS Only : Enforce TLS; validate certs.
Rate Limiting : Global (Cloudflare) + per-IP.
Replay Protection : Sig timestamp + unique id.
Compliance : GDPR (data retention 90 days), SOC2 (audit logs).
Edge Cases : Batched payloads (array of events), payload compression (gzip), proxy support (X-Forwarded-*).
Scalability : Horizontal scale sender (sharded by subscription_id), async queues.
Testing : Contract tests for sigs, chaos engineering for retries.
Implementation Roadmap
MVP : DB + API + Sender (1 week).
Security : Signatures + Rotation (1 week).
Retries + Quota (1 week).
UI + Replay (2 weeks).
Prod : Monitoring, load tests (1k EPS).
This design is production-ready, inspired by Stripe/Twilio webhooks. Open-source analogs: Svix, Hookdeck. Let me know if you need code snippets, ERDs, or expansions!