System design interview: design a distributed logging system
A distributed logging system collects log lines from thousands of machines and services, stores them for a set period, and lets engineers search them by time, service and text while an incident is happening. The interview is about ingest that never blocks the applications, an index cheap enough to keep at this volume, and storage tiers that trade query speed for cost as logs age.
By Evin JohnPublished 7 min read
1. Clarify the requirements
Logging overlaps with metrics and tracing, and interviewers often want you to notice that. Confirm that the prompt is about text log lines and full-text search, and treat metrics and alerts as neighbors.
- Functional: collect logs from hosts, containers and managed services; search by time range, service, host, level and free text; follow a live tail; find all lines for one request ID; keep logs for a retention period per team; export for audits.
- Non-functional: logging must never slow or crash the application; a line should be searchable within seconds; queries over the last hour return in seconds; no loss of acknowledged logs; costs grow slower than volume.
- Out of scope unless asked: metric dashboards and alert rules, trace visualization, security analytics, billing for teams.
2. Estimate the scale
| Quantity | Assumption | Result |
|---|---|---|
| Sources | 50,000 service instances | the number of agents to manage |
| Rate | 100 lines a second each, on average | 5 million lines a second |
| Raw volume | about 500 bytes a line | 2.5 GB a second, about 216 TB a day |
| Compressed | logs compress about 10x (repetitive text, assumed) | about 22 TB a day |
| Hot tier | 7 days searchable | about 150 TB compressed, plus index and replicas |
| Archive | 90 days in object storage | about 1.9 PB compressed |
The numbers settle two questions. A full-text index over 216 TB of raw text per day can rival the raw data in size and is costly to build, so be selective about indexing. And the archive is cheap only because object storage costs far less per terabyte than disks attached to search nodes.
3. Define the interfaces
POST /v1/ingest (agent, gzip) { source: { service, host, env }, lines: [{ ts, level, msg, attrs }] } -> 202
GET /v1/query?q={service="checkout",level="error"} |= "timeout"
&from=2027-01-10T10:00Z&to=2027-01-10T11:00Z&limit=500
GET /v1/tail?q={service="checkout"} (server-sent events or WebSocket)
GET /v1/trace/{traceId}/logs -> every line carrying that trace IDAsk teams to log structured lines, usually JSON, with a few standard fields. Structure turns parsing from guesswork into a lookup and makes trace IDs searchable.
{
"ts": "2027-01-10T10:42:17.381Z",
"level": "error",
"service": "checkout",
"env": "prod",
"host": "ip-10-2-7-41",
"trace_id": "4bf92f3577b34da6a3ce929d0e0e4736",
"msg": "payment authorization timed out",
"attrs": { "provider": "psp-a", "latency_ms": 3002 }
}4. Sketch the data model
| Data | Store | Notes |
|---|---|---|
| Raw batches in flight | Durable log (Kafka or similar), partitioned by tenant and service | Retained for a day or two as a replay buffer |
| Hot chunks | Compressed chunks on search nodes or fast disks | Grouped by label set and time window, for example 5 to 15 minutes per chunk |
| Index | Label index (service, env, level, host) mapping to chunks; optional full-text index for a few critical services | Small relative to the data when only labels are indexed |
| Archive | Object storage, columnar or compressed files by tenant, date and hour | Read back for audits or long-range investigations |
| Tenant config | Relational database | Retention, quotas, redaction rules, who can read what |
5. The core decision: what to index
| Approach | How it works | Good at | Costs |
|---|---|---|---|
| Full-text inverted index | Every token maps to the lines containing it (the Elasticsearch or OpenSearch model) | Fast free-text search across large time ranges | Index can rival or exceed the raw data; heavy indexing CPU; expensive at this volume |
| Label index plus chunk scan | Index only a few labels; store lines in compressed chunks; a query picks chunks by label and time, then scans them (the Grafana Loki model) | Cheap ingest and storage; fine for "service X, last hour, contains Y" | Broad text searches over many days scan a lot of data and are slow |
| Columnar storage | Store fields as columns in a column store (ClickHouse-style), compressed per column | Aggregations and filters on structured fields; good compression | Free-text search is slower than an inverted index; needs well-structured logs |
A defensible answer combines them: label index plus chunks as the default for everyone, a full-text index only for a few services whose teams need it and pay for it, and archive files for long retention. Keep label cardinality low. Indexing user_id or request_id as a label creates millions of tiny streams; put those in the line and search them by scan, or extract trace IDs into a separate lookup table.
6. The architecture
- Sources
- Agents on hosts and nodes
- Local disk buffer
- Ingest
- Ingest gateways (auth, quotas)
- Durable log, partitioned
- Processing
- Parsers and enrichers
- Redaction
- Chunk writers
- Storage
- Hot tier: chunks + label index
- Archive: object storage
- Query
- Query frontends (split by time)
- Queriers scanning chunks
- Live tail
- CollectThe agent reads files and container output, adds host and service labels, batches for a second or so and compresses. If the network is down, it buffers to local disk up to a cap, then drops the oldest debug lines first.
- BufferGateways write to the durable log before acknowledging. The log absorbs bursts and lets processors fall behind for a while without losing data.
- ProcessWorkers parse known formats, attach metadata (cluster, region, owning team), mask secrets and personal data by rule, and cut lines into chunks per label set and time window.
- QueryA frontend splits a 24-hour query into hourly pieces, runs them in parallel on queriers and caches results for repeated dashboards.
7. Scale it and keep it fair
- Partition by tenant and stream. Spreading the log and the chunk writers by tenant plus label set keeps one team's burst from sitting in front of everyone else's lines. The sharding guide covers picking keys that avoid hot partitions.
- Quotas at the gateway. Each tenant has an ingest rate and a burst allowance. Over the limit, the gateway answers 429 and the agent backs off, keeping its disk buffer. The token buckets behind such quotas are covered in the rate limiter walk-through.
- Sample the noise. Identical lines repeated thousands of times a second (a retry loop) can be collapsed into one line with a count. Debug levels can be sampled at the agent.
- Retention tiers. Hot for days, archive for months, deletion after that, all set per tenant. Compliance logs (audit trails) may need longer retention and write-once storage.
- Cache and limit queries. One engineer's "search everything for a word over 30 days" can starve incident responders. Cap scanned bytes per query and run long-range searches as background jobs.
8. What breaks, and what you do about it
| Failure | Effect | Mitigation |
|---|---|---|
| An incident multiplies log volume | Ingest saturates exactly when people need logs | Durable log absorbs the burst; quotas protect other tenants; error-level lines get priority over debug |
| Processor fleet falls behind | Lines searchable minutes late | Autoscale on consumer lag; live tail reads the log directly, so the freshest view still works |
| Secrets or personal data logged | Sensitive data copied into many stores | Redaction rules at processing, access controls per tenant, a deletion path that covers the archive |
| Hot tier node dies | Some recent chunks unavailable | Replicate chunks or keep them re-buildable from the durable log until they reach the archive |
| Agent misconfigured on many hosts | Silent gaps in coverage | Agents report heartbeats and line counts; alert when a service's volume drops to zero |
9. Trade-offs to discuss
- Push or pull. Agents pushing to gateways suit short-lived containers; a central collector pulling from hosts suits fixed fleets and simplifies auth. Most modern setups push.
- Index everything or index labels. Full text gives fast searches and a large bill; labels plus scans give cheap storage and slower broad searches.
- At-least-once or at-most-once delivery. Retries can create duplicate lines; deduplication by a batch ID is possible but often skipped, because an occasional duplicate log line is harmless.
- Parse at ingest or at query time. Parsing early speeds queries and enables redaction; parsing late keeps ingest cheap and lets formats change. Redaction pushes most designs toward early parsing.
- One shared platform or per-team clusters. Shared is cheaper and gives one place to search; per-team isolation limits the blast radius of a noisy neighbor.
10. How to talk through it in the interview
Fictional example
- Interviewer
- Why not index every line in a search cluster and be done?
- Candidate
- At about 216 TB of raw logs a day, a full inverted index would be large and expensive to build, and most queries are narrow: one service, the last hour, an error string. So I index a few labels, store compressed chunks, and scan only the chunks that match. Teams that need fast free-text search over weeks can opt into a full index for their services.
- Interviewer
- What about searching one request across twenty services?
- Candidate
- I would not make trace ID a label, because it would explode the number of streams. Processors write a small lookup from trace ID to the chunks that contain it, so the query reads only those chunks.
- Draw the durable buffer between agents and storage and say what it protects.
- Name label cardinality as a risk before the interviewer does.
- Close with retention tiers and quotas; it shows you have thought about who pays.
Practicing this design with Natively
Logging questions often turn into a long cost conversation, so rehearse explaining the indexing choice crisply. During a mock call, Natively captures what both people say on your Mac or Windows machine and, when you trigger it, suggests points for the current question, for example label cardinality or backpressure. Ask it to draw the ingest pipeline as a diagram to compare with your own. Afterwards, search the saved transcript for the places you said "it depends" without finishing the thought.
Questions people ask
How do you design a distributed logging system?
Run an agent on each host that batches and compresses lines and sends them to ingest gateways, which write to a durable log such as Kafka. Processors parse, enrich and redact lines and write compressed chunks with a small label index to a hot tier, and older chunks move to object storage. Query servers pick chunks by label and time, then scan them.
Why put Kafka between log agents and storage?
The durable log absorbs bursts, for example during an incident, and lets storage and processing fall behind for a while without losing acknowledged lines or slowing the applications. It also allows replay after a processing bug and lets a live-tail view read the newest lines directly.
Should a logging system use a full-text index?
Not for everything at large volume. A full inverted index can be as large as the data and costly to build. Indexing a few labels such as service, environment and level and scanning compressed chunks within a time range is much cheaper, with a full-text index reserved for the few services that need fast free-text search.
How do you stop one service from flooding the logging platform?
Give each tenant an ingest quota at the gateway with a burst allowance and answer 429 when it is exceeded, so the agent backs off and buffers locally. Collapse repeated identical lines into one with a count, sample debug levels, and cap how much data one query may scan.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
