Build a Company-Wide Log Aggregation and Search Platform
System DesignModel answerLast updated
Design a scalable platform that collects logs from many services, stores them durably with retention, supports filtered search, survives traffic spikes, and isolates tenants.
Your organization runs a large fleet of microservices and scheduled batch jobs spread across many hosts and containers. Each of them produces log output, and engineers need one place to collect, keep, and search it.
Design a centralized log aggregation and search platform that meets these needs:
- Collection: accept log events from a very large number of producers.
- Durability and retention: keep acknowledged logs safely, and expire them according to a retention policy.
- Search: let users narrow results by time window, service, host, severity level, and request or trace ID.
- Resilience: cope with sudden traffic spikes and with partial failures of internal components.
- Isolation: provide basic authorization and keep tenants (for example teams or environments) separated from one another.
In your answer, cover:
- Assumptions and a rough capacity estimate
- The main components and how data flows from producer to query result
- The event data model and your indexing approach
- How the system scales
- Reliability, failure handling, and security considerations
A diagram is not required, but the path a log line takes through the system should be unambiguous.
Hints
Hint 1
Start by scoping: write rates, average event size, hot versus archived retention, freshness target, and expected query latency. This is a write-heavy system with comparatively rare reads, which should shape your choices.
Hint 2
Put a durable buffer (such as a partitioned commit log) between the ingestion tier and the indexing tier, so spikes and downstream outages become consumer lag instead of lost data.
Hint 3
Avoid indexing every token. Prune by tenant and time first, index only low-cardinality labels, give trace IDs a dedicated lookup structure such as bloom filters, and scan for free text.
Hint 4
Decide where tenant identity comes from (the authenticated producer, not the payload) and how quotas stop one noisy tenant from harming others.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Requirements and sizing
Functional
- Producers send structured or semi-structured events.
- Users filter by time range, service, host, level, and trace/request ID, and can search free text.
- Retention is per tenant (for example, production 30 days searchable plus a year archived; dev 7 days).
- Users see only the tenants they are authorized for.
Non-functional
- Ingestion is highly available, and applications never block on logging.
- Acknowledged data is durable. Delivery is at-least-once, so occasional duplicates are tolerable.
- New events are searchable within roughly 10-30 seconds.
- Recent queries return in a few seconds; archived queries may be slower.
Back-of-envelope (state assumptions aloud)
- ~50k hosts, ~2k services, ~1M events/s average, bursts of 3-5M/s.
- ~500 B per event gives ~0.5 GB/s, or ~43 TB/day raw.
- 5-10x compression gives ~5-8 TB/day stored.
- 7 days hot is ~50 TB; with 2-3x replication, ~150 TB of SSD.
- Older data lives in object storage.
2. Interfaces
- Ingest: a batched, compressed call (gRPC or HTTP) carrying events with timestamp, service, host, env, level, trace/span ID, message, and a bounded attribute map. It returns success only after the event is durably in the queue, or a "slow down, retry after" response when over quota.
- Search: takes a tenant, time range, filters, optional text expression, limit, and a cursor; returns events, the next cursor, and stats.
- Trace lookup: returns all events for a trace ID within a time window.
- Briefly mention live tail and admin APIs for retention and access.
3. Data model and indexing
Each event holds: tenant_id (derived from the authenticated producer, never trusted from the payload), event time plus ingest time, low-cardinality fields (service, host, env, level), high-cardinality IDs (trace_id, request_id), the message, and bounded attributes. Include a per-event ID (for example a hash of host, timestamp, and sequence) for deduplication.
The key decision is how much to index. A full inverted index over every token is flexible but typically adds 1-2x the raw size and heavy CPU. For a write-heavy workload, a hybrid is better:
- Partition by tenant and time, for example tenant/env/date/hour/service. Every query carries a time range, so this prunes most data.
- Small label index over low-cardinality fields mapping label sets to chunk IDs.
- Columnar compressed chunks sorted by (service, timestamp), with min/max time stats per chunk.
- Trace IDs: per-chunk bloom filters or a compact secondary index from trace ID to chunks. Trace lookup is the most frequent debugging query, so it deserves a dedicated path.
- Free text: scan the already-pruned chunks in parallel. Optionally maintain a token index only for the hot tier or for tenants who pay for it.
Trade-off: cheaper writes and storage in exchange for slower arbitrary text search over wide time ranges.
4. Architecture and data flow
- Host agent (a sidecar or per-node daemon): tails stdout/files, parses lines, adds host/pod/service/env metadata, batches and compresses, and buffers to bounded local disk (a few GB) to ride out outages. It can sample and rate-limit locally.
- Ingestion gateways: stateless, behind a load balancer. They authenticate (mTLS or token), map the identity to a tenant, validate the schema, enforce per-tenant quotas, write to the queue, then acknowledge.
- Durable queue (Kafka-like), partitioned by tenant and service with 1-3 days of retention. It acts as a shock absorber: spikes and indexer failures show up as lag.
- Indexer workers: consume, group by tenant/partition, buffer ~30 s or ~100 MB, build columnar chunks, bloom filters, and label entries, write chunks to hot storage, update the metadata store, and only then commit offsets.
- Storage tiers: hot SSD (about 0-7 days, replicated); warm/cold object storage (up to a year) with small chunks compacted into larger files; a scalable key-value or SQL metadata catalog.
- Query service: authenticates the user, resolves permitted tenants, plans (time range, then partitions, then label filter, then bloom pruning), fans out scans to queriers, merges by timestamp, paginates with cursors, and caches recent results.
- Retention and compaction jobs: merge small chunks, move data between tiers, and drop expired partitions. Time partitioning makes deletion a cheap directory drop.
- UI and alerting are built on the query API.
5. Scaling
- Gateways scale horizontally, since they are stateless.
- Kafka scales with partition count; choose partition keys that avoid hot partitions for very large tenants (add a salt or hash suffix).
- Indexers autoscale on consumer lag.
- Queriers scale with scan parallelism; separate pools for interactive and heavy/archive queries so big scans do not starve interactive users.
- Metadata store is sharded by tenant and time.
6. Reliability
- Bursts: agent disk buffer with a drop policy (shed DEBUG before ERROR); gateway token-bucket quotas returning retry-after responses so a noisy tenant cannot starve others; the queue absorbs multi-hour indexer outages.
- Durability: acknowledge only after the queue confirms replication (all in-sync replicas, replication factor 3). Commit offsets after chunks are durable, giving at-least-once delivery.
- Duplicates: dedupe by event ID at query time or during compaction. Make chunk writes idempotent by naming chunks deterministically from partition and offset range.
- Failure domains: spread across availability zones; replicate object storage across regions for disaster recovery.
- Self-monitoring: track consumer lag, drop counts, and ingest-to-searchable latency, and ideally run the monitoring path independently of the logging pipeline itself.
- Agents use bounded memory and async I/O so logging can never take down the application.
7. Multi-tenancy and security
- Tenant comes from the authenticated identity at ingest, never the payload.
- Separate storage prefixes per tenant; optionally per-tenant encryption keys.
- RBAC enforced in the query service, with the tenant filter injected server-side so users cannot bypass it.
- Per-tenant quotas for ingest rate, query concurrency, and scan volume.
- Audit access, and scrub or mask sensitive fields (PII, secrets) at the agent or gateway.
- TLS in transit and encryption at rest.
Common mistakes
- Indexing every token and underestimating the storage and CPU bill.
- Letting producers block on a slow or down logging backend.
- Trusting a tenant field supplied by the client.
- Skipping a buffer between ingest and indexing, so any downstream hiccup drops data.
- Ignoring high-cardinality fields such as trace ID when designing the index.
- Forgetting to monitor the logging pipeline itself.
Likely follow-ups
- How to support live tailing (a separate streaming path from the queue).
- How to make full-text search faster for a subset of tenants (hot-tier inverted index).
- How to handle clock skew and late-arriving events (partition by event time with a bounded lateness window, and keep ingest time too).
- Cost controls: sampling, tiered retention, and per-tenant budgets.