Distributed Log Ingestion and Search Platform
Medium · System Design · Software Engineer · Onsite
Prompt
Architect a centralized observability logging platform for a large server fleet running backend microservices. Production services continuously emit log events, and on-call engineers search and aggregate those events while diagnosing live outages. Your architecture must address both sides of the workflow end to end:
- Log emission & ingestion: Trace a log entry from a library call inside application code (
billing-api,inference-router, etc.) into durable storage. Cover the client SDK interface, structured record fields (timestamps, service identity, severity, correlation/trace IDs, key-value metadata, and message body), local in-process or host-level batching, behavior when buffers saturate or downstream collectors stall, gateway authentication and validation, per-service rate isolation, durable stream buffering, duplicate handling, and explicit accounting whenever low-priority logs are sampled or shed. - Storage, indexing & query execution: Explain how ingested logs are organized on disk and object storage so engineers can filter by service, severity, and time window, match message text, fetch every line for a single request or trace ID, and chart per-minute error counts. Address time/service partitioning, compression, hot-to-cold retention tiers, the cost-versus-speed trade-off between write-time indexing and read-time scanning, parallel query fan-out, cursor pagination, near-real-time visibility of newly emitted events, access controls for sensitive logs, and safeguards against runaway queries.
Traffic volume, retention horizons, freshness targets, and overload policies are intentionally left open—begin by stating concrete quantitative assumptions.
Scope & Expectations
- Workload & SLA assumptions: Pin down realistic numbers for fleet size, average and burst ingest bandwidth, search freshness lag, retention tiers, access boundaries, and acceptable drop/sampling rules under overload.
- Non-blocking ingest pipeline: Detail how application processes, host agents, stateless gateways, and durable buffers cooperate so logging outages or noisy neighbors never stall user-facing request threads.
- Storage layout & indexing trade-offs: Justify chunk sizing, columnar/compressed formats, multi-tier retention, and which fields or tokens warrant indexes versus lightweight skip metadata and parallel scans.
- Query engine & guardrails: Walk through query planning, visibility of the most recent uncompacted minutes, time-ordered merging, aggregations, and cost budgets that prevent expensive scans from starving incident responders.
Step-by-step walkthrough
Clarify requirements and state assumptions
Because the prompt leaves traffic, freshness, and retention open, we first state concrete assumptions that anchor every sizing decision. Notice the core tension: emission & ingestion runs inside user-facing services and must be near-free and non-blocking, while storage & querying wants fast filtering and search across terabytes of data.
- Fleet and volume: 2,000 microservices across 20,000 hosts (VMs or Kubernetes nodes) in multiple regions, emitting 2 million records/s on average at ~500 bytes each = 1 GB/s raw (
86.4 TB/day). Daily peak is 3 GB/s, and a broken service can suddenly log 100× its normal rate. - Record structure: Structured logs carrying
timestamp,service,severity(TRACEthroughFATAL),body(free-text message),trace_id/request_id, and key-valueattributes. - Target queries and freshness:
- Newly emitted logs become searchable within 3 seconds typical / 10 seconds p99.
- Common incident queries (
service=billing-api, last 1 hour,level >= WARN, message contains"deadline exceeded", or looking up onerequest_id) return in 1–2 seconds. - Error-rate aggregations (
count by minute, service) return in under 1 second. - Unscoped regex scans across all 2,000 services over 24 hours are guarded by cost budgets or run asynchronously.
- Retention: 30 days hot/searchable in object storage, plus an optional 1-year cold archive for compliance services. Over 90% of queries inspect the newest 24–48 hours.
- Overload and loss policy: Logging must never block or crash an application. Under extreme overload,
DEBUGandINFOmay be sampled or dropped only if every dropped record is counted and reported;WARNand above receive reserved capacity. (Strict legal/financial audit trails belong in a separate synchronous pipeline.) - Security and privacy: Team-scoped access control per
service, audited queries, ingestion redaction, and support for user-data deletion requests.
- Fleet and volume: 2,000 microservices across 20,000 hosts (VMs or Kubernetes nodes) in multiple regions, emitting 2 million records/s on average at ~500 bytes each = 1 GB/s raw (
Back-of-the-envelope numbers: storage, indexing cost, and scan speed
Let's calculate storage footprint, buffer sizing, and the exact cost of indexing versus scanning:
Raw ingest 2M records/s x 500 B = 1 GB/s avg (86.4 TB/day), 3 GB/s peak Per-host average 1 GB/s / 20,000 hosts = 50 KB/s (~100 records/s per host) Object storage (columnar layout + Zstandard ~8x compression): Daily stored 86.4 TB / 8 = 10.8 TB/day 30-day searchable 30 x 10.8 TB = 324 TB Durable Kafka buffer (~5x wire batch compression -> 200 MB/s avg, 600 MB/s peak): Broker disk writes 600 MB/s peak x RF 3 = 1.8 GB/s across the broker cluster 72-hour retention 200 MB/s x 259,200 s x 3 = ~155.5 TB across brokers Chunks and SQL catalog: Raw 5-min flushes ~8,000 (service, partition) streams x 288/day = ~2.3M small chunks/day Hourly compaction merges small chunks per (service, hour) up to 64 MB raw (~8 MB compressed) -> ~1.4M compacted chunks/day -> ~42M catalog rows over 30 days (~13 GB)Why we do NOT build a full word-by-word index: An inverted index (a lookup table mapping every distinct word to the exact list of log IDs containing it, like a textbook index) extracts ~50 tokens per 500-byte log =
100 million index entries/s. Even at 1–2 bytes per compressed entry, the index adds 100–200 MB/s — roughly doubling our 125 MB/s compressed data size while burning heavy CPU indexing the 99%+ of logs nobody ever reads!Compare that against parallel scanning when data is partitioned by
(service, time)(at ~500 MB/s decompressed scan speed per CPU core):1 service (1% of fleet = 10 MB/s), 1 hour = 36 GB raw -> 72 core-s -> < 1 s across 100 cores! 1 service (1% of fleet), 24 hours = 864 GB raw -> 1,728 core-s -> ~17 s (or < 1 s with Bloom skip) All 2,000 services, 1 hour regex = 3.6 TB raw -> 7,200 core-s -> guarded by query budgetDesign takeaway: Partitioning by
serviceandtimeshrinks almost every real query into a fast scan, and adding tiny per-chunk Bloom filters (~3% storage overhead) skips 99% of chunks for rare error strings or IDs without paying full inverted-index costs.APIs: emitting, ingesting, and querying
1. Application logging SDK (language library;
service,env, andhostare injected once from deployment metadata so callers cannot misspell them):log = get_logger(__name__) # service, env, region, host bound automatically at startup log.info("invoice fetched", invoice_id="inv-7392", total_cents=12500) log.warning("retrying upstream ledger", invoice_id="inv-7392", attempt=2) log.error("upstream deadline exceeded", invoice_id="inv-7392", reason="rpc_timeout") # Active trace_id, span_id, and request_id are attached automatically from thread/async context2. Host-Agent-to-Gateway Ingest RPC (batched gRPC over mTLS — mutual TLS, where both client and server verify cryptographic certificates):
LogIngest.Push(PushRequest) resource: {service, env, region, host, pod_uid, version} -- sent once per batch producer_id: "<agent_uuid>:<boot_epoch>" batch_seq: monotonically increasing integer per (producer_id, service) dropped: {DEBUG: int, INFO: int, WARN: int, ERROR: int} -- upstream drops since last push records: compressed batch of LogRecord (<= 1 MB compressed, or every 1 s) Returns: OK | RESOURCE_EXHAUSTED {retry_after_ms, suggested_sample_rate} -- per-service quota exceeded | INVALID_ARGUMENT {rejected_indices, reasons} -- malformed records isolated3. Engineer Query REST API:
POST /v1/logs/query { "q": "service:billing-api level>=WARN attr.region=us-west-2 \"deadline exceeded\"", "start": "2026-12-02T14:00:00Z", "end": "2026-12-02T15:00:00Z", "order": "newest_first", "limit": 200, "cursor": null } -> { "records": [...], "next_cursor": "...", "stats": { "chunks_scanned": 34, "bytes_scanned": 268000000, "partial": false, "dropped_in_range": {"INFO": 3100, "ERROR": 0} } } POST /v1/logs/aggregate -- time-bucketed counts/rates (e.g., step="1m", group_by=["service"]) POST /v1/logs/estimate -- dry-run cost check returning {bytes_to_scan, est_seconds} GET /v1/logs/tail?q=... -- live streaming via Server-Sent Events (SSE)Every query requires
[start, end], and returningdropped_in_rangeensures an on-call engineer never mistakes dropped logs for a healthy service.Data model: log record, columnar chunk, and metadata catalog
LogRecord schema (aligned with OpenTelemetry so standard SDKs plug straight in):
ts_ns int64 application event timestamp in nanoseconds observed_ns int64 agent receipt timestamp (exposes clock skew and ingest delay) severity uint8 TRACE(1), DEBUG(2), INFO(3), WARN(4), ERROR(5), FATAL(6) body string UTF-8 message (capped at 16 KB; sets truncated=true if clipped) trace_id bytes[16] distributed trace identifier (optional) request_id string edge request identifier (optional) attributes map <= 64 structured key-value pairs (string | int64 | float64 | bool) record_key tuple (producer_id, batch_seq, index_in_batch) -- unique ID for deduplicationColumnar chunk object in S3/GCS: Each ingester packs one service's records from one Kafka partition (up to 64 MB raw / ~8 MB compressed or 5 minutes) sorted by
ts_nsinto a columnar file (where allts_nsvalues sit together, allseverityvalues sit together, and allbodystrings sit together for ~8× compression and fast column-only reads):Object key: <region>/<service>/<yyyy-mm-dd>/<hh>/<chunk_id>.col +-------------------------------------------------------------------------+ | Row-group blocks (8,000 rows each): | | [ts_ns delta-encoded] [severity dict] [host dict] [request_id] [body] | | Footer: column byte offsets + per-block {min_ts, max_ts, level_counts} | +-------------------------------------------------------------------------+ Sidecar: <chunk_id>.bloom (~240 KB) Bloom filters over trace_id, request_id, and lowercase message tokensSQL Metadata Catalog (sharded PostgreSQL / CockroachDB queried by the planner):
chunks(chunk_id PK, service, region, partition_id, min_ts, max_ts, first_offset, last_offset, record_count, bytes_raw, bytes_stored, level_counts_per_minute JSONB, tier, object_key, bloom_key, state) -- Indexed on (service, max_ts) and (service, min_ts)Storing
level_counts_per_minute(a few hundred bytes per chunk) lets error-rate dashboards over 7 days read only tiny catalog rows without opening a single object-storage file!High-level architecture
PATH 1: EMIT & INGEST (never blocks the application) +--------------------+ local +-----------------------+ mTLS +--------------------+ | App Process | rotated files | Host DaemonSet Agent | batches | Stateless Gateways | | log.info(...) | -------------> | tails WARN+ first | --------> | auth, redact, | | 8 MB ring buffer | warn / info | 5 GB disk cap + zstd | gRPC | per-service quota | +--------------------+ +-----------------------+ +---------+----------+ | acks=all v +----------------------------------+ | Kafka (1,024 partitions, RF=3, | | 72h disk, shuffle-sharded) | +--------+-----------------+-------+ | | PATH 2: INDEX, STORE & QUERY v v +------------------------+ +-------------+ | Ingesters | | Tail Nodes | | 5-min RAM head block | | live SSE | | build chunks + blooms | +-------------+ +---+----------------+---+ chunk + bloom | | metadata row v v +----------------+ +---------------+ | Object Storage | | SQL Catalog | | 30d hot / 1y | | chunks + ACLs | +-------+--------+ +-------+-------+ ^ ^ | byte-range reads | plan & prune Engineer -> Query Frontend (auth, cost budget, ------+---------------------+ fair queue, k-way merge, cache) ---> Querier Pool (48h NVMe SSD cache) + IngestersDeep dive 1 (Emit & Ingest): Non-blocking client emission and local host buffering
Consider what happens to user traffic when the logging backend stalls. If an application thread logs over the network synchronously — or even writes synchronously to
stdoutwhen a stalled container logging agent lets Linux's 64 KB pipe buffer fill up — user HTTP/RPC requests freeze! We isolate the application with two bounded local stages:App Thread -> [8 MB Lock-Free Ring Buffer] --200ms flusher--> [warn.log / info.log (5 GB host cap)] -> Agent- In-process ring buffer (microseconds, zero I/O):
log.info(...)writes into a fixed-size ring buffer (a pre-allocated circular array in RAM holding ~10,000 slots / 8 MB). A background flusher thread drains the ring every 200 ms into two bounded, size-rotated local files:warn.log(WARN/ERROR/FATAL) andinfo.log(TRACE/DEBUG/INFO).- Buffer-full policy: If disk stalls and the ring fills, incoming
DEBUG/INFOdrops immediately; incomingWARN+overwrites the oldestDEBUG/INFOslot. Every drop increments an atomic per-severity counter attached to the next batch. - Crash handling: A process
atexit/ signal handler makes one bounded 100 ms flush attempt; a suddenSIGKILL(kill -9) can lose at most the newest ~200 ms in RAM — the unavoidable trade-off for never blocking user requests.
- Buffer-full policy: If disk stalls and the ring fills, incoming
- Host agent (hours of outage survival): One lightweight agent per host tails
warn.logahead ofinfo.log, batches up to 1 MB / 1 s compressed withzstd, and advances its local file-offset checkpoint only after the gateway confirms Kafka persisted the batch.- At 50 KB/s average per host, a 5 GB local disk cap buffers ~28 hours of complete backend outage (~3 hours at 10× traffic). If the 5 GB cap fills, oldest
info.logsegments are deleted first and added todropped. - When a gateway returns
RESOURCE_EXHAUSTED(suggested_sample_rate=0.05), the agent keeps 100% ofWARN+(up to quota) and samplesDEBUG/INFOusing consistent hashing onrequest_id(hash(request_id) mod 100 < 5), keeping every log line of 5% of requests rather than an unreadable 5% confetti of every request!
- At 50 KB/s average per host, a 5 GB local disk cap buffers ~28 hours of complete backend outage (~3 hours at 10× traffic). If the 5 GB cap fills, oldest
- In-process ring buffer (microseconds, zero I/O):
Deep dive 2 (Emit & Ingest): Gateways, quotas, shuffle sharding, and deduplication
Authentication, validation, and clock-skew protection: - Gateways verify the host's mTLS certificate and check policy so a pod in
paymentscan never spoofservice: auth. - Records exceeding size/attribute caps are truncated or individually rejected; regex redaction masks stray credit-card numbers or bearer tokens before Kafka. - Clock-skew guard: If an application host's clock is wildly wrong (ts_ns> 10 minutes ahead ofobserved_nsor > 7 days behind), the gateway preserves the raw value in an attribute and substitutesobserved_nsso one bad clock cannot create millions of ancient or future chunks.Per-service quotas and shuffle sharding: - Each gateway enforces a token bucket (a rate-limiting counter refilled at a steady byte rate per second) per
service, coordinated every second by a lightweight quota controller, with separate reserved tokens forWARN+. - Approved batches write to Kafka (1,024partitions,RF = 3,min.insync.replicas = 2,acks = all). Rather than letting all 2,000 services write to all 1,024 partitions, we assign each service a deterministic subset ofkpartitions (sayk = 4for typical services) via shuffle sharding (hashing the service name to pick a unique combination of partitions). Even if two services share 1 partition, the probability they share all 4 out of 1,024 is tiny (< 1 in 40 billion), isolating lag spikes!End-to-end delivery guarantees and deduplication:
Hop Guarantee How duplicates / losses are handled ----------------------- ---------------- -------------------------------------------------------- App call -> Local file Best-effort Bounded 200 ms RAM window; every ring drop is counted Local file -> Kafka At-least-once Agent checkpoints file offset AFTER gateway/Kafka ack Kafka -> Object chunk At-least-once Ingester commits Kafka offset AFTER chunk + catalog save End-to-end query view Effectively-once 1) Ingester tracks highest batch_seq (+ out-of-order window) per (producer_id, service) for 1 h and drops retries. 2) Query merge deduplicates rare failover overlaps by record_key.Deep dive 3 (Store & Query): Time-partitioned layout and lightweight indexing
Storage tiers by data age: 1. 0–5 minutes (Ingester RAM head): Open, uncompressed/lightly compressed columnar buffers directly queryable via gRPC for instant freshness. 2. 5 minutes–48 hours (Querier NVMe SSD cache): ~22 TB distributed across querier nodes via consistent hashing on
chunk_id, serving > 90% of incident queries at local SSD speeds. 3. 0–30 days (Standard Object Storage): 324 TB of immutable compacted chunks (~8 MBcompressed each). An hourly background compactor merges small 5-minute chunks of low-volume services into64 MBraw chunks and atomically flipsstate = COMPACTEDin the SQL catalog. 4. 30 days–1 year (Cold Archive): Glacier/Archive object tier for compliance-flagged services, restored asynchronously on demand.Choosing the right index level: A Bloom filter is a compact bit array where each word sets several hashed bit positions: if any bit is
0, that word is 100% guaranteed absent from the chunk; if all bits are1, the word is probably present (with a tunable false-positive rate, here 1%).Strategy Ingest CPU & RAM Extra Storage Rare-Term Query ("inv-7392") --------------------------------- ----------------- -------------- ---------------------------- A. Full inverted index (all words) Very High ~100% (+324 TB) Reads exact matching chunks B. Metadata labels only Minimal 0% Scans 100% of service chunks C. Labels + Block stats + Blooms Low ~3% (+10 TB) Skips ~99% of chunks! (Chosen)Checking the 3% Bloom math: A 1% false-positive rate needs
9.6 bitsper distinct item. A64 MBraw chunk (~128,000 log lines) typically contains ~200,000 distinct tokens:200,000 × 9.6 bits = 240 KB, which is240 KB / 8 MB = 3%of the compressed chunk! (Putting high-cardinality IDs likerequest_idin dedicated columns with their own dedicated Bloom filters keeps the message token filter clean and accurate.)Deep dive 4 (Store & Query): Query execution, real-time freshness, and guardrails
Step-by-step execution of an incident query: 1. Authorize & prune in the SQL catalog: Query Frontend intersects requested services with the caller's ACLs, queries
chunksforservice = 'billing-api' AND max_ts >= start AND min_ts <= end, and skips chunks whoselevel_counts_per_minuteshow zeroWARN+logs in[start, end]. 2. Cost gate: Sumbytes_rawacross surviving chunks. If a query exceeds the interactive cap (say 2 TB raw), reject it immediately withbytes_to_scanand a hint to narrowserviceor time, or offer background execution. 3. Bridge the 5-minute freshness gap: Each catalog row recordslast_offsetper(service, partition_id). Alongside scanning flushed chunks on Queriers, the Frontend queries the owning Ingesters for in-memory records strictly afterlast_offset— giving ~3-second end-to-end freshness with zero missing or duplicated boundary records! 4. Two-level pruning inside each Querier: Queriers first fetch the240 KB.bloomsidecar (cached on SSD); if"deadline"or"exceeded"misses the Bloom filter, the8 MBchunk is never opened. If it hits, the footer's 8,000-row block headers skip blocks with zeroWARN+rows, and HTTP byte-range reads pull only the requested columns (ts_ns,severity,body). Straggler object-storage reads use hedged requests (firing a backup read if latency passes p95). 5. Newest-first k-way merge & cursor pagination: Frontend runs 15-minute time slices from newest to oldest, merges sorted streams via a min/max heap (k-way merge), and stops early as soon aslimit(200) rows are collected!next_cursorencodes(last_ts_ns, last_record_key, initial_ingest_offsets)so paging backward never shifts or repeats rows while new logs arrive.Multi-tenant query guardrails: Per-team fair-share scheduling queues, max 5 concurrent queries per user, a 60-second interactive timeout, automatic cancellation on client disconnect, and slice-level result caching (older immutable 15-minute slices are cached by
(query_hash, slice_window)so refreshing a dashboard only scans the newest minute).Scaling, failure modes, and summary of trade-offs
Cluster sizing and failure resilience: - Independent horizontal scaling: ~40 stateless Gateways (handling 3 GB/s peak TLS +
zstdvalidation), ~24 NVMe Kafka brokers (1.8 GB/sreplicated peak writes), ~120 Ingester cores (~25 MB/s raw chunk-building per core, ~110 GB total RAM for 5-minute heads), and an autoscaled Querier pool isolated from a separate background/export pool. - Key failure paths: - Gateways or Kafka down: Zero impact on production apps; Host Agents buffer up to 5 GB locally (~28 h avg) and drainWARN+first on recovery (provisioned at 2× average ingest to clear backlogs quickly). - Ingester crashes: Kafka reassigns its partitions; the new owner readslast_offsetfrom the SQL catalog and replays at most 5 minutes from Kafka in ~15–30 seconds. Queries hitting those partitions during replay returnpartial: truerather than failing or hiding the gap (avoiding 2× hot-standby compute). - Object storage or Catalog slow: Ingesters hold unflushed blocks in RAM up to a memory ceiling, then callconsumer.pause()so Kafka's 72-hour retention absorbs the stall without data loss.Summary of trade-offs: - Non-blocking local ring + files vs. synchronous network logging: Protects user-facing services from 100% of logging outages, trading away up to ~200 ms of RAM-buffered logs on a hard
SIGKILL(with explicit drop counters everywhere). - Kafka durable stream vs. direct-to-object-storage writes: Adds broker infrastructure, but absorbs incident bursts, decouples agent retries from chunk building, enables 72-hour parser bug replays, and powers live tailing for free. - Time/service columnar chunks + 3% Bloom filters vs. full inverted index: Cuts storage and ingest CPU roughly in half while keeping common service/time and rare-ID queries sub-second, trading off slower fleet-wide regex scans (protected by cost budgets). - Large 64 MB chunks + queryable Ingester RAM head vs. tiny 5-second files: Combines highzstdcompression and a compact SQL catalog with ~3-second real-time query freshness.
Intuition & how it works
Picture a hospital's central chart system collecting status notes from 20,000 bedside monitors at 1 GB per second. Doctors treating a patient (your production service handling a live user request) must never wait in line at a central filing cabinet: they drop each note into an in-memory ring buffer (a fixed-size circular array in RAM) in microseconds, a background helper writes notes to local host files (warn.log and info.log), and a host agent ships compressed batches through gateways into Kafka. Downstairs, instead of typing a massive word-by-word textbook index for millions of routine INFO lines nobody will ever read, clerks pack logs into compressed columnar chunks (files organized column-by-column, sorted and grouped by service and hour) and staple a tiny "words inside" checklist — a Bloom filter (a compact bit-array summary that answers "definitely not in this file" or "probably in this file") — onto each chunk's cover.
Why do the obvious designs fail? Sending logs synchronously over the network from request threads turns a slow logging backend into a site-wide production outage, while unbounded in-memory queues crash application servers with out-of-memory errors. On the query side, building a full inverted index (mapping every word of every message to exact record IDs) roughly doubles your 324 TB storage bill and burns heavy CPU on the 99%+ of logs nobody ever inspects, whereas dumping unpartitioned raw files forces every debugging query to scan terabytes of irrelevant services and days.
Follow 3 log events from billing-api across both halves of the system:
1. Emit (microseconds, zero network wait):
billing-api pod logs: INFO "invoice fetched" (req-408), ERROR "upstream deadline exceeded" (req-408), INFO "probe ok"
-> Appended to 8 MB RAM ring -> flushed within 200 ms to local warn.log & info.log.
-> Host Agent batches & zstd-compresses -> Gateway checks mTLS + quota -> Kafka (acks=all).
2. Index & Store:
-> Ingester holds newest 5 minutes in a queryable RAM buffer (~3 s freshness!).
-> Every 5 min / 64 MB raw, flushes sorted columnar chunk chk_904 + 240 KB Bloom filter to S3,
and writes row chk_904(service="billing-api", 14:00..14:05, errors=1) into the SQL Catalog.
3. Query ("service:billing-api level>=ERROR \"deadline exceeded\"", 14:00..15:00):
-> SQL Catalog prunes 42M total chunks down to 12 "billing-api" chunks in 14:00..15:00,
then skips 11 chunks whose per-minute severity counts show errors == 0!
-> Querier checks chk_904's Bloom filter ("deadline" & "exceeded" -> match), reads only chk_904's
error block + Ingester's live RAM tail, and returns the exact failure in < 500 ms.
Key trade-offs
- Non-blocking local buffering vs. strict zero-loss synchronous writes. Appending to a bounded in-memory ring buffer + local disk files guarantees logging never slows down or crashes user traffic, at the cost of potentially losing up to ~200 ms of un-flushed RAM logs on a hard process kill (
SIGKILL) or droppingDEBUG/INFOunder extreme overload. Attaching explicit per-severity drop counters to every batch makes any loss transparent rather than silent. - Partitioned scanning + Bloom filters (~3% overhead) vs. full inverted index (~100% overhead). Because every query specifies a time window and almost every query names a
service(or severe log level), columnar storage + per-chunk summaries + Bloom filters deliver 1–2 second answers at half the storage and fraction of the ingest CPU of a full inverted index. The trade-off is that unscoped fleet-wide text regexes require wide scans and must be gated by a byte-scan budget. - Large 64 MB chunks + queryable RAM head vs. tiny 5-second chunks. Flushing tiny chunks every few seconds would explode object-storage request costs and bloat the SQL catalog to billions of rows; buffering up to 64 MB / 5 minutes (plus hourly compaction) keeps compression high (~8×) while querying Ingesters' in-memory head blocks preserves ~3-second freshness.
- Kafka durable stream vs. writing directly from gateways to object storage. Running a 72-hour Kafka buffer adds broker cost, but absorbs traffic spikes, decouples agent retries from chunk building (making
batch_seqdeduplication simple), allows replaying logs after a parser bug, and feeds live tailing without touching storage. - Single ingester per partition with
partial: truefailover vs. active-active ingester replicas. Assigning one ingester per Kafka partition halves ingest CPU and RAM; if an ingester crashes, replaying its last ~5 minutes from Kafka takes ~15–30 seconds during which queries over those newest minutes returnpartial: truerather than paying 2× compute 24/7. - Strict per-service quotas with request-consistent sampling vs. shared best-effort ingest. Enforcing per-service token-bucket rate limits at the gateway means one runaway service's
INFOlogs are sampled (hash(request_id)keeps whole request traces intact while reserving headroom forWARN+), protecting the other 1,999 services from lag or dropped logs.
Common mistakes
- Making network calls or blocking pipe writes on application request threads. Even writing synchronously to container
stdoutcan block user traffic when a stalled host collector fills Linux's 64 KB pipe buffer. - Using unbounded in-memory queues in the SDK or agent. When the backend goes down for an hour, an unbounded queue grows until the application crashes with an out-of-memory error.
- Dropping logs silently under backpressure. Without per-severity
droppedcounters surfaced in query responses, engineers cannot tell "zero errors happened" apart from "95% of logs were dropped." - Random line-by-line sampling instead of consistent
request_idsampling. Keeping a random 5% of individual lines leaves 1 broken fragment of every request instead of complete end-to-end stories for 5% of requests. - Trusting raw client timestamps (
ts_ns) without bounds. One host with a misconfigured clock set to 1970 or 2099 will scatter tiny uncompacted chunks across decades unless gateways clamp extreme skew toobserved_ns. - Querying only flushed object-storage chunks. Ignoring the last 5 minutes sitting in Ingester memory hides the exact real-time logs engineers need most during a live outage.
- Running fleet-wide queries without cost guardrails or fair queuing. Without a
bytes_rawpre-check and per-team fair scheduling, one engineer running a 30-day regex across 2,000 services starves every other team's incident queries.
Follow-up questions
- Suppose a buggy deployment causes a single microservice to emit 100x its baseline log rate during an outage. How does your pipeline absorb and isolate that spike so healthy services are unaffected? Suppose
billing-apijumps from 2 MB/s to 200 MB/s (20% of the entire fleet's average volume): first, its own hosts absorb the burst into bounded local files without blocking request threads; second, Gateways hit that service's token-bucket quota and returnRESOURCE_EXHAUSTEDwith asuggested_sample_rate(say 2%), causing its Host Agents to send 100% ofWARN+within reserved headroom while consistently samplingINFO/DEBUGbyhash(request_id)and counting every drop. Because the quota blocks the 100× flood before Kafka — and shuffle sharding isolates that service to a tiny 4-partition subset out of 1,024 — the other 1,999 services see normal latency and zero drops, while the UI banners"INFO sampled at 2% (14:04–14:22)"and re-weights count charts accordingly. - How can your storage and indexing layer rapidly retrieve every log entry matching a single correlation or request ID across the entire fleet over a 30-day window? First, generate edge
request_idvalues using UUIDv7 (a standard 128-bit ID whose top 48 bits encode the Unix millisecond creation timestamp): the query planner extracts the exact start timestamp directly from the ID and narrows the 30-day window down to[start - 1 min, start + 15 min]across all services (~18,000 chunks instead of 42 million!). Queriers then check only the dedicatedrequest_idBloom filters (at 0.1% false positives =14.4 bits/ID, ~54 KB per chunk or ~1 GB total across the pool), opening just the ~5 true matching chunks plus ~18 false positives to return in ~1 second. If callers use opaque random IDs without embedded timestamps, have Ingesters emit(request_id -> chunk_id)entries into a lightweight key-value index (~650 GB/day or ~19 TB for 30 days — just 6% of compressed log storage) for directO(1)chunk lookup. - How would you support a real-time tail mode that pushes matching log lines to an engineer's terminal or browser within a couple of seconds of generation? Deploy stateless Tail Nodes holding browser/CLI Server-Sent Events (SSE) or WebSocket streams that consume directly from Kafka using manual partition assignment (subscribing only to the specific shuffle-sharded partitions of the
servicein the user's filter, starting at the latest offset with zero offset commits). Each Tail Node evaluates the query predicate on incoming batches in memory and streams matches straight to the client, achieving ~1–2 second end-to-end latency (<= 200 msapp flush +<= 1 sagent batch + tens of ms through Kafka). Protect the cluster by enforcing the same per-service ACLs, capping output at e.g. 500 lines/s per stream (inserting"N lines sampled"markers above that), and auto-closing idle tabs. - If a customer submits a regulatory right-to-erasure request and their personal identifiers already sit inside compressed, immutable log files, how do you fulfill the deletion? First minimize occurrences at ingest by redacting PII patterns (emails, cards, tokens) at the Agent/Gateway and logging a pseudonymous ID (a keyed cryptographic hash whose user mapping lives in an erasable lookup table, where legally sufficient). When raw personal data still lands in immutable 30-day chunks (or the 1-year archive) and retention exceeds the legal erasure window (such as 30 days under GDPR): immediately add the identifier to a query-time deny-list in the Query Frontend so matching records are masked instantly, then run a weekly batched background rewrite job on the separate batch pool that uses Bloom filters (or a single shared scan pass over ~1.5 hours on 1,000 cores) to locate affected chunks, writes clean replacement chunks without those rows, atomically swaps the SQL catalog pointers, deletes the old S3 objects, and writes a compliance audit receipt.
Follow-up questions
- Suppose a buggy deployment causes a single microservice to emit 100x its baseline log rate during an outage. How does your pipeline absorb and isolate that spike so healthy services are unaffected?
- How can your storage and indexing layer rapidly retrieve every log entry matching a single correlation or request ID across the entire fleet over a 30-day window?
- How would you support a real-time tail mode that pushes matching log lines to an engineer's terminal or browser within a couple of seconds of generation?
- If a customer submits a regulatory right-to-erasure request and their personal identifiers already sit inside compressed, immutable log files, how do you fulfill the deletion?
Similar questions
- Noisy Pod Alert Normalization and Outlier Replica Detection
- Crash-Safe Log-Structured Key-Value Engine
- Multi-Tenant LLM Serving and Scheduling Platform
- Single-Pass S-Expression Parser with Error Positions
- Bounded Thread-Pool Batch Executor
- Concurrent Chunked File Downloader with SHA-256 Verification
More Baseten interview questions
- Single-Pass S-Expression Parser with Error Positions Medium
- XorShift32 Stream Cipher for Tree Documents Medium
- Crash-Safe Log-Structured Key-Value Engine Hard Pro
- Noisy Pod Alert Normalization and Outlier Replica Detection Medium Pro
- Multi-Tenant LLM Serving and Scheduling Platform Hard Pro
- Bounded Thread-Pool Batch Executor Hard Pro
- Concurrent Chunked File Downloader with SHA-256 Verification Medium Pro