InterviewDryRun
Lesson 28 · 24 min video · free

Design Log Aggregation and Search

Thousands of services each write logs on their own machines, and when something breaks at three in the morning, engineers need to search all of them in seconds. This lesson designs the pipeline that collects those logs, buffers them durably, cleans and enriches them, stores them cheaply in compressed time-ordered chunks, and searches them fast with the right kind of index, while keeping costs and noisy tenants under control.

What you will learn

  • Agents on every machine tail logs, buffer to disk and back off, so a slow pipeline never breaks the application.
  • A durable, partitioned ingestion log decouples bursty producers from indexing and storage.
  • Parse, enrich and redact once, centrally, before storage: structured fields make search fast and safe.
  • Store logs in compressed, time-partitioned chunks; index labels and maybe terms, and scan the rest in parallel.
  • Queries prune by time and labels first, then fan out to many workers; time range is the most important filter.
  • Tier data hot, warm and cold, and enforce per-team quotas: log volume grows faster than anyone's budget.

In this lesson

  1. The question
  2. Step 1: Clarify the requirements
  3. Step 2: Back-of-the-envelope estimates
  4. Step 3: The log format and the API
  5. Step 4: Collecting logs on every machine
  6. Step 5: Ingestion through a durable log
  7. Step 6: Parsing, enrichment and redaction
  8. Step 7: Storing logs: chunks and indexes
  9. Step 8: The storage layout
  10. Step 9: The query path
  11. Step 10: Tiers and retention
  12. Step 11: Live tail and alerts
  13. Step 12: Many teams, one system
  14. Step 13: One incident, end to end
  15. Step 14: Scaling and failures
  16. Step 15: The follow-up questions
  17. Recap
Practice this question with Max

The question

Welcome to lesson twenty-eight of the InterviewDryRun system design course. Today we design log aggregation and search: collecting the logs of thousands of services into one place, and letting engineers search them in seconds when something goes wrong.

Every service writes logs: requests handled, errors, warnings, debugging lines. On one machine you can read them with a text editor. With thousands of services on tens of thousands of machines, that stops working. The logs for a single failed request may be spread across ten services on ten machines, some of which no longer exist because they were replaced an hour ago. A central log system brings them together. It looks like plumbing, but it is a serious data system: one of the highest-volume pipelines in any company, and the one engineers depend on most during an incident, which is exactly when it is under the most load.

Max asks

“Design collection, storage and search of logs from thousands of services.”

That is how Max, our AI interviewer, asks it. Three verbs: collect, store, search. Treat them as the three parts of your answer. And thousands of services hints at the real challenges: volume, cost, and many teams sharing one system, some of whom will log far too much.

The plan: requirements and numbers, then the log format and the API. Then collection on each machine, ingestion through a durable log, and processing. Then the core: how to store and index logs so search is fast and storage is cheap. Then the query path, tiers and retention, live tail, multi-tenancy, a search walked end to end, failures, and the follow-up questions.

Step 1: Clarify the requirements

Functional requirements
  1. 01
    CollectFrom every service, machine and container
  2. 02
    SearchBy time range, service, level, fields and free text
  3. 03
    Live tailWatch logs as they arrive, with a filter
  4. 04
    AggregateCount errors per service per minute
  5. 05
    RetentionKeep logs for a set time, per team

Start with questions.

Collect logs from every service, whether it runs on a virtual machine or in a container that may live for only a few minutes. Ask whether logs are structured, as JSON with fields, or plain text lines. The answer is usually both, with a push towards structured.

Search them: within a time range, filter by service, environment, log level and fields like the request id, and by free text, such as an error message. Engineers also want live tail, a stream of matching logs as they happen, during a deployment. And simple aggregations, like errors per service per minute, though detailed metrics belong in a metrics system, which we designed in lesson eighteen.

And retention: how long are logs kept? Ask. A common answer is two weeks searchable, and longer, cheaper storage for audit logs, which may need to be kept for a year or more.

Non-functional requirements
  1. 01
    Never block the appLogging must not slow or crash services
  2. 02
    FreshSearchable within seconds
  3. 03
    Fast searchSeconds for the last hour, longer for weeks
  4. 04
    Durable enoughDo not lose logs, especially errors
  5. 05
    Cost-efficientVolume grows faster than budgets

The qualities.

The most important rule: logging must never hurt the application. If the log system is slow or down, services must keep serving. That shapes the agent design.

Logs should be searchable within a few seconds of being written. Searches over the last hour should take a second or two; searches over two weeks can take longer. We should not lose logs, though a log system can accept a slightly lower bar than a payment system: losing a few debug lines in a disaster is acceptable, losing error logs is not.

And cost. Log volume tends to grow faster than traffic, because every new feature adds log lines. In many companies, the log bill is one of the largest infrastructure costs. Saying that cost is a first-class requirement is a strong opening.

Step 2: Back-of-the-envelope estimates

Sizing it
Services3,000on 50,000 machines and containers
Log lines5 million / sat peak, all services
Line sizeabout 500 bytesstructured, with fields
Raw volumeabout 200 TB / day2.5 GB a second at peak
Compressedabout 20 TB / daylogs compress about 10×

Let us size it.

Say three thousand services across fifty thousand machines and containers, producing five million log lines a second at peak. At about five hundred bytes a line, that is two and a half gigabytes a second, and averaged over a day, about two hundred terabytes of raw logs.

Logs compress extremely well, often ten times or more, because they are repetitive: the same messages, the same field names, the same service names over and over. So about twenty terabytes a day stored. Two weeks of searchable logs is then about three hundred terabytes, and a year of archives about seven petabytes.

Two conclusions. First, ingestion is a high-throughput streaming problem: gigabytes a second, which needs partitioning everywhere. Second, the size of any index matters a lot. A full-text index can be as large as the compressed data itself, or larger, doubling the storage bill. That trade-off will be the core of the storage discussion.

And queries are rare compared with writes: perhaps a few hundred searches a minute, from engineers. This is a write-heavy system, where almost all data is written once and never read. Designing for that, cheap writes and cheap storage, with reads that may do more work, is the key insight.

Step 3: The log format and the API

A structured log event
{ "ts": "2026-10-30T14:03:07.412Z",
  "level": "error",
  "service": "checkout", "env": "prod", "region": "south-1",
  "host": "ip-10-2-4-7", "pod": "checkout-7f9c",
  "traceId": "a91f…", "userId": "u_123",
  "msg": "payment authorisation failed",
  "error": "timeout after 2000 ms calling payments" }

First, what a log line looks like when it reaches us.

Encourage structured logs: one JSON object per event, with a timestamp, a level, the service, and fields like the trace id. Structure makes search precise. Searching for trace id a-nine-one-f is an exact field match instead of a fuzzy text search, and it lets engineers jump from a trace to all its logs across services.

Separate two kinds of fields. Labels, like service, environment, region and level, have few distinct values and are used in almost every query. Content fields, like the message, user id or trace id, have many distinct values. This distinction will decide how we index.

Query API
GET /v1/logs?from=-1h&to=now
    &q={service="checkout", env="prod", level="error"} |= "timeout"
    &limit=500                → lines, newest first, + cursor
GET /v1/logs/stats?…&by=service&step=1m   → counts for a chart
WS  /v1/logs/tail?q=…         → stream of matching lines

The query API is a small language: a time range, label filters, and then filters on content, like level is error and service is checkout and the message contains timeout. Results come back newest first, a page at a time, with an option to count matches per minute for a chart. And a live tail endpoint streams new matching lines over a long-lived connection.

Step 4: Collecting logs on every machine

Collection
spillbatchesSERVICEServicewrites to stdout or fileWORKERAgenttail, batch, bufferSTORELocal disk bufferEDGEIngest gatewaysauth, quotasQUEUEIngestion logpartitioned

Collection starts on the machine where the log is written.

Services write logs the simplest possible way: to standard output, or to a local file. They never call the log system directly. An agent running on every machine, or alongside every group of containers, reads those outputs, like following a file as it grows.

The agent adds metadata the service does not know: the host, the container, the region. It batches lines, compresses each batch, and sends it to the ingest gateways. Batching and compression cut network use by about ten times and are essential at this volume.

If the gateways are slow or unreachable, the agent buffers to local disk, up to a limit, and retries with backoff. If the buffer fills, it starts dropping, lowest levels first: debug lines before info, info before errors. And it limits its own CPU and memory. This is how we keep the rule that logging never hurts the application: the service writes to a file and moves on, and everything after that is the agent's problem.

Agents also remember how far they have read in each file, so after a restart they continue where they stopped, rather than re-sending or skipping lines. Containers that exit are a special case: the agent must finish reading a container's output before it is deleted, which orchestration systems allow with a short grace period.

Step 5: Ingestion through a durable log

Why a durable log in the middle
  1. 01
    Absorbs burstsAn incident triples log volume in seconds
  2. 02
    DecouplesIndexers can slow down or restart freely
  3. 03
    ReplayRe-index after a bug or a new parser
  4. 04
    Several consumersStorage, live tail, alerts, archive

The ingest gateways authenticate agents, check each team's quota, and append batches to a durable, partitioned ingestion log.

Why put a log in the middle of a log system? First, bursts. When something breaks, every service starts logging errors at once, and volume can triple in seconds, exactly when people need search the most. The log absorbs the burst, and the indexers work through it at their own pace.

Second, decoupling: indexers can be upgraded, restarted, or fall behind without losing anything, because the log keeps a few days of data. Third, replay: if a parsing bug corrupted an hour of logs, fix it and reprocess from the log.

Fourth, several consumers read the same stream: the indexers that build searchable storage, the live tail service, log-based alerts, and an archiver that copies raw compressed batches to cheap object storage for long-term retention.

Partition the ingestion log by tenant and service, with big services spread across many partitions. At two and a half gigabytes a second, with each partition handling, say, twenty megabytes a second, we need over a hundred partitions, so plan for several hundred. Replicate each partition across zones and acknowledge the agent only after the batch is replicated: once acknowledged, the agent can forget it.

Step 6: Parsing, enrichment and redaction

Processing each event
  1. 01
    ParsePlain text to fields with per-service patterns
  2. 02
    NormaliseTimestamps, levels, field names
  3. 03
    EnrichTeam, owner, deployment version
  4. 04
    RedactRemove tokens, card numbers, personal data
  5. 05
    Route and sampleDebug to short retention; drop known noise

Before storing, a processing stage cleans every event, once, centrally.

Parse unstructured lines into fields with patterns each team defines for its service, so a plain text access log becomes method, path, status and latency fields. Normalise timestamps to one format and time zone, and levels to one vocabulary, because warn, warning and W should all match one filter.

Enrich with information from elsewhere: which team owns this service, which deployment version produced the line. These make queries like errors from the new version possible.

Redact. Services will accidentally log passwords, access tokens, card numbers and personal details, no matter how many times they are told not to. Scrub known patterns centrally, before anything is stored, because once a secret is in the index and the archives, removing it everywhere is very hard. Interviewers like candidates who raise privacy without being asked.

Finally, route and sample. Debug logs can go to a short retention tier. Known noisy lines, like a health check logged every second by every instance, can be sampled down to one in a hundred, with the sample rate recorded so counts can be scaled back up. Cutting volume here is the cheapest place to cut cost.

Step 7: Storing logs: chunks and indexes

Two ways to make logs searchable
Full-text indexLabel index + scan
What is indexedevery word in every lineonly labels: service, env, level
Index sizeoften as big as the datatiny
Ingest costhigh: tokenise and index everythinglow: compress and append
Rare-term searchvery fastscan matching chunks in parallel
Cost at 20 TB/dayhighlow

Now the core design decision: how to store logs so search is fast and storage is cheap. There are two main schools of thought.

The first is a full-text inverted index, the same structure as a search engine: for every word, a list of the log lines that contain it. Searching for a rare word is extremely fast. But every word of every line must be tokenised and indexed at ingest, which costs a lot of CPU, and the index is often as large as the data itself.

The second indexes only the labels. Logs are grouped into streams, one per unique combination of labels, such as checkout, prod, south-one, error. Each stream's lines are appended in time order into compressed chunks of a few megabytes. The index only says: for this stream and this time range, here are the chunks. Searching for a word means finding the chunks for the matching streams and time range, then decompressing and scanning them, in parallel across many workers.

The trade-off is clear. Full-text indexing makes rare searches fast and storage expensive. Label indexing makes storage cheap and pushes work to query time, which is fine when queries are rare and well-filtered by time and labels, which they nearly always are. Scanning is also fast in practice: decompressing and scanning a gigabyte takes well under a second per core, and a query can use hundreds of cores.

My recommendation, stated with the reasoning: use label indexing with chunk scans as the default, because it is several times cheaper at this volume. Add small helper structures per chunk, such as a compact filter of the trace ids and request ids it contains, so the most common needle-in-a-haystack searches can skip almost every chunk. And offer full-text indexing as an option for the few datasets, like security audit logs, where fast arbitrary search is worth paying for.

Step 8: The storage layout

Writing chunks
flushregisterrecentQUEUEIngestion logWORKERIngestersbuild chunks in memorySTOREObject storagecompressed chunksSTOREChunk indexstream + time → chunksSERVICEQueriers

Let us make the layout concrete.

Ingesters consume the ingestion log. Each one holds open chunks in memory, one per active stream, and appends lines as they arrive, compressing as it goes. Their memory also serves the most recent few minutes of logs, so a search for the last minute is fresh even before chunks are written.

When a chunk reaches a few megabytes, or a few minutes old, the ingester flushes it to object storage, which is cheap, durable and effectively unlimited. Object storage, from the previous lesson, is the right home for immutable chunks of compressed logs.

It then registers the chunk in the chunk index: this stream, from this time to this time, is in this chunk, with its size and helper filters. The index is small and kept in a fast key-value store, partitioned by tenant and day.

Queriers answer searches by reading the index, fetching chunks from object storage, and asking ingesters for the newest data still in memory. Because the ingesters' memory holds unflushed data, it must not be lost on a crash: either replicate each stream to two or three ingesters, or keep the ingestion log's offset with each flush, so a replacement ingester can rebuild its open chunks by replaying from the log.

Small chunks are bad for object storage and for queries, so a background compactor merges small chunks from quiet streams into bigger ones, and rewrites the index. This is the same small-files problem we met in object storage, seen from the other side.

Step 9: The query path

Planning a query
q = {service="checkout", env="prod"} |= "timeout"   last 6 h

1  split time range into 15-minute slices      → 24 slices
2  for each slice: index → streams matching labels → chunks
3  skip chunks whose filters can't match
4  fan out: 400 chunks across 100 querier workers
5  each: decompress, scan for 'timeout', return newest first
6  merge, stop early once 500 lines are found

Now a search, in detail. The single most important filter is time. Every design decision should make time-range pruning cheap.

A query frontend receives the search and splits it by time, say into fifteen-minute slices. For each slice it asks the index which streams match the labels, and which chunks hold them. Chunks whose helper filters rule out a match are skipped.

The remaining chunks are spread across a pool of querier workers. Each one fetches its chunks, decompresses them, scans them for the search term, and returns matches. The frontend merges results by time. Because the default is newest first with a limit, it can start with the most recent slices and stop as soon as it has five hundred lines, which makes typical searches fast even over long ranges.

Cache aggressively. Engineers in an incident run the same search repeatedly, refreshing every few seconds. Results for completed time slices never change, so cache them by query and slice, and only recompute the most recent slice. This turns the tenth refresh of a six-hour search into a tiny query.

And protect the system from expensive queries. A search with no label filter over thirty days would scan every chunk the company has. Require at least one label filter, limit the bytes a single query may scan, and show the user how much data their query will touch. A query that would scan two hundred terabytes should be refused with a helpful suggestion, not allowed to slow down everyone else's incident.

Step 10: Tiers and retention

Storage tiers
TierAgeWhereSearch speed
Hotlast few hoursingester memory + local SSD cachesub-second
Warmup to 14 daysobject storage + chunk indexseconds
Coldup to 1 year+archive storage class, raw batchesminutes to hours
Deletedafter policylifecycle rules—

Not all logs deserve the same storage.

Hot data, the last few hours, is where most searches go, so keep it in ingester memory and in a cache on the queriers' fast local disks. Warm data, up to two weeks, lives in object storage and is fetched on demand.

Cold data, kept for compliance, sits in the cheapest archive storage class as raw compressed batches. It is not indexed for interactive search. When someone needs it, a job restores the relevant days and re-indexes them into a temporary search space, which takes minutes or hours, and that is acceptable for audits.

Retention is set per team and per log type: debug logs for three days, application logs for two weeks, security audit logs for a year or more. Deletion is cheap with this layout, because chunks are grouped by tenant and day: dropping old data is deleting whole objects and index partitions, never rewriting files. Compare that with deleting individual lines from a large search index, which is slow and expensive.

Step 11: Live tail and alerts

Reading the live stream
  1. 01
    Live tailFilter applied to the stream; push matches to the browser
  2. 02
    Rate limit tailsDrop and summarise if too many lines match
  3. 03
    Log alertsCount matches per minute; alert on thresholds
  4. 04
    Prefer metricsTurn frequent log alerts into real metrics

Two features read the stream as it flows, rather than stored data.

Live tail lets an engineer watch logs during a deployment. The tail service subscribes to the relevant partitions of the ingestion log, applies the user's filter to every event, and pushes matches over a long-lived connection to the browser. Sampling helps: if a filter matches ten thousand lines a second, no human can read that, so send a sample and a count of what was skipped.

Log-based alerts work similarly: a streaming job counts events matching a rule, for example level error and service checkout, per minute, and fires an alert when the count crosses a threshold. They are useful for rare events that have no metric yet.

But encourage teams to turn frequent log alerts into proper metrics. Counting log lines is an expensive way to measure something a counter in the code could measure for free. A good log system nudges teams towards better observability rather than becoming the place everything is measured.

Step 12: Many teams, one system

Multi-tenancy
  1. 01
    QuotasPer-team ingest rate and daily volume
  2. 02
    Over quotaSample or drop debug first; tell the team
  3. 03
    Fair queriesPer-team query concurrency and scan limits
  4. 04
    Show the costEach team sees its volume and bill

Three thousand services means hundreds of teams sharing one system, and some will log far too much.

Every team has an ingest quota: a rate and a daily volume. A bug that logs the same error a million times a second must not fill the ingestion log and delay everyone else's logs. When a team exceeds its quota, the gateways sample or drop its lowest-level logs first, keep its errors, and notify the team.

Queries are limited per team too: how many can run at once, and how much data each may scan, so one team's huge search during a busy hour does not starve another team's incident investigation. And partition the ingestion log and ingesters so one tenant's burst lands on its own partitions.

The most effective control is transparency: show each team its log volume, its share of the bill, and its noisiest log lines. Teams cut their volume dramatically once they see that a single debug line costs thousands a month. Cost controls that people can see work better than limits that surprise them.

Step 13: One incident, end to end

From error to answer
WhenWhat happens
14:03:07.412checkout logs 'payment authorisation failed' to stdout
14:03:07.9agent batches 800 lines, compresses, sends
14:03:08.0gateway checks quota; batch appended, replicated
14:03:08.3processor redacts, enriches; ingester appends to chunk
14:03:09engineer's live tail shows the line
14:20search 'timeout' over 6 h: 380 chunks, 1.4 s

Let us follow one log line from an error to an engineer's screen.

At three minutes past two, the checkout service logs an error: payment authorisation failed, timeout calling payments. It writes the line to standard output and moves on. Half a second later the agent sends it in a compressed batch of eight hundred lines.

The gateway checks that the checkout team is within its quota, appends the batch to the ingestion log, and acknowledges once it is replicated. The processor parses it, removes a card number another line accidentally included, adds the owning team and deployment version, and the ingester appends it to the open chunk for the stream checkout, prod, south-one, error. Within two seconds of being written, it is searchable, and the on-call engineer watching live tail sees it.

Seventeen minutes later, the engineer searches checkout errors containing timeout over the last six hours. The frontend splits the range into twenty-four slices, the index returns three hundred and eighty chunks, filters skip a few, and a hundred workers scan the rest in parallel. The first page arrives in under a second and a half, starting with the newest. The engineer clicks a trace id, and a second search, using the trace id filters, shows that request's logs from all ten services it touched.

Step 14: Scaling and failures

Scale and failure
  1. 01
    Gateways downAgents buffer on disk and retry
  2. 02
    Indexers behindIngestion log absorbs; freshness drops, nothing lost
  3. 03
    Ingester crashReplay open chunks from the log, or use replicas
  4. 04
    Object storage slowHot cache keeps recent searches working
  5. 05
    Log system downApplications unaffected; that was rule one

Scaling and what breaks.

Every stage scales horizontally: more gateways, more partitions, more ingesters, more queriers. Ingest and query scale independently, which matters because ingest is constant and queries are spiky during incidents.

When gateways are down, agents buffer. When indexers fall behind, the ingestion log holds the backlog, and search becomes less fresh but nothing is lost. Monitor the lag between a line being written and being searchable, and alert on it, because a log system that is twenty minutes behind is useless in an incident.

A crashed ingester's open chunks are rebuilt by replaying from its last flushed offset. If object storage is slow, the hot cache keeps the most recent searches working. And if the whole log system is down, applications keep running, because they only ever wrote to a local file. That last property is the most important one, and it is worth ending this step by saying it again.

One more: the log system must not depend on itself. If it is failing, its own logs and metrics must go somewhere else, a small separate system, or engineers will be debugging their debugging tool in the dark.

Step 15: The follow-up questions

Max asks

“How would you find all logs for one request across ten services?”

Every service propagates a trace id and includes it in every log line, which the agent or the logging library adds automatically. Each chunk carries a compact filter of the trace ids it contains, so a trace id search over a time window skips nearly every chunk and scans only the few that might match. The result is merged by time across services. Linking from a trace view straight to its logs makes this one click.

Max asks

“A team logs a password by mistake. What do you do?”

Add the pattern to the central redaction rules immediately, so new lines are scrubbed. For data already stored, find the affected chunks using the time range and stream, rewrite them without the secret, and update the index, then delete the originals, including archived copies. Because chunks are immutable and grouped by stream and time, the rewrite is targeted. And rotate the password, because it must be treated as leaked anyway.

Max asks

“Why not put all logs in a relational database?”

Two hundred terabytes a day of append-only text is the opposite of what a relational database is built for. Row-by-row indexes and transactional writes would cost far more than compressed chunks in object storage, and we need none of the transactions. Logs are written once, never updated, and searched by time, which suits an append-only, time-partitioned design. A database is the right home for the small chunk index, not the logs.

Max asks

“How would you cut the log bill in half?”

Measure first: show each team its volume and top log lines, which often finds a few lines producing a large share. Then sample noisy, low-value logs like health checks, move debug logs to a short retention tier, shorten default retention where it is not needed, and convert frequent log-based alerts into metrics. On the storage side, use label indexing rather than full-text for most data, and better compression. Each step is modest; together they often halve the cost.

Recap

Your 45 minutes
  1. 01
    0 to 5: requirementsCollect, store, search; never block the app
  2. 02
    5 to 10: estimates5 million lines/s; 200 TB raw, 20 TB stored a day
  3. 03
    10 to 20: pipelineAgents with disk buffers, ingestion log, processing
  4. 04
    20 to 35: storage and searchChunks + label index; time pruning; fan-out
  5. 05
    35 to 45: operationsTiers, retention, quotas, failures

On the clock: five minutes on requirements, with the rule that logging never hurts the application, and cost as a first-class requirement. Five minutes of numbers: two hundred terabytes a day raw, twenty compressed, few queries.

Ten minutes on the pipeline: agents that buffer and back off, a durable ingestion log, and processing with redaction.

Fifteen minutes on storage and search: compressed chunks in object storage, label indexes versus full-text, and queries that prune by time and labels and then fan out. And ten minutes on tiers, retention, quotas and failures. If you explain the indexing trade-off with numbers, you will stand out.

Data pipeline questions have many moving parts, and practicing out loud is how you learn to explain them in the right order. You can practice this exact question with Max, our AI interviewer, at interview dry run dot com. It is free to start, and you get a scored report with what to fix. The written lesson, with every diagram, is on the site too. See you in lesson twenty-nine.

Now say it out loud

Watching an answer is not the same as giving one. Max asks this exact question, pushes back when an answer is vague and keeps time, then scores you per skill.

Practice with Max

Free: a 5-minute voice round and unlimited typed drills, with scored feedback. No card, and your camera is never recorded.