Build a Rule-Based Event Fan-Out Service with Webhook Delivery
System DesignModel answerLast updated
Design a platform that takes up to a million fire-and-forget events per second and pushes each one to the webhooks of tenants whose filter rules match, with retries, isolation and security.
You are asked to design a multi-tenant platform that moves events from producers to interested consumers.
Producers push events and do not wait for any matching or delivery to happen. Aggregate ingest can reach 1,000,000 events per second at peak.
Consumers register a rule (a filter over event contents) together with a webhook URL. Each event that satisfies a rule must be sent to that rule's webhook over HTTP.
Your design should cover:
- Requirements and capacity estimates. State your assumptions (event size, number of tenants and rules, matches per event, retention) and derive bandwidth, storage and the number of concurrent outbound requests.
- APIs. Event ingestion, and subscription create/update/pause/resume/delete, plus anything needed for observability or replay.
- Rule language. What can a rule express, what limits do you impose, and how do you make matching fast with a large number of rules?
- Architecture and data model. Major components, what is stored where, and how rule changes reach the matching layer.
- Webhook delivery. Success criteria, retry and backoff policy, handling of permanently failing endpoints, and request authenticity.
- Guarantees. Delivery semantics, ordering, and exactly when a new or changed rule starts to apply.
- Backpressure and scaling. How each layer protects itself and how you shard.
- Multi-tenancy, rate limiting and security. Prevent a slow or malicious tenant from degrading others.
- Operations. Metrics, alerts and failure modes you would plan for.
Be explicit about trade-offs and about where your design would break first.
Hints
Hint 1
Do the arithmetic early: if each event matches about two rules, outbound webhook calls outnumber inbound events, and with a few hundred milliseconds of latency each, hundreds of thousands of requests are in flight at once. Which side is harder to build, ingest or delivery?
Hint 2
Put a durable partitioned log between ingest and everything else. It defines your durability point (the 202 response), lets the matchers lag safely, and makes replay cheap. Then ask how to avoid evaluating every rule for every event, for example by requiring an indexable equality on event type.
Hint 3
Separate delivery from matching and isolate it per tenant and per subscription. Think about per-subscription queues, concurrency caps, circuit breakers for dead endpoints, jittered exponential backoff, a dead-letter queue, and what ordering you can promise without head-of-line blocking everyone.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Requirements and scale
Functional
- Producers send events and get an acknowledgement as soon as the event is durably accepted, not when it is delivered.
- Subscribers register a filter and a webhook. Every matching event is POSTed to the webhook.
- Subscribers can pause, resume, inspect failed deliveries, look at dead letters and replay history.
Non-functional
- 1M events/s peak ingest, p99 ingest latency under about 50 ms.
- Event-to-first-delivery-attempt p99 of a second or two.
- At-least-once delivery; no acknowledged event is lost.
- One tenant's slow or broken endpoint must never delay another tenant.
Estimates (assumptions stated)
| Quantity | Estimate |
|---|---|
| Event size | ~1 KB, so ~1 GB/s ingress, ~86 TB/day |
| Log retention | 7 days, 3x replication, roughly 1.8 PB raw (less after compression) |
| Tenants / rules | ~10K tenants, ~1M rules, ~1 KB compiled each, so ~1 GB, which fits in memory on every matcher |
| Matches per event | ~2, so ~2M deliveries/s |
| Concurrent outbound calls | 2M/s x 0.2 s, about 400K in flight |
The last row is the main insight: delivery, not ingestion, is the hard part. It needs async I/O, tens of thousands of connections per host and a few hundred delivery workers.
2. APIs
POST /v1/events: batch of up to ~500 events (about 1 MB). Optional idempotency key. Returns202after the durable append,429withRetry-Afterwhen throttled,413when too large.POST /v1/subscriptions: name, filter expression, webhook URL and secret reference, ordering mode (noneorper_key), optional rate cap and retry policy. Starts inpending_verificationuntil the endpoint proves ownership (challenge handshake).GET/PATCH/DELETE /v1/subscriptions/{id}, plus pause, resume andreplay {from_time}.GET .../deliveries?status=failedandGET .../dead-lettersfor observability.
Events use a CloudEvents-style envelope. If the producer omits an ID, the server assigns one; it becomes the dedup key for receivers.
3. Rule language
Use a small, non-Turing-complete expression language in the spirit of CEL:
type == "order.created" && data.amount > 100 && data.region in ["EU","UK"] && !has(data.test)
- Supported: field paths, comparisons,
in,startsWith,has,&&,||,!, parentheses, literals only. - No loops, user functions or backtracking regex (RE2-style only, if at all).
- Caps at registration: size (say 4 KB) and predicate count (say 50). Compile once to an AST; matching never parses.
- Indexability rule: each rule must contain a top-level equality on
type(or a type prefix). Matchers build an inverted index(tenant, type) -> candidate rules, further indexed on equality andinpredicates with a counting algorithm. Only surviving candidates get a full AST evaluation. Cost is proportional to candidates, not total rules.
4. Architecture
Producers -> LB -> Ingest gateway (auth, quota, validate, batch)
-> Partitioned replicated log
-> Matcher fleet (in-memory rule index)
-> Per-subscription delivery queues
-> Delivery workers (async HTTP, sign, retry) -> Webhooks
\-> DLQ + delivery log -> status APIs
Control plane: Subscription API -> strongly consistent DB -> change feed -> matchers
- Durability point: the gateway returns 202 only after a quorum append to the log. The producer SDK batches, compresses and retries with jitter, buffering locally on 429.
- Log: partitioned by hash of (tenant, partition key), about 2,000 partitions at ~500 events/s each for headroom, 7-day retention for replay.
- Subscriptions: stored in a strongly consistent database; changes stream to matchers, which hold all rules in memory and converge within seconds.
- Matchers: stateless consumers scaled by partition count. At roughly 50K events/s per core, 1M/s needs about 20 cores of matching; provision several times that.
- Delivery state: per-subscription queues sharded by subscription ID; records of (sub, event, attempt, next_attempt_at, last_status); retries kept in a time-bucketed timer store or delay queue.
5. Webhook delivery
- Authenticity: HMAC-SHA256 over timestamp plus body with a per-subscription secret (rotatable, two active versions), timestamp header, and event ID. Receivers dedupe on event ID and reject stale timestamps.
- Success: any 2xx within about 10 s.
- Retry: 5xx, 408, 429, timeouts and connection errors. Other 4xx go straight to the DLQ.
- Backoff:
min(cap, base * 2^attempt) * random(0.5, 1.5), base 1 s, cap 1 h, for up to 24 h, honoringRetry-After; then DLQ. - Dead endpoints: a circuit breaker per endpoint stops hammering; after days of failure, auto-disable and notify the tenant.
- Optional batching: up to ~100 events per POST cuts in-flight requests by an order of magnitude for busy subscribers.
- SSRF defense: resolve and block private/link-local addresses, pin DNS results, restrict ports, and run delivery from an egress-restricted network.
6. Guarantees
- At-least-once, no global order. Duplicates are possible, hence the event ID.
- Per-key ordering (opt-in): same partition key is delivered in log order, with one in-flight request per (subscription, key). Cost is head-of-line blocking: a failing event stalls later events for that key until success or DLQ. Default is
nonefor maximum parallelism. - Rule versioning: an event is matched against the rule version active when it is processed. A new rule affects only later events unless the tenant calls replay.
7. Backpressure and isolation
- Ingest: per-tenant token buckets return 429 with
Retry-After; global load shedding protects the log if broker lag or disk crosses thresholds. - Log as shock absorber: matchers can fall behind safely; autoscale on consumer lag.
- Delivery: per-subscription and per-tenant concurrency and rate caps, bounded queues, and fair scheduling (for example weighted round robin across tenants) so a slow endpoint consumes only its own budget. Overflowing queues spill to storage rather than blocking matchers.
- Noisy tenants: large tenants can get dedicated partitions or worker pools; hot partition keys are salted where ordering is not required.
8. Security
Authenticate producers with API keys or OAuth scoped to a tenant; enforce tenant ID from the credential, never from the payload. Encrypt in transit and at rest, keep secrets in a secrets manager, validate payload size and schema, and audit subscription changes.
9. Observability and failure modes
- Metrics: ingest latency and 429 rate, consumer lag per partition, match latency, delivery success rate, attempt-age and queue depth per tenant, DLQ size.
- Alerts on lag growth, end-to-end latency SLO burn, and per-endpoint error spikes.
- Failure modes: matcher crash (another consumer resumes from offsets, duplicates possible), broker loss (quorum replication), stale rule cache (bounded by change-feed lag), retry storms after a mass endpoint outage (jitter plus circuit breakers).
Common mistakes
- Sizing only for ingest and ignoring the 400K concurrent outbound calls.
- Evaluating every rule for every event.
- A single shared delivery queue, which lets one slow tenant cause head-of-line blocking for everyone.
- Promising exactly-once or global ordering without acknowledging the cost.
- Retrying without jitter or circuit breakers, and forgetting SSRF protection on user-supplied URLs.