Design a Scalable Real-Time Event Notification Engine
System DesignModel answerLast updated
Design a robust event delivery platform supporting independent fan-out isolation, classified retry delays, rate limiting, and historical replays.
Problem Statement
Design a robust, multi-tenant event delivery engine capable of handling high-volume real-time event streams (e.g., shipment status changes, driver location updates, order state transitions) and dispatching them to hundreds of downstream internal services and external partner webhooks.
Downstream subscribers exhibit diverse operational characteristics: varying throughput capabilities, different SLA profiles, distinct payload schema requirements, and fluctuating availability. A key architectural goal is ensuring complete consumer isolation so that an outage or performance degradation in one consumer system never disrupts event processing for others.
Requirements
Functional Requirements
- Ingestion & Routing: Ingest events via an HTTP API and route them to matching subscribers according to filter expressions and versioning rules.
- Consumer Isolation: Guarantee that slow, unresponsive, or failing consumer destinations cannot introduce head-of-line (HoL) blocking or delay delivery for healthy consumers.
- Idempotency & At-Least-Once Delivery: Provide at-least-once delivery guarantees. Automatically detect and ignore duplicate incoming events from upstream producers via deduplication keys.
- Error Classification & Retry Strategy: Classify downstream delivery failures into transient (e.g., HTTP 503, network timeouts) versus permanent (e.g., HTTP 400, 404, authorization errors). Implement exponential backoff for transient issues and forward non-retryable failures to a Dead Letter Queue (DLQ).
- Historical Replays & Auditability: Support administrative replay of historical events for a specific subscriber across a chosen time range. Maintain a complete audit log of every delivery execution attempt and response status.
Non-Functional Requirements
- High Throughput & Low Latency: Handle peak ingestion traffic of 50,000 events/second. Deliver events to responsive destinations within 1 second at $p_{99}$.
- Backpressure & Flow Control: Rate-limit dispatches on a per-subscriber basis to prevent overwhelming downstream destination endpoints.
- Data Retention: Retain raw ingested events for a minimum of 7 days to facilitate system recovery, debugging, and historical replays.
Scale & Capacity Assumptions
- Ingestion Peak: 50,000 incoming events/sec.
- Active Subscriptions: ~500 configured downstream consumers.
- Average Fan-Out: 5 destinations per ingested event (yielding ~250,000 delivery dispatches/sec at peak).
- Average Event Payload: ~2 KB.
- Audit Logging: Up to 300 million daily log entries under normal operations (with capacity for burst peaks matching max dispatch rates).
Key Areas to Address
- API Interfaces: Ingestion, subscription management, and replay execution APIs.
- Data Model & Storage: Schemas and storage engine choices for deduplication state, subscription rules, raw event streams, and audit histories.
- System Architecture: Complete system topology covering ingestion endpoints, fan-out compute layers, isolated worker dispatchers, retry backoff mechanisms, and DLQ handling.
- Failure Modes & Trade-offs: Mitigating head-of-line blocking, managing deduplication storage windows, implementing circuit breakers, and enforcing replay controls.
Hints
Hint 1
Decouple the primary ingestion event log from per-consumer delivery state so write path performance is unaffected by slow consumers.
Hint 2
Store full event payloads in a centralized blob log or main topic, passing reference IDs through fan-out queues to prevent memory and bandwidth amplification.
Hint 3
Use classified retry delay queues combined with circuit breakers to prevent failing endpoints from overwhelming dispatchers or triggering cascading outages.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. High-Level Requirements & Capacity Sizing
Capacity Sizing & Calculations
- Ingest Data Volume:
- $50,000 \text{ events/sec} \times 2 \text{ KB/event} = 100 \text{ MB/sec}$ ingress.
- Daily raw ingest: $100 \text{ MB/s} \times 86,400 \text{ s} \approx 8.64 \text{ TB/day}$.
- 7-day retention requirement: $8.64 \text{ TB} \times 7 \approx 60.5 \text{ TB}$ raw storage. Accounting for $3\times$ replication in a streaming log like Kafka, raw retention demands $\sim 180 \text{ TB}$ of storage (or tiered storage writing older segments to S3/GCS).
- Fan-Out Dispatch Volume:
- Peak delivery throughput: $50,000 \text{ events/sec} \times 5 \text{ fan-out} = 250,000 \text{ dispatches/sec}$.
- Copying 2 KB payloads for every dispatch directly into 5 separate queues would require $500 \text{ MB/sec}$ of write IOPS. To optimize throughput, delivery messages carry lightweight pointers (
event_id) or payloads are cached at the edge worker.
- Audit Logs:
- $250,000 \text{ dispatches/sec}$ peak generates up to $21.6 \text{ billion}$ records per day during prolonged peak usage. The system must use a high-throughput, append-only columnar database (e.g., ClickHouse) for audit storage.
2. API Design
Event Ingestion API
POST /v1/events
Headers:
X-Idempotency-Key: <string>
Content-Type: application/json
{
"event_type": "order.status_changed",
"schema_version": "1.2.0",
"entity_key": "order_849204",
"timestamp": 1718000000,
"payload": {
"order_id": "order_849204",
"status": "DISPATCHED",
"driver_id": "drv_9921"
}
}
Response: 202 Accepted
{
"event_id": "evt_01HZX890ABCDEF1234567890",
"status": "ACCEPTED"
}
Subscription Management API
POST /v1/subscriptions
Content-Type: application/json
{
"name": "Partner Webhook Service",
"event_types": ["order.status_changed"],
"filter_expression": "$.payload.status == 'DISPATCHED'",
"delivery_target": {
"type": "HTTP",
"endpoint_url": "https://api.partner.com/webhooks/orders",
"timeout_ms": 3000
},
"rate_limit_rps": 500,
"max_concurrency": 50,
"ordering_guarantee": "NONE"
}
Event Replay API
POST /v1/replays
Content-Type: application/json
{
"subscription_id": "sub_99210",
"start_time": 1717900000,
"end_time": 1717936000,
"target_rps": 200
}
3. Data Architecture & Storage Schema
| Storage Component | Technology | Data Stored |
|---|---|---|
| Idempotency Cache | Redis Cluster (Distributed) | Producer Deduplication State |
| Ingestion Log | Apache Kafka / Redpanda (Tiered Storage) | Immutable Raw Event Stream |
| Configurations | PostgreSQL (In-Memory Worker Caching) | Subscriptions & Routing Rules |
| Audit Storage | ClickHouse / Apache Cassandra | Execution Logs & Status Codes |
Idempotency Schema (Redis Key-Value)
- Key:
dedup:{producer_id}:{idempotency_key} - Value:
{"event_id": "evt_...", "state": "COMMITTED"} - TTL: 86,400 seconds (24 Hours).
Raw Event Store Schema (Kafka Topic / Parquet S3 Archive)
{
"event_id": "STRING (UUIDv7)",
"producer_id": "STRING",
"event_type": "STRING",
"schema_version": "STRING",
"entity_key": "STRING",
"ingested_at": "TIMESTAMP",
"payload": "JSON"
}
Audit Log Schema (ClickHouse Columnar Table)
CREATE TABLE delivery_audit_logs (
subscription_id UUID,
event_id UUID,
attempt_number UInt8,
attempt_timestamp DateTime64(3),
http_status UInt16,
latency_ms UInt32,
outcome Enum8('SUCCESS' = 1, 'TRANSIENT_FAILURE' = 2, 'PERMANENT_FAILURE' = 3),
error_message String
)
ENGINE = MergeTree()
PARTITION BY toYYYYMMDD(attempt_timestamp)
ORDER BY (subscription_id, attempt_timestamp, event_id);
4. End-to-End System Architecture
+-------------------------------------------------+
| INGESTION |
+-------------------------------------------------+
|
Producers -----> Ingestion API Gateways (Stateless Go/Java Nodes)
| |
Redis Deduplication Kafka Raw Event Topic
(24-hr TTL) (Partitioned by entity_key)
|
v
+-------------------------------------------------+
| FAN-OUT ENGINE |
+-------------------------------------------------+
|
Fan-Out Router Workers
(Matches against cached PostgreSQL rules)
|
+-----------------------------+-----------------------------+
| | |
v v v
Per-Consumer Queue A Per-Consumer Queue B Per-Consumer Queue C
(Sub 1 Partition Group) (Sub 2 Partition Group) (Sub 3 Partition Group)
| | |
v v v
Dispatcher Workers Dispatcher Workers Dispatcher Workers
(Rate Limiter / Breaker) (Rate Limiter / Breaker) (Rate Limiter / Breaker)
| | |
+-----------------------------+-----------------------------+
|
v
+-------------------------------------------------+
| DISPATCH & RETRIES |
+-------------------------------------------------+
|
Downstream HTTP / Webhooks
|
+-----------------------------+-----------------------------+
| (2xx Success) | (Transient Error) | (Permanent / Exhausted)
v v v
Audit Stream Retry Topics Dead Letter Queue (DLQ)
(ClickHouse Sink) (1m -> 5m -> 15m -> 1h) (S3 / Admin Replay UI)
Detailed Component Workflow
1. Ingestion Layer
- Upstream callers emit HTTP POST requests containing an
X-Idempotency-Key. - Ingestion nodes issue an atomic Redis command:
SET key event_id NX EX 86400.- If the key exists, return the existing
event_idwith202 Acceptedimmediately. - If the key is new, write the incoming message payload to the
raw-eventsKafka topic partitioned byentity_key.
- If the key exists, return the existing
2. Fan-Out & Routing Engine
- Stateless router nodes consume messages from
raw-events. - Rules loaded in-memory from PostgreSQL are matched against event types and jsonpath filter conditions.
- For every matched rule, a lightweight delivery message containing
(event_id, subscription_id, target_schema_version)is written to the consumer's dedicated Kafka topic/partition group.
3. Dispatch & Multi-Tenant Isolation
- Queue Level Isolation: Every consumer subscription owns a separate Kafka topic (or dedicated set of partitions). A degraded subscriber accumulates lag inside its own topic without affecting others.
- Worker Level Isolation: Async dispatch pools execute requests to endpoints. Token bucket algorithms enforce target
rate_limit_rps. - Circuit Breaking: If consecutive HTTP failures exceed 50% over a 30-second window, the circuit trips to
OPEN. The dispatcher stops polling Kafka for that consumer, allowing lag to build safely in Kafka rather than continuously slamming an unready target system.
4. Error Handling & Delay Queues
- Transient Failures (HTTP 500, 502, 503, 504, 429, Socket Timeout): Forwarded to tiered retry delay queues (
retry-1m,retry-5m,retry-15m,retry-1h). - Permanent Failures (HTTP 400, 401, 403, 404, 422): Bypasses retries and publishes straight to the consumer's Dead Letter Queue (DLQ).
- Retry Exhaustion: Events failing after maximum attempts (e.g., 5 total retries over 24 hours) are routed to the DLQ.
5. Key Trade-offs & Failure Recovery
Trade-offs
-
Payload References vs. Deep Copying:
- Choice: Pass
event_idreferences through fan-out queues and fetch payloads from an in-memory cache/Kafka when dispatching. - Trade-off: Slightly increased dispatch latency (network fetch for cold cache) in exchange for massive storage and bandwidth savings on high fan-out events.
- Choice: Pass
-
Strict Ordering vs. Parallel Throughput:
- Choice: Deliver out-of-order by default (
ordering_guarantee: NONE). Allow opt-in strict ordering perentity_key. - Trade-off: Strict ordering routes all events for an entity key to a single partition worker, sacrificing concurrent throughput for guaranteed sequencing.
- Choice: Deliver out-of-order by default (
Common Pitfalls & Edge Cases
- Cascading Retry Storms: Exponential backoff alone can cause synchronized request spikes. Add $20%$ randomized jitter to backoff intervals to distribute worker load smoothly.
- Large Replay Operations: Triggering a 7-day replay for a subscriber could starve real-time event processing. Enforce a
target_rpsparameter on replay requests and route replay traffic through dedicated low-priority dispatcher threads.