Dynamic Weighted Log Routing Pipeline
Medium · System Design · Software Engineer · Online Assessment
Prompt
Architect a high-throughput distributed log routing pipeline that collects log streams from hundreds of microservices and forwards events across heterogeneous storage targets—including Elasticsearch clusters, S3 object-storage buckets, and local-disk log hosts—according to operator-defined percentage splits. For instance, an operator might configure billing-svc so 80% of its events land in es-alpha while 20% land in es-beta.
Your design must satisfy the following operational and performance targets:
- Live weight updates: Operators must be able to adjust traffic-split weights on the fly with zero restarts, dropped batches, or service interruption.
- Even load distribution: Spread incoming batches and routed streams evenly across ingestion instances, buffers, and storage nodes so single-partition or single-host hotspots do not form.
- Zero-loss fault handling: Whenever a downstream storage target becomes degraded or unreachable, the pipeline must absorb the backlog safely or redirect traffic to healthy capacity without losing accepted logs.
- Per-node throughput & tail latency: Sustain 100,000 events per second per ingestion node while keeping end-to-end ingestion acknowledgment latency under 50 ms.
- Horizontal scale-out: Scale capacity linearly by adding stateless nodes and workers as fleet-wide log volume grows.
Scope & Expectations
- End-to-end topology & data path: Sketch and trace how log batches move from service hosts through ingestion, weighted routing, durable buffering, and backend-specific writers.
- Configuration store & propagation: Justify where dynamic routing rules and weights are stored and how updates reach every routing instance consistently in real time.
- Backpressure & outage resilience: Detail how retries, circuit breaking, buffering, and capacity-aware failover protect healthy backends when a destination cluster stalls or goes offline.
- Control & ingestion APIs: Define clean request/response schemas for reading, validating, updating, and rolling back weighted routing rules alongside batch ingestion.
Step-by-step walkthrough
Clarify requirements and latency semantics
Writing a function that picks
es-alpha80% of the time andes-beta20% of the time takes ten lines of code. What makes this a real distributed-systems problem is doing that 100,000 times per second on every node, acknowledging batches in under 50 ms, changing weights live without dropping a single log, and surviving a dead Elasticsearch cluster without toppling the healthy ones next to it.Functional requirements
- High-volume log ingestion: Microservices run a lightweight host agent that batches log lines and sends them to our routing fleet.
- Dynamic weighted routing: Rules match log streams (by
service, and optionallyenvorlevel) and split traffic across destinations by weight—for example,billing-svcroutes 80% to Elasticsearch clusteres-alphaand 20% to Elasticsearch clusteres-beta. Weight updates apply within seconds with zero restarts or downtime. - Multiple storage backends: Support Elasticsearch clusters, S3 object-storage buckets, and fleets of local-disk log hosts.
- Hotspot-free load balancing: Spread traffic evenly across gateway nodes, message-queue partitions, and destination nodes.
- Fault tolerance: When a destination slows down or goes offline, either buffer its logs durably or reroute them to healthy capacity—never lose acknowledged logs.
Non-functional requirements and key assumptions
- Throughput & horizontal scale: 100,000 events/s per routing gateway node (~1 KB per event). Assume total cluster load is 500,000 events/s average and 1,000,000 events/s peak, scaling linearly by adding gateway nodes.
- What
< 50 mslatency measures: It measures ingestion acknowledgment—from the host agent sending a batch until our service confirms those logs are durably replicated across availability zones (AZs). It cannot mean "searchable in Elasticsearch," because Elasticsearch only refreshes its search index every 1 second by default. Downstream delivery has separate freshness targets (< 10 ssearchable in Elasticsearch at p99;< 2 minwritten as objects in S3). - Split vs. mirror: Weighted rules split events (each event lands in one chosen target of the rule). Full archival copies can use a separate mirror rule if needed.
- Delivery guarantee & ordering: At-least-once delivery with deduplication via a client-generated
event_id. Random weighted splits have no cross-cluster ordering by definition; per-user ordered routing is supported via ahashrule mode.
Back-of-the-envelope capacity estimates
Sizing the network, compute, and disk buffers up front tells us where capacity is cheap and where it is scarce.
1. Raw log volume (assuming ~1 KB uncompressed JSON per event) Average: 500,000 events/s x 1 KB = 500 MB/s (43.2B events/day, ~43.2 TB/day raw) Peak: 1,000,000 events/s x 1 KB = 1.0 GB/s (~8 Gbit/s network ingress) 2. Stateless Routing Gateway fleet (target: 100k events/s = ~100 MB/s per node) Minimum at 100% peak utilization : 1,000k / 100k = 10 nodes Target ~55-60% peak utilization : 18 nodes (6 nodes in each of 3 AZs) If an entire AZ goes offline : 12 surviving nodes handle ~83.3k events/s each (safe!) 3. Kafka buffer cluster (assuming ~4x zstd batch compression on repetitive JSON logs) Compressed ingress at peak : 1,000 MB/s / 4 = 250 MB/s (125 MB/s average) Broker disk writes (3x replicas) : 250 MB/s x 3 = 750 MB/s at peak 24-hour outage buffer (at avg) : 125 MB/s x 86,400 s = 10.8 TB unique (32.4 TB replicated) Cluster size: 9 brokers (3/AZ) : ~83 MB/s peak disk writes and ~3.6 TB storage per broker (~1/3 of a modern NVMe broker's ~250 MB/s write ceiling) 4. Example peak destination shares (1M events/s total) es-alpha (Elasticsearch A) : 40% -> 400k events/s (~100.0 MB/s compressed) s3-archive (S3 bucket) : 30% -> 300k events/s (~75.0 MB/s compressed) es-beta (Elasticsearch B) : 20% -> 200k events/s (~50.0 MB/s compressed) disk-cold (local disks) : 10% -> 100k events/s (~25.0 MB/s compressed)Key takeaway from the numbers: Stateless gateway CPU and network (~0.8 Gbit/s per node on a 10 Gbit/s NIC) are easy to scale in minutes. Destination write capacity—especially Elasticsearch indexing—cannot scale instantly, so any failover strategy must check how much spare headroom healthy clusters actually have before dumping extra traffic onto them.
API design for log ingestion and routing rules
1. Data-plane Ingestion API (gRPC / HTTP/2, called by host log agents)
POST /v1/ingest Headers: Authorization: mTLS service identity Content-Encoding: zstd Body: { "service": "billing-svc", "env": "prod", "events": [ // max 1,000 events or 1 MB per batch { "event_id": "01K4M...", // agent-generated UUID/ULID for dedup "ts": 1796198400123, "level": "INFO", "routing_key": "usr-409", // optional; used by hash-ordered rules "body": "<raw opaque UTF-8 bytes>" } ] } Responses: 200 OK {"accepted": 1000} (replicated across Kafka AZs) 429 Too Many Requests Retry-After: 1 (buffer full; agent keeps batch on local disk & retries) 503 Service Unavailable Produce timed out; agent retries same batch (event_id deduplicates)Why put
service,level, androuting_keyin an outer envelope? Parsing 100,000 arbitrary JSON log bodies per second burns huge amounts of CPU. Reading three tiny envelope fields while treatingbodyas opaque bytes lets a single gateway hit 100k events/s effortlessly.2. Control-plane Routing Admin API
GET /v1/routes List all active routing rules GET /v1/routes/{rule_id} Fetch rule + ETag (backed by etcd's revision number) PUT /v1/routes/{rule_id} Create/replace rule; requires If-Match: <ETag> -> 200 OK (new ETag) | 409 Conflict (concurrent edit) | 422 Over destination capacity PATCH /v1/routes/{rule_id}/weights Update weights, e.g. {"targets": [...], "ramp_seconds": 300} POST /v1/routes:validate Dry-run: projects events/s per destination against limits GET /v1/routes/{rule_id}/status Shows applied revision across all 18 gateways + actual % split POST /v1/routes/{rule_id}/rollback?to=<revision> Instant revert to a known-good historical version PUT /v1/destinations/{dest_id} Register destination endpoints, max capacity, or drain stateRequiring
If-Matchwith anETag(optimistic concurrency control) prevents two engineers from accidentally overwriting each other's edits, and capacity validation blocks a typo from routing 300k events/s into a cluster rated for 100k events/s.Configuration storage and Kafka topic model
Where dynamic routing weights live Our routing table is tiny (a few thousand rules × 1 KB = a few megabytes), updated occasionally by operators or health automation, and read in memory 100,000 times per second on every gateway. We need strong consistency and sub-second push notifications to all 18 gateways.
Storage option How updates propagate Trade-off & verdict etcd (or ZooKeeper) Long-lived streaming Watch API ordered by a global monotonic revisioncounterChosen. Consensus via Raft (majority-quorum replication), atomic compare-and-swap writes, expiring leases (TTL keys), and gap-free watch resume after brief network drops. Relational DB + polling Gateways run SELECTevery 5–10 sSimple, but adds polling lag and fails to push urgent outage overrides quickly. Kafka compacted topic Gateways consume config log Reuses Kafka, but lacks atomic compare-and-swap ( If-Match) and expiring leases on write.etcd key layout and rule schema:
/logroute/rules/{rule_id} -> authored routing rule (JSON below) /logroute/destinations/{dest_id} -> {"type": "elasticsearch" | "s3" | "disk", "topic": "dest.es-alpha", "capacity_eps": 500000, "state": "active" | "draining" | "disabled"} /logroute/overrides/{rule_id} -> temporary emergency weights written by Health Controller with a 60-second etcd lease (auto-expires if controller dies) Example /logroute/rules/billing-svc-prod: { "rule_id": "billing-svc-prod", "match": {"service": "billing-svc", "env": "prod"}, // most-specific match wins, then priority "priority": 100, "mode": "weighted", // or "hash" (with "hash_key": "routing_key") "unit": "events", // or "bytes" "targets": [ {"dest": "es-alpha", "weight": 80}, {"dest": "es-beta", "weight": 20} ], "on_failure": "reroute", // or "buffer" when cluster affinity is strict "fallback": "s3-overflow" }A catch-all rule (
"match": {}) routes unknown services tos3-archiveso unconfigured logs are never dropped, and a tiny auditor service watches/logroute/and appends every revision to Postgres for history and 1-click rollbacks.Per-destination Kafka topics: We create one Kafka topic per destination (
dest.es-alpha,dest.es-beta,dest.s3-archive,dest.disk-cold,dest.s3-overflow) plus dead-letter topics (dlq.<dest>) for malformed events. Pre-provisioning generous partition counts (32fordest.es-alpha,24fordest.es-betaanddest.s3-overflow,16fordest.s3-archive,12fordest.disk-cold) lets sink worker pools scale horizontally and avoids changing partition counts later (which would reshuffle hash keys).High-level architecture
We place Kafka as a durable, isolated buffer layer between the stateless routing gateways and the destination-specific sink workers:
Microservices + Host Log Agents (local disk ring buffer, zstd batching, retry) | gRPC / HTTP/2 (batches <= 1,000 events) v [ L4 Network Load Balancer ] | v [ Routing Gateways (18 stateless nodes across 3 AZs) ] <=== Watch === [ etcd (3-5 nodes) ] 1. match rule in local immutable snapshot ^ ^ 2. pick destination by weight (or hash) | | 3. batch-produce to dest.<id> (acks=all) -> return 200 OK [ Admin API ] [ Health Controller ] | (CAS + ramp) (leased overrides) v ^ [ Kafka Cluster (9 brokers across 3 AZs, 24h retention) ] | Topics: dest.es-alpha | dest.es-beta | dest.s3-archive | dest.disk-cold | dest.s3-overflow | | | | | v v v v v [ ES Sink ] [ ES Sink ] [ S3 Writer ] [ Disk Pull ] [ Overflow Writer ] (bulk API + (bulk API + (64-128 MB zst (agents on (writes S3 + later breaker) breaker) chunk files) disk hosts) Replay Worker) | | | | | v v v v | [ es-alpha ] [ es-beta ] [ S3 Bucket ] [ Local Disks ] <---------+Why decide the destination at ingestion instead of after a single giant
raw-logstopic? 1. Half the Kafka cost: Every event is written to Kafka once (250 MB/s compressed at peak) instead of twice (ingest toraw-logs, consume, then re-produce todest.<id>). 2. Strict fault isolation: Each destination owns its own topic and consumer group. Ifes-alphastalls, onlydest.es-alphaaccumulates lag;es-beta, S3, and local disks continue at full speed with zero head-of-line blocking.Deep dive 1: hitting 100k events/s per node under 50 ms
How one node processes 100,000 events/s without breaking a sweat: Because agents send batches of up to 1,000 events, 100,000 events/s is only ~100 RPCs per second per gateway node. The gateway decompresses the batch, reads the tiny envelope headers without parsing the JSON log payload, assigns each event to a per-destination producer buffer, and lets the Kafka producer re-compress outgoing per-topic batches with
zstd.End-to-end
< 50 msingestion latency budget:Agent -> L4 LB -> Gateway over persistent HTTP/2 connection : ~2 ms Decompress batch + match rules + weighted destination selection : ~2 ms Kafka producer batching window (linger.ms = 5) : 5 ms Kafka replication across 3 AZs (acks=all, min.insync.replicas=2) : 5-15 ms Gateway HTTP 200 response back to agent : ~1 ms ---------------------------------------------------------------------------- Typical latency: 15-25 ms (leaves ~25 ms headroom for p99 < 50 ms)(Important Kafka tuning detail: we set
enable.idempotence=trueso broker retries never duplicate records, and lowerdelivery.timeout.msto ~1,000 ms withrequest.timeout.msat ~900 ms so a wedged broker fails fast with503instead of hanging caller threads for 30 seconds.)Fast, thread-safe weighted routing with zero lock contention: Whenever etcd updates, a gateway compiles each rule's integer weights into a read-only prefix-sum array (
cumulative). Selecting a destination per event takes one random integer and a binary search—zero shared mutable counters or locks across CPU cores:import bisect import random class WeightedTargets: """Immutable prefix-sum table for fast, lock-free weighted selection.""" def __init__(self, destinations: list[str], weights: list[int]) -> None: self.destinations = list(destinations) self.cumulative: list[int] = [] running_total = 0 for weight in weights: running_total += weight self.cumulative.append(running_total) if running_total <= 0: raise ValueError("Total routing weight must be positive") self.total = running_total def pick(self) -> str: # Draw an integer in [0, total - 1] and binary-search the prefix sums. roll = random.randrange(self.total) idx = bisect.bisect_right(self.cumulative, roll) return self.destinations[idx]Mini-trace with destinations = ["es-alpha", "es-maint", "es-beta"] and weights = [80, 0, 20]: cumulative = [80, 80, 100], total = 100 - roll in 0..79 -> bisect_right([80, 80, 100], roll) = 0 -> "es-alpha" (80% exact) - roll in 80..99 -> bisect_right([80, 80, 100], roll) = 2 -> "es-beta" (20% exact) - index 1 ("es-maint", weight 0) is cleanly skipped without special-case branches!Is random selection accurate enough? At
N = 100,000events/s withp = 0.80, the standard deviation of the observed fraction over a single second issqrt(0.80 * 0.20 / 100,000) = 0.00126—within 0.13 percentage points (80.0% +/- 0.13%), and even tighter over a minute! And because weighted rules publish to Kafka without a partition key, Kafka's sticky partitioner spreads batches evenly across all partitions ofdest.es-alpha, preventing partition hotspots.If a sudden spike fills >70% of a gateway's bounded producer memory, the gateway sheds
DEBUGbatches first with429 Retry-After: 1so agents hold them on local disk rather than crashing the gateway with out-of-memory errors.Deep dive 2: zero-downtime live weight updates
How do all 18 gateways switch from
80/20to50/50in real time without dropping requests or pausing traffic?- Streaming etcd Watch: Every gateway maintains an open watch on
/logroute/starting fromlast_applied_revision + 1. - Copy-on-write atomic pointer swap: When a change event arrives, a background thread builds a brand-new, immutable
RoutingSnapshotobject containing all compiledWeightedTargets(merging/rules/with any active/overrides/), saves a backup copy to local disk, and atomically swaps a single in-memory reference (current_snapshot = new_snapshot). Requests already mid-batch finish cleanly using the old snapshot; new batches immediately use the new one, with zero mutex locking on the hot path. - Resilience when etcd is down: If a gateway loses its watch stream, it reconnects from
last_applied_revision + 1(or performs a full snapshot read if etcd already compacted old revisions). If the entire etcd cluster goes down, gateways keep routing indefinitely using their in-memory (and disk-cached) snapshot—data-plane ingestion never depends on control-plane availability. - Gradual ramping for large weight shifts: Shifting
es-betafrom 20% to 85% in one millisecond can overwhelm cold JVM caches and shard queues ones-beta. When an operator specifiesramp_seconds: 300, the Admin API steps weights smoothly every 30 seconds (20% -> 27% -> 34% ... -> 85%) and automatically halts the ramp ifes-betareports rising error rates or consumer lag.
- Streaming etcd Watch: Every gateway maintains an open watch on
Deep dive 3: destination backpressure, circuit breakers, and capacity-aware rerouting
When
es-alphaslows down or goes dark, three coordinated layers prevent both data loss and cascading outages:Layer 1: Sink-level backpressure, retries, and circuit breakers - Bounded concurrency & commit-after-write: Each consumer in
es-alpha's sink pool keeps only a few bulk requests in flight and commits Kafka offsets only after Elasticsearch acknowledges the write. Whenes-alphaslows down, the sink naturally slows down its Kafka reads—pushing the backlog safely onto Kafka disks rather than exhausting worker RAM. - Selective backoff & dead-lettering: Elasticsearch's_bulkAPI returns per-document statuses. Documents rejected with transient429(write queue full) or5xxretry with exponential backoff and random jitter (100 ms, 200 ms, 400 ms ...up to30 s). Documents rejected with permanent400(such as a schema mapping conflict) go straight todlq.es-alphaso one malformed log never wedges an entire partition. - Idempotent sink writes: Crash replays never create duplicate searchable docs because Elasticsearch indexes each log usingevent_idas its document_idinside date-stamped indices (logs-billing-svc-2026.12.02), and the S3 writer names files deterministically ({dest}/{date_hour}/part-{partition}-{first_offset}.jsonl.zst) so a replayed flush simply overwrites the exact same S3 key. - Circuit breaker: A circuit breaker is an automatic safety switch per destination. If >50% of bulk writes fail over 30 seconds (or p99 write latency exceeds 5x baseline), the breaker trips Open, pausing writes so the struggling cluster can recover, and enters Half-Open every 30 seconds to send a single probe batch before closing again.Layer 2: Capacity-aware rerouting (stopping cascading failures!) When
es-alpha's breaker trips open, sinks report health to a single leader Health Controller (elected via an etcd lease). - Rules configured with"on_failure": "buffer"(such as strict compliance logs or hash-ordered streams) leave gateway weights untouched and buffer safely indest.es-alpha(up to 24 hours on Kafka disk; if an outage exceeds 6 hours, a background drain job streams the Kafka backlog intos3-overflowso disk space never runs out). - Rules configured with"on_failure": "reroute"receive a temporary/logroute/overrides/{rule_id}entry. Crucially, we never blindly dump 100% ofes-alpha's load ontoes-beta! Supposebilling-svcemits250,000events/s (80% = 200ktoes-alpha,20% = 50ktoes-beta), andes-betaonly has50kevents/s of spare capacity left before its own disks saturate. Sending all250ktoes-betawould crashes-betatoo! Instead, the controller fills healthy targets only up to their spare headroom and spills the excess to S3 (s3-overflow), which absorbs bulk object uploads effortlessly:def compute_reroute_rates( rule_eps: float, weights: dict[str, int], is_healthy: dict[str, bool], spare_eps: dict[str, float], fallback_dest: str, ) -> dict[str, float]: """Reallocate stranded events/s up to healthy targets' spare capacity, spilling rest to S3.""" total_weight = sum(weights.values()) new_rates: dict[str, float] = {} stranded_eps = 0.0 # Phase 1: Keep healthy targets' baseline share and total up stranded traffic from dead ones. for dest, weight in weights.items(): baseline = rule_eps * (weight / total_weight) if is_healthy.get(dest, False): new_rates[dest] = baseline else: new_rates[dest] = 0.0 stranded_eps += baseline # Phase 2: Absorb stranded traffic into healthy targets without exceeding spare_eps. for dest in weights: if is_healthy.get(dest, False) and stranded_eps > 0: absorbed = min(stranded_eps, spare_eps.get(dest, 0.0)) new_rates[dest] += absorbed spare_eps[dest] -= absorbed stranded_eps -= absorbed # Phase 3: Send any remaining unabsorbable traffic to the elastic S3 fallback bucket. if stranded_eps > 0: new_rates[fallback_dest] = new_rates.get(fallback_dest, 0.0) + stranded_eps return new_ratesConcrete trace for billing-svc (250k events/s, 80% es-alpha / 20% es-beta, es-alpha DOWN, es-beta spare = 50k/s): 1. Baseline: es-alpha = 0 (200k stranded), es-beta = 50k 2. Absorb: es-beta takes min(200k, 50k) = +50k -> es-beta = 100k/s (spare_eps["es-beta"] becomes 0) 3. Spill: remaining 150k/s routes to "s3-overflow" Published override weights (ratios): {"es-alpha": 0, "es-beta": 100, "s3-overflow": 150}Because each override is tied to a 60-second etcd lease, if the Health Controller itself crashes, overrides expire automatically and gateways revert safely to buffering in Kafka. Once
es-alpharecovers, the controller ramps live weights back in steps, drains the Kafka backlog at a capped1.5xcatch-up rate, and runs a background replay worker to backfill the S3 overflow files intoes-alpha(deduplicated byevent_id).Scaling, failure modes, and trade-off summary
- Horizontal gateway scaling: Gateways scale out on CPU and events/s per node. Because gRPC/HTTP/2 clients reuse persistent TCP connections (which would otherwise stay pinned to old nodes when new gateways boot), gateways configure
MAX_CONNECTION_AGE = 5 minutes(+/- jitter) so agents gracefully reconnect across newly added instances. - Kafka and sink scaling: Our 9 brokers run at ~33% write utilization, absorbing an unexpected 2x traffic spike without moving partitions (if disk fills during a spike + outage, tiered S3 storage or temporary retention trimming bridges the gap). Sink worker pools autoscale on consumer lag up to their topic's partition count.
Failure scenario Impact Recovery Gateway crashes mid-batch Agent sees connection reset or 503Agent retries batch against another gateway; event_iddeduplicates in ES / downstreamWhole AZ fails (6 gateways + 3 Kafka brokers) 1/3 capacity lost Surviving 12 gateways run at ~83% peak; acks=all(min.insync=2of 3) keeps accepting writes with zero data lossetcd cluster down Admin API cannot save edits Gateways continue routing from in-memory + local-disk snapshot Poison-pill malformed log Destination returns HTTP 400Routed to dlq.<dest>and archived to S3; partition never stallsKey metrics to monitor: - Gateway p99 ingestion latency (
< 50 msSLO) and429/503rates. - Per-destination time-to-retention-expiry (24h - oldest_unconsumed_message_age)—the ultimate countdown before data must drain to S3. - Observed split % vs. configured weight % per rule, plusapplied_revisionspread across gateways.Core trade-offs: - Route at ingest vs. post-Kafka routing: Halves Kafka write bandwidth and isolates destination backlogs, at the cost of needing a background drain job if an outage outlasts Kafka retention. - Acknowledge at Kafka vs. at storage: Achieves
< 50 msp99 reliably, trading synchronous search visibility for asynchronous sink freshness (< 10 s). - Stateless random split vs. stateful round-robin: Eliminates cross-thread lock contention at 100k events/s while staying within +/-0.13% accuracy per second.- Horizontal gateway scaling: Gateways scale out on CPU and events/s per node. Because gRPC/HTTP/2 clients reuse persistent TCP connections (which would otherwise stay pinned to old nodes when new gateways boot), gateways configure
Intuition & how it works
Imagine an airport baggage sorting hub handling thousands of suitcases a minute. At the check-in counter (our stateless routing gateways), clerks don't carry bags all the way out to each airplane—that would create an enormous line out the front door whenever one flight is delayed. Instead, clerks glance at the bag tag (a tiny metadata envelope), check an overhead digital board showing current gate splits (an in-memory routing snapshot pushed from etcd), and drop 80% of bags onto Conveyor Belt Alpha and 20% onto Conveyor Belt Beta (per-destination Kafka topics). As soon as the bag is safely on its belt, the passenger gets a receipt in milliseconds (< 50 ms). Separate ground crews (sink workers) load each plane at that plane's own speed, and if Flight Alpha has a mechanical issue, a central dispatcher updates the digital board so excess bags divert to Flight Beta's spare cargo space and an overflow warehouse (S3) instead of piling up on Flight Beta until it breaks too.
A naive design—having web servers parse every JSON log line, query a database for current weights, and write directly to Elasticsearch or S3 inside the request handler—fails every requirement at scale. First, Elasticsearch refreshes in ~1-second cycles and experiences garbage-collection pauses, making a < 50 ms p99 ingestion target impossible on direct writes. Second, parsing full JSON bodies and querying a config database at 100,000 events/s saturates both CPU and the database. Third, if es-alpha goes down and gateways naively reroute all 80% of its traffic onto es-beta (which was sized for 20%), es-beta immediately tips over in a cascading failure.
Walk through a concrete 4-step trace of a 1,000-event batch from billing-svc (80% es-alpha, 20% es-beta):
- Ingest (
t = 2 ms): The host log agent sends onezstd-compressed batch of 1,000 events—each carrying a small header (service="billing-svc",event_id) plus opaque raw payload bytes—to one of 18 stateless gateways. - Lock-free weighted split (
t = 4 ms): Using its local immutable routing table (cumulative = [80, 100]), the gateway draws a random integer0..99per event, placing ~800 events in itsdest.es-alphaproducer batch and ~200 indest.es-betawithout parsing the JSON bodies. - Durable acknowledge (
t = 18 ms): Kafka replicates both compressed batches across 3 availability zones (acks=all,min.insync.replicas=2), and the gateway returns200 OKwell inside the 50 ms budget. - Isolated consumption & outage handling: Independent sink pools bulk-index from
dest.es-alphaanddest.es-betausingevent_idfor deduplication. Ifes-alpha's circuit breaker (an automatic fault switch) opens, a central Health Controller publishes a temporary etcd override that fillses-betaonly up to its remaining spare capacity and routes the rest tos3-overflowfor later replay.
Key trade-offs
- Route at ingestion (one Kafka write) vs. route after a shared raw topic (two Kafka writes). Choosing the destination inside the gateway writes each log to Kafka once (250 MB/s compressed at peak instead of 500 MB/s) and isolates every destination's backlog in its own
dest.<id>topic. Putting a router after a singleraw-logstopic would make re-routing already-queued logs trivial, but doubles Kafka hardware cost and causes one stalled destination to hold back shared partition offsets unless you add separate spill topics anyway. - Acknowledge after Kafka replication vs. after destination indexing. Returning
200 OKonce Kafka replicates across availability zones guarantees< 50 msp99 latency and zero data loss on single-zone failures, at the trade-off that "ingested" and "searchable in Elasticsearch" are asynchronous milestones (< 50 msvs.< 10 s). - etcd streaming watches vs. database polling. etcd (a strongly consistent key-value store built on the Raft consensus protocol) pushes weight changes to all 18 gateways within ~1 second and lets disconnected gateways resume from their last seen
revisionnumber without missing updates. Polling a SQL database removes etcd as a dependency, but trades slower update propagation against constant read load; in both cases, gateways cache their last valid snapshot in memory and on local disk so ingestion survives a config-store outage. - Stateless random sampling vs. stateful weighted round-robin. Drawing a random number against prefix-sum weights requires zero shared mutable counters across threads and deviates by only
+/-0.13percentage points per second at 100,000 events/s (sqrt(0.8 * 0.2 / 100,000)). Deterministic smooth weighted round-robin hits exact integer ratios per node, but introduces cross-thread contention on the hot path. - Buffering vs. capacity-aware rerouting during outages. Buffering in
dest.es-alphapreserves exact cluster placement and per-key ordering at the cost of delayed search visibility (draining to S3 if an outage exceeds 6 hours of the 24-hour Kafka retention). Rerouting keeps logs live immediately, but requires capping redirected traffic to healthy clusters' measured spare headroom and spilling excess to S3 so one outage never cascades into two. - Centralized health overrides with leases vs. per-gateway health checks. Having one leader Health Controller write overrides attached to a 60-second etcd lease (an auto-expiring key) ensures all 18 gateways switch cleanly in unison and revert safely to buffering if the controller dies, trading a couple seconds of detection latency to avoid 18 gateways flapping independently.
- At-least-once delivery with idempotent sinks vs. distributed transactions. Setting Elasticsearch's
_id = event_idand naming S3 objects by{partition}-{first_offset}absorbs sink retries without slow two-phase commits, at a modest Elasticsearch indexing overhead for checking existing document IDs (while duplicate lines from rare upstream503agent retries shareevent_idso S3 query engines can deduplicate when needed).
Common mistakes
- Promising
< 50 msall the way into Elasticsearch: Elasticsearch indexes in batches and refreshes search segments every ~1 second by default; synchronous writes to storage backends inside the HTTP handler blow past 50 ms and couple ingestion uptime to storage GC pauses. - Sharing a single Kafka topic or worker pool across destinations: If
es-alphaandes-betashare one consumer queue, a slowdown ones-alphastalls consumption fores-betatoo (head-of-line blocking). - Blindly rerouting 100% of a failed cluster's traffic to its neighbor: Sending 200k events/s of stranded
es-alphatraffic toes-betawhenes-betaonly has 50k events/s of spare headroom crasheses-betaas well. Always bound reroutes by spare capacity and overflow the remainder to elastic object storage (S3). - Parsing full JSON log bodies in the routing gateway: Deserializing 100,000 JSON payloads per second per node wastes most of your CPU budget when routing only needs 2–3 envelope fields (
service,level,routing_key). - Making the data plane fail when etcd/ZooKeeper is unreachable: Gateways must serve from their last known in-memory (and disk-backed) routing table if the config store goes down; only new weight edits should pause.
- Hammering a degraded cluster with tight retries: Retrying bulk failures immediately without exponential backoff, jitter, and a circuit breaker prevents an overloaded Elasticsearch cluster from recovering.
- Committing Kafka offsets before the sink confirms persistence (or retrying
400errors forever): Committing early loses logs on worker crash, while retrying permanent schema errors (400 Bad Request) instead of routing them todlq.<dest>blocks the entire partition.
Follow-up questions
- How would you preserve per-user chronological log ordering when routing deterministically by a hashed user_id while still honoring target cluster weights? Switch the rule to weighted rendezvous hashing (each destination computes a deterministic score
-weight / ln(hash_to_unit_interval(user_id, dest))and the highest score wins), which routes every log foruser_idto the exact same cluster in exact proportion toweightwhile moving the minimum possible fraction of users when weights change (for example, shifting80/20 -> 65/35moves only 15% of users, strictly fromes-alphatoes-beta). Inside the chosendest.<id>Kafka topic, set the Kafka message key touser_idso all events for that user land in a single ordered partition, configure the sink consumer to process each partition sequentially with in-place retries, and seton_failure: "buffer"because rerouting mid-outage would split a user's timeline across two clusters. Finally, require host agents to send one in-flight batch at a time per log source with a monotonic sequence number, and schedule weight changes with a sharedactivate_at = now + 5 stimestamp so all 18 gateways cut over at the same instant.
```python import hashlib import math
def unit_hash(key: str, dest: str) -> float: """Deterministically map (key, dest) into the open interval (0.0, 1.0).""" digest = hashlib.blake2b(f"{key}|{dest}".encode(), digest_size=8).digest() top_52_bits = int.from_bytes(digest, "big") >> 12 return (top_52_bits + 0.5) / (1 << 52)
def pick_by_key(key: str, destinations: list[str], weights: list[int]) -> str | None: """Weighted rendezvous hash: picks dest with probability weight / sum(weights).""" best_dest, best_score = None, -1.0 for dest, weight in zip(destinations, weights): if weight <= 0: continue # -ln(U) is Exponential(1), so -weight / ln(U) maximizes for min(Exp(1) / weight). score = -weight / math.log(unit_hash(key, dest)) if score > best_score: best_dest, best_score = dest, score return best_dest ```
- How should the ingestion fleet auto-scale and protect itself if incoming log traffic suddenly surges 2x? Run the stateless gateway fleet at a ~60% steady-state target (60k of each node's 100k events/s ceiling) and autoscale horizontally by adding +50% instances whenever per-node events/s or CPU stays above target for 2 minutes, using
MAX_CONNECTION_AGE(~5 minutes with jitter) on gRPC/HTTP/2 listeners so persistent host agents reconnect onto the newly launched gateways. While new instances boot over 1–3 minutes, a 2x spike temporarily pushes existing gateways toward 120% capacity—so once a gateway's producer buffer passes 70%, it shedsDEBUGbatches first with429 Retry-Afterwhile host agents buffer rejected batches safely on local disk. Behind the gateways, our 9 Kafka brokers already run at ~1/3 write capacity with pre-provisioned partitions (needing only disk headroom or tiered S3 storage if sustained), sink workers autoscale on consumer lag up to partition count, and the Health Controller automatically spills any volume exceeding Elasticsearch's fixed indexing ceiling intos3-overflowfor later replay. - Which telemetry signals and alerts tell operators that a particular storage backend is turning into a throughput bottleneck? Because every destination has an isolated Kafka topic (
dest.<id>) and dedicated sink pool, bottleneck signals show up cleanly per cluster: track Kafka consumer lag in seconds (and its rate of growth), sink write throughput vs. gateway ingress rate, bulk-write p99 latency,429thread-pool rejection ratio, and circuit-breaker state. Rising lag when sink worker CPU is low proves the storage backend itself is the bottleneck (whereas saturated sink CPU with fast destination responses simply means scaling out more sink consumers). Combine pipeline metrics with backend-native health—Elasticsearch bulk write queue depth, JVM heap pressure, and disk flood-stage watermarks; S3503 SlowDownrates; or local-disk IOPS and free space—and page operators primarily on time until Kafka retention expiry (retention_hours - oldest_unconsumed_event_age), which is the hard deadline before draining to S3.
Follow-up questions
- How would you preserve per-user chronological log ordering when routing deterministically by a hashed user_id while still honoring target cluster weights?
- How should the ingestion fleet auto-scale and protect itself if incoming log traffic suddenly surges 2x?
- Which telemetry signals and alerts tell operators that a particular storage backend is turning into a throughput bottleneck?
Similar questions
- Global Live Video Streaming Platform
- Multi-User Collaborative Document Editor
- Burst-Resilient Multi-Channel Notification Platform
- Prior Authorization Status Engine, Clinical Worklists, and Digests
- Diagnosing and Optimizing Full-Stack Web Request Latency
- Multi-Source Enterprise Question Answering System