Real-Time Log and Metrics Telemetry Platform
Medium · System Design · Software Engineer · Onsite
Prompt
Architect a centralized observability platform that collects, stores, and serves application logs and operational metrics across thousands of backend services.
Your platform must satisfy three core behaviors:
- High-fan-in asynchronous collection: Thousands of distributed services emit log records and metric samples continuously without slowing down or blocking live user traffic.
- Near-real-time visibility: Engineers must be able to search recent logs, stream live output during active incidents, and power live monitoring dashboards and alerts within seconds of emission.
- Multi-tenant resilience at scale: Sudden traffic surges, noisy deployments, or partial infrastructure outages must not trigger cascading application failures or silently drop acknowledged telemetry.
Scope & Expectations
- Define ingestion and query APIs along with physical data models tailored to structured/text logs versus numeric time-series metrics.
- Present the end-to-end architecture spanning host collection, durable buffering, storage engines, and low-latency query execution.
- Explain how the pipeline sustains heavy write volume while keeping newly arrived events searchable and streamable within seconds, including backpressure and load-shedding rules.
- Cover partitioning keys, indexing trade-offs, tiered data retention, fault tolerance, and horizontal scaling.
Step-by-step walkthrough
Clarify requirements and separate logs from metrics
"Logs and metrics" are often mentioned together, yet they have completely different shapes and access patterns. Recognizing that difference up front drives the entire architecture:
- A log event is an individual timestamped record containing a free-text message and structured key-value fields (
service,host,level,trace_id,attributes). Each record is relatively large (~500 bytes), volume is massive, and engineers search logs ad hoc ("show meERRORlines containingtimeoutfrompayments-apiin the last 15 minutes"). - A metric sample is a single floating-point number attached to a named counter or gauge over time, such as
http_requests_total{service="search", status="500"}. Each sample is tiny (a timestamp plus one number), and dashboards or alert rules read millions of data points aggregated over time windows (rates, sums, percentiles).
Trying to force both into one database hurts both workloads. Instead, we use one shared ingestion pipeline (local agents, stateless gateways, and a durable stream) feeding two specialized storage engines: 1. A columnar log store — a database that stores each column in its own compressed file on disk so queries only read the columns they filter on. 2. A time-series database (TSDB) — a database built to append tiny
(timestamp, value)pairs to millions of active series in memory and compress them tightly.Functional requirements
- Thousands of services emit logs and metrics asynchronously through a lightweight library (SDK) and a per-host agent; application threads never wait on network calls to the logging platform.
- Engineers search logs by time range,
service,env, severitylevel,trace_id, structured attributes, and free-text tokens, ordered newest first with cursor pagination. - Live tail: engineers stream matching log lines in real time as they arrive.
- Dashboards and an alerting engine query aggregated metrics over time (rates, percentiles, grouped by labels).
- Tiered retention by data class: debug logs for 3 days, standard logs for 30 days, and security/audit logs for 1 year.
Non-functional requirements
- Real-time freshness: 99% of log lines (p99, the 99th-percentile latency) become searchable within
10 sof emission; live tail displays lines within~2 s; metric samples become queryable within~15 s. - Interactive query speed: 95% (p95) of 1-hour single-service log searches finish in under
2 s, and 24-hour searches in under10 s. - Zero impact on host applications: if the logging pipeline slows down or goes offline, applications shed log lines (and increment a drop counter) rather than blocking user requests or running out of memory.
- No silent data loss after acknowledgment: once the ingestion gateway returns HTTP
200, the batch survives single-node or single availability zone (AZ) failures (an AZ is an isolated data center within a cloud region with independent power and networking). - Multi-tenant isolation: one runaway service logging 20x its normal volume cannot delay or drop other services' telemetry.
Scale assumptions for a large platform
~3,000microservices running across~150,000hosts and containers in one 3-AZ region (additional regions run independent stacks; see follow-ups).- Logs:
2M events/saverage,5M events/speak,500 Baverage raw event size. - Metrics:
40Mactive time series scraped or pushed every15 s. - Delivery guarantee: at-least-once delivery (every acknowledged batch is written at least once; rare duplicate records during crashes are acceptable, whereas losing acknowledged records is not).
- Users:
~5,000engineers,~1,500live dashboards refreshing every30 s, plus automated alert rules.
- A log event is an individual timestamped record containing a free-text message and structured key-value fields (
Back-of-the-envelope capacity planning
Let's turn those assumptions into concrete network, broker, memory, and disk numbers so we can see where the real bottlenecks live.
1. Log volume (500 B raw per event) Average ingest: 2,000,000 events/s x 500 B = 1.0 GB/s raw Peak ingest: 5,000,000 events/s x 500 B = 2.5 GB/s raw (= 20 Gbit/s network) Daily raw volume: 1.0 GB/s x 86,400 s/day = 86.4 TB/day Average per host: 2,000,000 / 150,000 hosts = ~13.3 events/s (~6.7 KB/s raw) Local disk buffer: 2 GB raw ring per host = ~83 hours for an avg host (~1.7 h at 50x rate) 2. Stateless ingest gateways Capacity per node: ~100,000 events/s (zstd decompress + schema check + regex secret scrub) Needed at peak: 5,000,000 / 100,000 = 50 nodes 3-AZ N+1 sizing: 75 nodes (25 per AZ) so if 1 AZ goes down, 50 surviving nodes still handle peak 3. Kafka durable stream (zstd batches ~5x compression; 3x replication across 3 AZs) Log stream in: 200 MB/s avg, 500 MB/s peak -> x3 replicas = 1.50 GB/s peak disk writes Metric stream in: 40M series / 15 s = ~2.67M samples/s x ~30 B batched = ~80 MB/s -> x3 = 0.24 GB/s Total disk writes: 1.50 + 0.24 = 1.74 GB/s at peak Broker count: at ~100 MB/s sustained disk writes/broker, need 18 surviving brokers at peak -> run 27 brokers (9 per AZ) so 2 surviving AZs still give 18 brokers (1.8 GB/s) 24h retention: (200 + 80) MB/s x 86,400 s x 3 = ~72.6 TB total (~2.7 TB/broker; use 8 TB NVMe) Partitions: 384 partitions on logs.std (= 12 storage shards x 32) for parallel consumers 4. Columnar log store (~10x compression on repetitive structured + text logs) Compressed/day: 86.4 TB / 10 = 8.64 TB/day Hot tier (NVMe): 7 days x 8.64 TB x 2 replicas = ~121 TB -> 12 shards x 2 replicas = 24 nodes (~5 TB active data per node on 10 TB NVMe drives, leaving room for background merges) Warm tier (S3/GCS): days 8-30 = 23 days x 8.64 TB = ~199 TB (object storage handles 3-AZ durability) 1-year archive: audit + ERROR+ (~5% of volume) = 8.64 TB x 0.05 x 365 = ~158 TB in Parquet Peak shard rate: 5,000,000 rows/s / 12 shards = ~417,000 rows/s per shard 5. Metrics TSDB Sample rate: 40M active series / 15 s = ~2.67M samples/s Compressed disk: ~2 B/sample (delta-of-delta timestamps + XOR floats) -> 2.67M x 86,400 x 2 B = ~461 GB/day (~6.9 TB for 15 days raw) Ingester RAM: ~4 KB per active series (labels, index, open chunk) x 40M x 2 replicas = ~320 GB RAM -> 20 ingester nodes with ~16 GB series RAM each 6. Read traffic Dashboards: 1,500 dashboards x 20 panels / 30 s refresh = ~1,000 metric queries/s Log searches: ~30 queries/s normal, ~300 queries/s during a major incident Live tail: up to ~1,000 concurrent WebSocket sessionsThree architectural lessons from the math
- Batching is mandatory at every hop. At
5M events/s, nobody can afford per-event RPCs or per-event disk seeks. - Storage capacity is modest; write amplification and search scope are the real problems.
121 TBof hot SSD fits on 24 machines, whereas writing tiny batches or indexing every English word across86.4 TB/daywould multiply CPU and disk costs by 5–10x. - Scoped parallel scans are fast enough to skip a heavyweight full-text index. Suppose one large service generates 1% of all logs (
20,000 events/s). Over 1 hour (3,600 s), that is72Mrows. Ifmessageis300 Braw per row (21.6 GBraw), 10x columnar compression shrinks it to2.16 GBtotal — just180 MBper shard across 12 shards, which NVMe SSDs scan in well under half a second.
- Batching is mandatory at every hop. At
Ingestion and query APIs
Applications write to
stdoutor a local memory buffer; the node agent on each host talks to the platform over OpenTelemetry Protocol (OTLP) — a standard vendor-neutral format for logs, metrics, and traces using Protocol Buffers (protobuf) (a compact binary serialization format) over mTLS (mutual TLS, where both agent and server prove their identity with certificates).Ingestion endpoints
POST /v1/logs OTLP protobuf over HTTPS (or gRPC Export), mTLS Content-Encoding: zstd <= 4 MB compressed, <= 10,000 log records per batch Request body: resource: {service.name, service.version, env, region, host, pod} records: [{time_unix_nano, severity, body, trace_id, span_id, attributes{...}}] Responses: 200 OK {partial_success: {rejected_log_records: 2, error_message: "record 17: ATTRIBUTE_TOO_LARGE"}} -> valid records are durably stored; bad records are dropped and counted 429 Too Many Requests Retry-After: 2 -> this service exceeded its quota 503 Service Unavailable Retry-After: 1 -> downstream Kafka queue is full; nothing stored, retry 400 Bad Request -> corrupt protobuf frame; agent dead-letters batch POST /v1/metrics OTLP metrics or Prometheus Remote-Write (snappy/zstd protobuf)Query endpoints
POST /v1/logs/search Request: {"from": "2026-11-27T10:00:00Z", "to": "2026-11-27T10:15:00Z", "filter": {"service": "payments-api", "env": "prod", "level": ["ERROR", "WARN"], "attributes.http.status_code": "500"}, "text": "timeout", // fast whole-token match; full regex allowed with stricter scan cap "trace_id": "4bf92f3577b34da6a3ce929d0e0e4736", "limit": 500, "order": "desc", "cursor": "eyJ0cyI6..."} Response 200: {"rows": [...], "cursor": "eyJ0cyI6...", "stats": {"scanned_bytes": 412000000, "partial": false, "freshness_ms": 3100}} POST /v1/logs/histogram per-minute counts grouped by severity for the timeline bar chart GET /v1/logs/tail?service=... WebSocket live stream; capped at 2,000 lines/s (sampled above cap) GET /v1/metrics/query_range PromQL expression, start, end, step (e.g., 30s)Why each API rule exists
- Per-record
partial_success(200) vs. whole-batch400: If 1 log line out of 10,000 has a 1 MB stack trace, rejecting the entire batch would trap the agent in an endless retry loop or drop 9,999 healthy lines. - Distinct
429vs.503: On both codes the agent backs off and keeps batches on local disk, but operations dashboards treat them differently —429blames one noisy tenant, while503pages the logging platform team. - Honest
partialandfreshness_msmetadata: During an outage, if Shard 4 times out or lags by 18 seconds, telling an on-call engineer0 errors foundis dangerous. Returningpartial: truewarns them immediately that results are incomplete. - Mandatory time window: Every search requires
fromandto(max 24 hours for interactive text scans; longer searches run as asynchronous background jobs).
- Per-record
Data model and physical storage layout
Normalized log record (produced by the gateway)
ts DateTime64(9) producer timestamp in nanoseconds (clamped if clock is skewed) ingest_ts DateTime64(3) gateway receive timestamp in milliseconds service, env, region, host, pod level Enum8 TRACE=1, DEBUG=2, INFO=3, WARN=4, ERROR=5, FATAL=6 trace_id String W3C distributed trace identifier (empty if none) message String UTF-8 log body, truncated at 32 KB attributes Map<String, String> up to 64 structured key-value pairs event_id FixedString(16) (agent_id, boot_epoch, seq_no) for duplicate detection sample_rate UInt16 1 = unsampled; N = gateway kept 1 out of N similar linesClock-skew protection: Gateways never trust producer clocks blindly. If
tsis more than2 hoursin the future or24 hoursin the past, the gateway setsts = ingest_tsand preserves the raw value inattributes["raw_ts"]. Otherwise, one misconfigured container clock from 2019 would create ancient daily partitions on cold storage and slow down partition management.Columnar log table (ClickHouse-style MergeTree, one table per retention tier)
CREATE TABLE logs_std_30d ( ts DateTime64(9), ingest_ts DateTime64(3), service LowCardinality(String), env LowCardinality(String), region LowCardinality(String), host String, level Enum8('TRACE' = 1, 'DEBUG' = 2, 'INFO' = 3, 'WARN' = 4, 'ERROR' = 5, 'FATAL' = 6), trace_id String, message String, attributes Map(LowCardinality(String), String), event_id FixedString(16), sample_rate UInt16 DEFAULT 1, INDEX idx_trace trace_id TYPE bloom_filter(0.01) GRANULARITY 4, INDEX idx_msg message TYPE tokenbf_v1(32768, 3, 0) GRANULARITY 1 ) ENGINE = ReplicatedMergeTree PARTITION BY toDate(ts) ORDER BY (service, ts) TTL toDateTime(ts) + INTERVAL 7 DAY TO VOLUME 'cold', toDateTime(ts) + INTERVAL 30 DAY DELETE SETTINGS storage_policy = 'nvme_then_s3', ttl_only_drop_parts = 1;Let's unpack each physical storage concept in plain words:
- Data parts and background merges: Every batch insert writes a new immutable directory called a part (with rows sorted by
(service, ts)), and background threads continuously merge small parts into larger ones to keep reads fast. - Granules and the sparse primary index (
ORDER BY (service, ts)): Each sorted part is sliced into 8,192-row blocks called granules. Instead of indexing every single row (which wouldn't fit in RAM at trillions of rows), the sparse primary index records only the first(service, ts)key of each 8,192-row granule — like listing only the first word at the top of each dictionary page. A query forservice = 'payments-api'between10:00and10:15binary-searches that tiny in-memory list and jumps straight to the matching granules. - Bloom filter skip indexes (
idx_trace,idx_msg): A Bloom filter is a compact bit array computed from hashed tokens in a granule that answers "could"timeout"appear in these 8,192 rows?" A "no" is 100% certain (we skip reading those disk blocks completely); a "yes" has a tiny false-positive chance. With32 KB(262,144bits) and3hash functions per granule, a granule containing15,000distinct words has only a~0.4%false-positive rate (skipping99.6%of irrelevant blocks for rare errors), rising to~8%at50,000distinct words. - Zero-cost retention via partition drops:
PARTITION BY toDate(ts)groups parts by UTC day, andttl_only_drop_parts = 1moves whole 7-day-old part folders to S3/GCS (cold) and unlinks 30-day-old part folders in milliseconds — avoiding row-by-rowDELETErewrites across170 billiondaily rows. Frequently queried map keys (likehttp.status_code) can also be promoted to dedicated columns.
Metric time-series layout
series_key metric_name + sorted labels: http_requests_total{code="500",region="eu",service="search"} series_id 64-bit hash (xxHash64) of series_key chunks up to 120 (ts_ms, float64) samples compressed with Gorilla delta-of-delta + XOR (~2 B/sample) index per-2-hour block inverted index mapping each label="value" pair -> sorted list of series_ids- Data parts and background merges: Every batch insert writes a new immutable directory called a part (with rows sorted by
High-level architecture
3,000 services across 150,000 hosts / pods [ App process ] ---> non-blocking SDK ring buffer (8 MB RAM; drop + count if full) | stdout / Unix domain socket v [ Node Agent ] batches every 1 s or 1 MB, zstd-compresses, 2 GB local disk ring, backoff + jitter | HTTPS OTLP, mTLS v [ L7 Load Balancer ] ---> [ Stateless Ingest Gateways (75 across 3 AZs) ] auth, schema check, clamp skewed clocks, scrub secrets, per-service token-bucket quotas + priority sampling | Kafka produce (acks=all, min.insync.replicas=2) | key: logs = hash(service, host) | metrics = hash(series_key) v [ Kafka Cluster: 27 brokers across 3 AZs, RF=3, 24-48h NVMe retention ] topics: logs.std (384 partitions), logs.debug, logs.audit, metrics (128 partitions) ______________________|____________________________________ | | | v v v [ Log Writers (48) ] [ Live-Tail Service (24) ] [ Metric Ingesters (20) ] 4 writers/shard x 12 own Kafka consumer group; 2 replicas per partition; flush 2 s or 200k rows service-indexed filters in-memory head (~2h) | | WebSocket | cut immutable block / 2h v v v [ Hot Log Store: 12 shards x 2 replicas, NVMe ] [ Object Storage (S3 / GCS) ] 7d local NVMe ---(TTL move after 7d)----------------> warm log parts (days 8-30), ^ 1y Parquet archive, 13m metric blocks |____________________________ ____________________________^ | | [ Query Frontend + Stateless Queriers ] time-slice caching, scan budgets, 12-shard scatter-gather ^ [ Engineer UI: Search / Live Tail / Dashboards ] + [ Alert Evaluator ]Tracing a single log event from top to bottom shows why each layer earns its keep:
- Decoupled ingestion vs. storage: Kafka sits as a shock absorber between unpredictable application traffic and picky storage engines. If a storage node reboots or background merges slow down, writers simply lag a few seconds behind in Kafka while gateways keep returning
200and applications notice nothing. - Single stream, multiple readers: Writing once to Kafka lets log writers, the live-tail service, and security anomaly detectors read the exact same stream independently without slowing each other down.
- Specialized storage per signal: Columnar MergeTree shards excel at scanning millions of compressed strings per second, while TSDB ingesters excel at appending tiny 16-byte samples to 40M active counters in RAM.
- Decoupled ingestion vs. storage: Kafka sits as a shock absorber between unpredictable application traffic and picky storage engines. If a storage node reboots or background merges slow down, writers simply lag a few seconds behind in Kafka while gateways keep returning
Deep dive 1: Sustaining heavy write volume and end-to-end backpressure
Absorbing
5M events/ssafely requires two things at every hop: batching (turning millions of tiny items into thousands of sequential megabyte-sized blocks) and backpressure (a chain of bounded buffers with explicit rules for waiting or shedding load when a downstream stage fills up).App SDK (8 MB RAM) -> Agent (2 GB disk) -> Gateway queue -> Kafka (73 TB disk) -> Writer (2s / 200k rows) drop + count retry w/ jitter 503 pushback 24-48h buffer stretch window to 5s1. Inside the application (SDK): Logging appends to an
8 MBlock-free ring buffer (a fixed-size circular array in memory). If the local agent stalls and the ring fills up, the SDK never blocks the caller thread — it drops the line and increments a local counterlogs_dropped_total{severity}. Blocking user threads on logging would turn a telemetry hiccup into a site-wide checkout outage.2. On the host (Node Agent): The agent reads from the SDK, buffers batches in a
2 GBon-disk write-ahead ring, compresses1 MBor1 sbatches withzstd, and leaves each batch on disk until a gateway returns200. If its2 GBdisk cap fills during a prolonged outage, it evicts lowest-severity records (DEBUG, thenINFO) first soERRORandFATALlogs survive.import random import time MAX_DISK_BUFFER_BYTES = 2 * 1024 ** 3 def ship_forever(disk_buffer, gateway): backoff_s = 0.5 while True: # Peek the oldest unacknowledged batch (up to 1 MB or 1 second old) without deleting it yet. batch = disk_buffer.peek_batch(max_bytes=1_000_000, max_wait_s=1.0) if batch is None: continue status, retry_after_s = gateway.send(batch) if status == 200: # Safe on 3 Kafka replicas: now we can remove the batch from local disk. disk_buffer.ack(batch) backoff_s = 0.5 elif status == 400: # Malformed payload: retrying will never succeed, so quarantine and move on. disk_buffer.dead_letter(batch) else: # Covers 429 (quota), 503 (pipeline busy), 502/504, or network timeout (status is None). base_wait_s = max(retry_after_s or 0.0, backoff_s) # Multiply by random jitter [1.0, 1.5] so 150k agents do not retry at the exact same instant. time.sleep(base_wait_s * random.uniform(1.0, 1.5)) backoff_s = min(backoff_s * 2.0, 30.0) def append_record(disk_buffer, record): # If the 2 GB local disk cap is full, drop DEBUG/INFO batches before losing ERROR logs. while disk_buffer.size_bytes() + record.size_bytes > MAX_DISK_BUFFER_BYTES: if not disk_buffer.evict_lowest_severity(): return False disk_buffer.append(record) return True3. At the stateless gateway: Each gateway enforces per-service quotas in memory using a token bucket (a counter that refills at
service_quota / num_gatewaysbytes per second, requiring zero cross-node coordination). When a service exceeds its quota: -WARN,ERROR, andFATALrecords pass through unsampled (sample_rate = 1) up to a generous safety ceiling; -INFOandDEBUGrecords are deterministically sampled1-in-Nwithsample_rate = Nstamped on kept rows (so histogram queries multiply bysample_rateand still estimate true volume accurately); - Only past the hard ceiling does the gateway return429. If the gateway's own Kafka producer buffer exceeds 80% capacity, it returns503so agents hold logs on their150,000local disks. Gateways return200only after Kafka confirmsacks=allacross at least2in-sync AZ replicas.4. Kafka partition key (
hash(service, host)): - Partitioning byservicealone routes a giant service (10% of platform traffic =500k events/s) onto a single Kafka partition, overloading one broker and one writer. - Partitioning by(service, host)spreads that giant service evenly across all 384 partitions while preserving exact chronological log order per host and keeping similar strings together for betterzstdcompression.5. Shard-aware columnar writers: Columnar stores hate tiny inserts because every insert creates a new disk part that background threads must merge. We divide the 384 partitions into 12 groups of 32 (one group per shard), with 4 writer processes per shard (8 partitions per writer), flushing every
2 sor200,000rows: - Peak rows per insert:(417,000 rows/s per shard x 2 s) / 4 writers = ~208,000 rows. - Part creation rate:4 writers / 2 s = 2 new parts/s per shard— completely comfortable for background merges.def write_loop(consumer, store): while True: # Collect up to 200k rows (or wait at most 2 seconds) across this writer's 8 partitions. batch = consumer.poll_batch(max_rows=200_000, max_wait_s=2.0) if not batch.records: continue rows = [] for record in batch.records: rows.append(to_columnar_row(record)) # Deterministic token from partition offset ranges, e.g. "p17:1200-1450,p18:900-1010". # If store.insert retries internally after a socket timeout, ClickHouse drops the duplicate block. dedup_token = batch.offset_ranges_text() store.insert("logs_std_30d", rows, dedup_token=dedup_token) # Commit Kafka offsets ONLY after storage acknowledges, guaranteeing at-least-once delivery. consumer.commit(batch.next_offsets())Notice what happens on failures: if
store.inserthits a network blip and retries the samerowsin memory, ClickHouse sees the identicaldedup_tokenin its recent-blocks cache (replicated_deduplication_window) and ignores the second copy. If the writer process crashes afterstore.insertand beforeconsumer.commit, the replacement writer replays from the last committed offset; even if its newly polled 8-partition batch has slightly different boundaries (producing a newdedup_token), every row carriesevent_id, allowing queries or the UI to collapse any rare duplicate lines cleanly.Deep dive 2: Serving freshly ingested telemetry within seconds
Storage systems face an inherent tension between write efficiency (big, infrequent batches) and read freshness (seeing events immediately). Three patterns exist, and we combine the right ones for logs vs. metrics:
Pattern Typical freshness Trade-off A. Fast micro-batch flushes to storage ~4–5 sOne unified query path; pushing below 1–2 sexplodes part counts and merge CPUB. Queryable in-memory head block < 1 sIdeal for tiny fixed-size metric samples; expensive in RAM for 1 GB/sof text logsC. Direct stream filtering from Kafka ~1–2 sInstant "watch live" feed; supports streaming filters only, not historical aggregations Logs combine Pattern A (for search) + Pattern C (for live tail). Here is the concrete end-to-end latency budget for search:
App SDK -> local Node Agent < 0.10 s Agent batch window (1 s or 1 MB) <= 1.00 s HTTPS OTLP -> Gateway -> Kafka (acks=all, 3 AZs) ~0.05 s Writer batch window (2 s or 200k rows) <= 2.00 s Columnar part write + visibility on primary replica ~0.60 s Async replication to second shard replica ~1.00 s -------------------------------------------------------------- Typical end-to-end freshness: ~4.0-4.8 s (SLO: p99 <= 10 s)- Graceful merge protection: If background merges on a shard start falling behind (active part count per partition climbs past a threshold), writers automatically widen their batch window from
2 sto5 s. Search freshness slips from~5 sto~8 s— still inside the10 sSLO — while cutting part creation in half. Queries covering the most recent 5 minutes also prefer the replica that writers insert into directly, shaving off the~1 sreplication lag. - Scaling Live Tail (Pattern C) without melting CPUs: The live-tail tier reads Kafka with its own consumer group (
24instances,16partitions each). Naively testing5,000,000 events/sagainst1,000active engineer WebSocket filters would require5 billionfilter evaluations per second! To prevent that, every live-tail session must specify at least oneservice. Tail nodes index active filters in a hash map keyed byservice: when a log arrives forpayments-api, it is checked only against the handful of engineers currently tailingpayments-api. Matched lines forward to the user's WebSocket gateway capped at2,000 lines/s(excess lines are sampled with a UI banner:"Showing 2,000 of 18,400 lines/s").
Metrics use Pattern B (in-memory TSDB head): Appending one 16-byte sample every 15 seconds across
40Mseries would create horrible write amplification in a batch columnar table, whereas in a TSDB head block each active series simply appends 2 compressed bytes to an open in-memory chunk. Queriers read recent minutes straight from the ingesters' RAM (two replicas per Kafka partition in separate AZs; a crashed ingester rebuilds its 2-hour head by replaying Kafka). Every 2 hours, each ingester seals its memory head into an immutable block and uploads it to object storage.Freshness-aware query caching: The query frontend splits dashboard range queries into aligned 1-hour windows. Windows that ended more than
10 minutesago are cached in Redis (expiring after1 hourin case an offline host uploads late logs), while the trailing 10-minute window is always queried live so engineers never stare at stale graphs during an incident.- Graceful merge protection: If background merges on a shard start falling behind (active part count per partition climbs past a threshold), writers automatically widen their batch window from
Deep dive 3: Sharding, skip indexes, tiered retention, and scaling
Let's trace what happens step by step when an engineer runs:
service = "payments-api" AND level IN ("ERROR", "WARN") AND message CONTAINS "timeout"overlast 1 hour.[ Query Frontend ] 1. Estimate scan cost; enforce per-user concurrency + byte budget | | 2. Scatter sub-query in parallel to 1 replica of each of the 12 shards v [ Shard 1 .. 12 ] 3a. Partition pruning: open only today's partition folder 3b. Sparse primary index (service, ts): jump to 'payments-api' granules in [t-1h, t] 3c. Token Bloom filter (idx_msg): test hash("timeout") per 8,192-row granule; skip 99%+ of granules that lack the token 3d. Read compressed 'level' + 'message' columns ONLY for surviving granules; verify exact substring/token match and return top 500 by ts DESC | v [ Query Frontend ] 4. Gather & merge-sort 12 sorted streams -> top 500 rows + cursor + statsWhy scatter across all 12 shards instead of pinning one service per shard? - Pinning each service to one shard avoids fan-out, but our largest service (10% of all logs) would overload its single shard on both writes and incident queries while small shards sit idle. - Spreading every service evenly across all 12 shards eliminates hot shards completely and divides every large scan across 12 NVMe machines in parallel (scatter-gather). A 12-way fan-out adds negligible network overhead. If the cluster ever grows past
~100 shards(where tail latency of the slowest of 100 nodes starts hurting), we switch to shuffle sharding — assigning normal services to a deterministic subset of 4 shards and giant services to 16–32 shards.Why sort key + Bloom skip indexes beat a full inverted index here - A full inverted index (Elasticsearch / OpenSearch style, mapping every distinct word in the corpus to exact row IDs) makes Needle-in-a-Haystack searches across all services fast, but tokenizing and building posting lists at
86.4 TB/dayconsumes massive ingest CPU and doubles or triples hot storage. - Because95%+of debugging queries already know theserviceand a narrow time window, sorting by(service, ts)plus a32 KBper-granule Bloom filter delivers sub-second queries at a fraction of the ingest and hardware cost. Unscoped multi-day needle searches ("find this email address across all 3,000 services over 7 days") run asynchronously via a background worker pool with strict I/O throttling.Guarding metric cardinality: In a TSDB, cardinality is the total count of unique
(metric_name, labels)combinations. If a developer accidentally attachesuser_idorrequest_idas a metric label, one metric explodes into50 millionseries and exhausts ingester RAM. Gateways and ingesters enforce strict budgets (<= 100kactive series per metric name,<= 2Mper service), dropping new series above the cap with an alert; high-cardinality IDs belong in logs and traces, never metric labels.Zero-copy shard scaling: When log traffic doubles and we add 4 new shards (12 -> 16), we never copy existing terabytes across the network. Instead, writers begin routing new Kafka batches across all 16 shards, queries scatter across all 16 shards, and the old 12 shards naturally shed excess disk usage over 30 days as daily partitions age out via TTL.
Reliability, failure handling, and trade-off summary
Failure scenario System behavior Data lost? Local agent hangs or crashes App SDK 8 MBring buffer fills, drops new lines, incrementslogs_dropped_total; app latency unaffectedBounded & counted at edge Host reboots (disk intact) Agent restarts and ships unacknowledged batches from its 2 GBdisk bufferNone Gateway node or 1 entire AZ fails In-flight HTTP requests fail/time out; agents retry another gateway; surviving 50 gateways + 18 Kafka brokers ( min.insync.replicas=2) keep serving full peakNone (rare duplicates) Writer crashes mid-insert Kafka reassigns its 8 partitions; new writer replays from last committed offset with dedup_token/event_idNone Storage shard down or overloaded That shard's 4 writers pause in Kafka (up to 48h buffer); searches return 200from 11 shards withpartial: trueNone if repaired within 48h Runaway deploy logs 20x volume Gateway token bucket keeps WARN/ERRORand samplesINFO/DEBUGwithsample_rate=N; all other services unaffectedSampled low-severity only "Query of death" ( .*timeout.*over 30d)Query frontend enforces max scanned_bytes, 10 s interactive timeout, and per-user concurrency limitsN/A Monitoring the monitor: A logging system must never rely solely on itself to page engineers when it breaks! Gateways, Kafka brokers, writers, and storage nodes export health metrics (503 rates, Kafka consumer lag, active part counts) to a tiny, isolated "meta-monitoring" Prometheus pair. In addition, a synthetic canary in each AZ emits a tagged log line every
10 sand queries for it continuously, measuring true end-to-end freshness and paging on-call ifp99 > 10 s.Summary of key trade-offs
- Non-blocking edge vs. zero loss on crash: Dropping at the SDK ring when overloaded guarantees logging never takes down production revenue, trading away the last seconds of buffered logs if a host's disk dies before flush.
- Kafka shock absorber vs. direct database writes: Operating a 27-broker Kafka cluster adds infrastructure and
~50 ms, buying 24–48 hours of outage survival and fan-out to writers + live tail from one stream. - Columnar
(service, ts)+ Bloom skip indexes vs. full-text inverted index: Cuts ingest CPU and SSD footprint dramatically while keeping service-scoped searches sub-second, at the cost of slower unscoped multi-day text scans. - 2-second writer batches + separate Live Tail vs. sub-second database inserts: Keeps background part merges healthy (
~5 ssearch freshness) while still giving engineers~1–2 sstreaming visibility via Kafka live tail. - 12-way scatter-gather vs. service-to-shard pinning: Eliminates hot-service shards on both writes and reads at the modest cost of fanning each query across 12 nodes.
Intuition & how it works
Think of a real-time logging and telemetry platform like an emergency mailroom and filing warehouse for thousands of busy hospital departments. Doctors and nurses (application services) can never pause patient care to walk down to the basement and file a note in a cabinet. Instead, they drop notes into a small outbox tray on their desk (SDK ring buffer — a fixed-size circular memory queue that never blocks the caller), a floor courier (node agent) bundles and zips a stack of notes once per second onto a local cart, a front reception desk (ingest gateway) checks badges and throttles spam, and a fireproof conveyor belt (Apache Kafka — a distributed append-only message log replicated across data centers) holds up to 48 hours of bundles if the filing room slows down. At the end of the belt, two different specialists take over: detailed text notes go into date-sorted, column-compressed filing cabinets (columnar log store) in big 2-second stacks, while numerical vital signs (requests/sec, CPU %) update live wall charts kept in memory (time-series database, or TSDB). Meanwhile, a glass viewing window over the conveyor belt (live tail) lets an engineer watch matching notes roll by within a second without opening a single filing cabinet.
Why do naive designs collapse at scale? Sending every log line synchronously over HTTP or inserting rows one-by-one into a traditional database (INSERT INTO logs) slows down customer requests, crashes applications with out-of-memory errors whenever the logging database hiccups, and overwhelms disk drives at 5 million writes per second. Building a full word-by-word search index over 86 TB of daily logs burns massive CPU and SSD budgets on routine INFO lines nobody ever reads, whereas skipping indexes completely forces multi-terabyte table scans just to inspect 15 minutes of errors.
Let's trace four concrete events through the pipeline to see how throughput, isolation, and real-time reads work together:
Event / Situation What happens at each stage
--------------------------------------------- ---------------------------------------------------------------
1. Normal error from payments-api App drops line into 8 MB RAM ring (<1 us) -> Agent zips 1s batch
ts=10:00:01, level=ERROR, "db timeout" -> Gateway checks quota, writes to Kafka (acks=all, ~50 ms)
-> Live Tail pushes over WebSocket at ~10:00:02.2 (~1.2s fresh!)
-> Shard writer flushes 2s batch (200k rows) to NVMe MergeTree;
searchable via (service, ts) + Bloom filter by ~10:00:05.2.
2. Bad deploy: search-api logs 20x DEBUG Gateway token bucket sees search-api over quota -> keeps 100% of
storm (400k lines/s instead of 20k/s) WARN/ERROR (sample_rate=1), samples DEBUG 1-in-20 (sample_rate=20);
Kafka and payments-api freshness stay completely untouched.
3. Storage Shard 4 reboots for 45 seconds Shard 4's writers pause; Kafka holds the backlog on disk; apps &
gateways keep succeeding (200 OK); searches return results from
Shards 1-3 & 5-12 in 400 ms with stats.partial = true.
4. Engineer searches payments-api last 15m Query fans out to 12 shards -> prunes to today's partition ->
for level=ERROR and text="timeout" jumps via sparse index to payments-api granules -> skips 99.6%
of granules via 32 KB token Bloom filter -> returns in ~350 ms.
Key trade-offs
- Asynchronous edge shedding vs. 100% capture under failure. Applications write into a bounded
8 MBmemory ring buffer and the host agent buffers up to2 GBon disk, dropping lowest-severity lines (DEBUGbeforeINFO) if full rather than blocking application threads. We trade away a tiny, counted slice of edge logs when a host crashes mid-second or loses connectivity for days, in exchange for guaranteeing that the logging system can never cause a user-facing outage; everything after the gateway's HTTP200is replicated across three availability zones (AZs) (isolated data centers within a region). - Kafka buffer between gateways and storage vs. writing directly to databases. Running a 27-broker Kafka tier adds operational moving parts and
~50 msof transit latency. In return, storage maintenance, slow background compactions, and traffic spikes turn into harmless consumer lag (up to 24–48 hours on broker disks) instead of dropped telemetry, and a single ingested stream feeds batch log writers, live tail, and metric ingesters simultaneously. - Columnar sort key
(service, ts)+ Bloom filter skip indexes vs. a full inverted index. An inverted index (a dictionary mapping every unique word in every log message to the exact list of rows containing it, as in Elasticsearch) makes needle-in-a-haystack searches across all 3,000 services fast, but building it on86.4 TB/daymultiplies ingest CPU and hot SSD size severalfold. Sorting columnar blocks by(service, ts)and attaching a32 KBBloom filter (a compact probabilistic bit array per 8,192-row block that rules out blocks missing a search token) makes95%+of real incident queries — which already filter byserviceand time — sub-second at a fraction of the hardware cost, while unscoped multi-day text hunts run as throttled background jobs. - 2-second writer batches + Kafka live tail vs. sub-second database flushes. Flushing
~200krows every2 screates only2new data parts per second per shard so background compactions keep up easily, yielding~4–5 ssearch freshness. Serving the "watch logs right this second" workflow from a direct Kafka WebSocket consumer (~1–2 slatency) avoids torturing the database with100 msmicro-inserts. - Even
(service, host)spreading + 12-shard scatter-gather vs. pinning each service to one shard. Scatter-gather means every search queries all 12 shards in parallel and merges their sorted top results. That small 12-way fan-out completely prevents our largest microservice from becoming a write and read hotspot on a single shard. - At-least-once delivery with deduplication tokens vs. end-to-end distributed transactions. Writers commit Kafka offsets after storage confirms an insert, using deterministic offset-range idempotency tokens (unique batch identifiers that let the database ignore immediate retry duplicates) plus per-record
event_ids. Rare duplicate lines after hard process crashes cost far less to collapse at read time than coordinating two-phase commits across 150,000 hosts. - Dual storage engines (Columnar + TSDB) vs. one unified database. Operating two storage engines requires more expertise, because scanning
300 Btext messages across billions of rows and appending2 Bcompressed floats every15 sto40Mactive counters have opposite memory and disk layouts.
Common mistakes
- Blocking application threads on logging (synchronous HTTP calls or unbounded in-memory queues), turning a slow telemetry pipeline into an application latency spike or out-of-memory crash.
- Sending or inserting one event at a time. At
5M events/s, skipping batching at the agent, Kafka producer, or columnar database writer overwhelms network sockets and creates millions of tiny disk files that stall compaction. - Partitioning Kafka by
servicealone, which funnels a flagship service carrying 10% of company traffic (500k events/s) into a single hot partition and a single overloaded consumer thread. - Evaluating every live-tail filter against every log event, turning
5M events/s x 1,000 engineersinto5 billionchecks/s instead of indexing active WebSocket sessions in a dictionary byservice. - Under-sizing 3-AZ clusters for AZ failover, such as provisioning 60 gateways when peak needs 50 (losing 1 of 3 AZs leaves only 40 gateways — an instant overload during an AZ outage).
- Putting unbounded high-cardinality IDs (
user_id,order_id,trace_id) into metric labels, multiplying40Mtime series into billions and crashing TSDB ingesters out of RAM. - Deleting expired logs with SQL
DELETE WHERE ts < ...instead of dropping whole daily partitions (DROP PARTITION/ part-level TTL) as an instant metadata operation. - Trusting client timestamps blindly, allowing one server with a clock stuck in 1970 or 2035 to spray tiny files across thousands of cold daily partitions.
- Alerting on the logging system through itself, so when ingestion dies, the alert meant to page the on-call team silently dies in the same broken pipeline.
- Returning
0 resultswhen a shard times out, misleading incident responders instead of surfacingpartial: truealongside results from healthy shards.
Follow-up questions
- How can an engineer retrieve every log line across 50 microservices for a single slow user request? Every service propagates a shared
trace_idheader (such as W3Ctraceparent) and the logging SDK stamps it onto every log record automatically. Because our table is sorted by(service, ts)rather thantrace_id, the query looks up the trace's start/end timestamps from the distributed tracing store (or defaults to a narrow+-15 minutewindow), fans out across all 12 shards, and uses theidx_traceBloom filter skip index (1%false-positive rate per 32,768 rows) to skip~99%of disk blocks without readingmessage. If trace-ID log lookups are very frequent, an asynchronous materialized view at insert time can also populate a tiny lookup tabletrace_id -> (service, min_ts, max_ts), turning the search into targeted primary-key jumps. - What happens step by step when a faulty release causes one microservice to emit 20x its normal log rate? Each stateless gateway tracks per-service byte rates in a local token bucket (
quota / 75 gateways). As soon as the runaway service bursts past its bucket, the gateway keepsWARN,ERROR, andFATALrecords unsampled (sample_rate = 1) up to a hard cap while dynamically samplingINFOandDEBUGrecords1-in-N(sample_rate = N) and firing an automated"logs sampled"alert to that team. If even error logs exceed the hard safety cap, the gateway returns429 Too Many Requeststo only that service's agents, which buffer up to2 GBon local host disks (evictingDEBUGfirst) while Kafka, storage writers, and every other service's 5-second freshness remain completely unaffected. - How would you adapt this architecture to operate across multiple geographic regions such as US, EU, and APAC? Run a completely self-contained ingestion, Kafka, and storage stack inside each region rather than streaming
86 TB/dayacross expensive, high-latency transoceanic links — which also satisfies regional data-residency laws like GDPR by keeping local logs in-region. For global engineering visibility, deploy a lightweight stateless global query proxy that fans cross-region searches out to only the selected regions' query frontends in parallel (marking any unreachable region withpartial: true), while replicating only tiny pre-aggregated metric rollups (~0.1%of raw volume) to a global dashboard tier.
Follow-up questions
- How can an engineer retrieve every log line across 50 microservices for a single slow user request?
- What happens step by step when a faulty release causes one microservice to emit 20x its normal log rate?
- How would you adapt this architecture to operate across multiple geographic regions such as US, EU, and APAC?
Similar questions
- Backend Fundamentals: Memory, Serialization, gRPC, Kafka, SQL, and CI/CD
- Designing a Safe Ticket-to-PR Agent Pipeline
- Payment Coverage per Booking
- Anagram Buckets, One-Swap Digit Maximization, and Hotel Review Ranking
- Global Live Video Streaming Platform
- Multi-User Collaborative Document Editor