Design a Centralized Log Aggregation Platform
System DesignModel answerLast updated
Design a high-throughput internal logging platform that ingests, indexes, and retains logs from thousands of services with near-real-time search and strict tenant isolation.
The Problem
Your organization runs thousands of services across virtual machines, containers, and serverless functions. Right now every team manages logs differently — some stream to local files, some push to ad-hoc dashboards, and on-call engineers spend the first ten minutes of every incident just finding the right logs. You've been asked to design an internal, self-hosted log aggregation platform that every team can ship logs to and query from.
Think of it as the platform behind tools like the ELK stack, Splunk, or Datadog Logs — but you own the infrastructure.
What the system needs to do
- Ingest log events from a wide variety of sources: different languages, different runtimes, different environments. Agents on hosts, sidecars in containers, and SDK-level emitters in serverless functions all need to get data in.
- Search and filter logs interactively: by service name, host, severity, time range, and free-text message content. Engineers debugging an incident need answers in seconds, not minutes.
- Enforce retention tiers: for example, logs are fully searchable for 7 days, archived but retrievable for 90 days, then permanently deleted. Teams should be able to configure their own retention windows within platform limits.
- Absorb bursty write load: during incidents, retry storms, or deployment failures, write volume can spike dramatically. The system must not drop data under these conditions.
- Isolate tenants: different teams share the same platform, but one team's spike must not degrade another team's query experience or ingest reliability. Tenant data must be logically (and where required, physically) separated.
Constraints and scale assumptions
Nail down your numbers early — they drive every architecture decision.
- Around 10,000 hosts, each emitting roughly 100 events/second at baseline. That's on the order of 1 million events/second steady-state, spiking to 5–10 million events/second during major incidents.
- Average event size after enrichment: ~1 KB. That's roughly 1 GB/s ingest, or ~86 TB/day of raw log data.
- Ingest-to-searchable latency: a few seconds end-to-end is acceptable.
- Query latency: sub-second to a few seconds for a filtered query over the hot (fully searchable) window.
- Logs are append-only and immutable. There are no per-record updates or deletes — only bulk expiry when a retention window closes.
- At-least-once delivery is acceptable. Small windows of duplication and minor out-of-order events are tolerable; data loss is not.
What you're expected to cover
Walk through the full design. A strong answer will address:
- Requirements — Functional and non-functional, with explicit non-goals (e.g., metrics, traces, alerting engine).
- Scale sizing — Back-of-envelope math that turns the numbers above into concrete storage, throughput, and partitioning requirements.
- Architecture — End-to-end data path from agent to queryable store. Name each stage, describe its role, and justify why it belongs there.
- Data model and indexing — What a canonical log event looks like, how you index it for fast filtered and full-text search, and how you prevent indexing pathologies like cardinality explosions.
- Partitioning and scaling — How you shard the ingestion pipeline and the storage layer, and how you handle hot-partition and query fan-out problems.
- Reliability and delivery semantics — How the system behaves when agents crash, brokers lose a node, or the search cluster is slow. Where exactly do you make durability guarantees?
- Multi-tenancy and security — How tenant isolation is enforced, how quotas and rate limits work, and how PII is handled.
- Cost and operational trade-offs — Storage tiering strategy, the cost/latency/durability knobs you'd expose, and what you'd instrument to know the system is healthy.
Clarifying questions you should raise
Before diving into architecture, a strong candidate asks:
- What is the burst multiplier we need to absorb without dropping events?
- Is full-text search on message bodies a hard requirement, or are structured field filters sufficient? (This changes the hot-store technology choice significantly.)
- What are the compliance requirements — PII redaction, data residency, immutability for audit logs?
- How many tenants, and how skewed is their volume distribution? A few high-volume teams or hundreds of roughly equal ones?
- Is exactly-once delivery required anywhere, or is at-least-once with idempotent reads acceptable throughout?
- Is the budget posture cost-optimized (aggressive tiering, sampling) or latency-optimized (long hot window)?
Hints
Hint 1
Start with the durable buffer between ingest and storage — it's the single component that decouples write spikes from the search cluster and is the foundation of your reliability story. Justify your choice of partition key and explain its ordering trade-off.
Hint 2
Think carefully about what 86 TB/day means for your hot store. A 7-day hot window is ~600 TB. Time-bucketed indices let you enforce retention by dropping an entire index rather than running deletes — that's both operationally simpler and dramatically cheaper.
Hint 3
Multi-tenancy is not just a query filter. You need server-side tenant resolution (agents cannot self-declare their own tenant), per-tenant write quotas enforced before the broker, and a mandatory tenant filter injected at query time. Trace through what happens when a tenant exceeds their quota.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Requirements
Functional: ingest from heterogeneous sources; structured field search plus free-text; configurable retention tiers; tenant-scoped access and quotas.
Non-functional: ~1M events/sec baseline, 5–10M peak; ~1 GB/s raw ingest; ingest-to-searchable in a few seconds; interactive query latency (sub-second to low seconds) over the hot window; at-least-once delivery; no meaningful data loss.
Non-goals (stated explicitly): metrics pipeline, distributed tracing, alerting engine, log-based anomaly detection. These are adjacent systems that may consume data from this platform but are out of scope here.
Back-of-envelope sizing
| Dimension | Number |
|---|---|
| Baseline ingest | 1M events/sec, ~1 GB/s |
| Peak ingest | 5–10M events/sec, ~5–10 GB/s |
| Daily raw volume | ~86 TB/day |
| 7-day hot window | ~600 TB |
| 90-day archive | ~7.7 PB (before compression; expect 5–10x compression on text → ~1–1.5 PB) |
These numbers immediately tell you: (a) you need a distributed durable buffer to absorb bursts, (b) a single-node search cluster is out of the question, and (c) tiered storage is mandatory on cost grounds alone.
End-to-end architecture
Emitters → Agents → Collectors → [Durable Buffer] → Stream Processors → Hot Store → Archive
↓
Query API → UI / SDK
Agents (Fluent Bit, Vector, or a thin SDK): run on every host or as a sidecar. They tail files, receive over a local socket, buffer to disk during network interruptions, and forward with at-least-once semantics. Disk buffering on the agent is the first durability guarantee — if the network is down for minutes, events queue locally rather than being dropped.
Stateless collectors: horizontally scaled, autoscaling services that receive agent output over TLS, perform server-side tenant resolution (more on this below), do lightweight validation, and publish to the durable buffer. Keeping these stateless lets you scale them independently of both agents and storage.
Durable buffer (Kafka or a Kafka-compatible system like Redpanda): the architectural keystone. It decouples write spikes from the search cluster, provides replayability for reprocessing, and is the point where durability is formally guaranteed (replication factor ≥ 3, acks=all). Partition key should be tenant_id — this gives per-tenant ordering guarantees and makes quota enforcement natural. The trade-off: a single very noisy tenant can create a hot partition. Mitigate with sub-partitioning by service_id for known-whale tenants, or by hashing on tenant_id + shard_suffix for the top N by volume.
Stream processors (Flink, Spark Structured Streaming, or simpler Kafka Streams): enrich events (geo-IP, k8s metadata injection), apply PII redaction rules, parse unstructured messages into structured fields, and route to the hot store. These are stateless or near-stateless and scale horizontally with the buffer partitions.
Hot store (Elasticsearch or OpenSearch): receives processed events, indexes them for field-filtered and full-text search. Time-bucketed daily indices (logs-{tenant}-{YYYY.MM.DD}) mean retention enforcement is a single index delete call — no expensive per-document deletes, no tombstoning overhead.
Archive tier (object storage: S3, GCS): stream processors also write Parquet-encoded, Snappy-compressed files to object storage in parallel with the hot store write. After the hot window closes, queries against the archive tier go through a query engine like Athena, Trino, or BigQuery. Read latency is higher (seconds to tens of seconds) but cost is roughly 10–20x lower per GB than hot-store storage.
Query API: a thin routing layer that determines whether the requested time range falls in the hot window, the archive window, or spans both, and fans the query out accordingly. Enforces mandatory tenant filtering (see below) before the query reaches either backend.
Data model and indexing
A canonical event:
{
"event_id": "uuid-v4",
"tenant_id": "platform-eng",
"service": "checkout-api",
"host": "ip-10-0-1-42",
"env": "production",
"severity": "ERROR",
"timestamp": "2025-07-10T14:32:01.123Z",
"message": "timeout waiting for payment gateway after 30s",
"trace_id": "abc123",
"fields": { "order_id": "ord_9988", "latency_ms": 30012 }
}
Index strategy: tenant_id, service, host, severity, and timestamp are keyword fields — exact-match, not analyzed. message is analyzed text with a standard tokenizer. fields.* are dynamically mapped but controlled via an allowlist and a maximum field-count limit per index. Without this, a tenant can trivially cause a mapping explosion by emitting thousands of unique field names, which degrades all tenants on the same cluster.
Shard sizing: target ~30–50 GB per shard for Elasticsearch performance. A daily index for a large tenant at, say, 5 TB/day needs ~100–150 primary shards. Spread these across nodes and you get ~10–15 GB/shard after compression — comfortable.
Reliability and failure scenarios
- Agent crash: disk buffer replays on restart; duplicates handled by
event_id-based idempotent writes at the hot store. - Collector crash: agents retry with backoff; stateless collectors are replaced by autoscaling in seconds.
- Broker node loss: Kafka replication absorbs it with no data loss as long as replication factor ≥ 3 and
min.insync.replicas = 2. - Hot store overloaded: consumers slow down; the buffer absorbs the backpressure. Lag on the consumer group is the key leading indicator — alert when lag exceeds, say, 30 seconds of ingest.
- Poison message: malformed event causes processor crash. Use a dead-letter topic; forward to an alert and human review. Never block the main pipeline.
- AZ failure: Kafka and Elasticsearch clusters should span ≥ 3 AZs. Replica placement rules (Kafka rack awareness, ES zone awareness) prevent quorum loss on single-AZ failure.
Multi-tenancy and security
Tenant resolution is server-side, always. Agents authenticate with a short-lived credential (mTLS or a token scoped to a tenant). Collectors resolve tenant_id from the credential, not from anything the agent sends in the payload. This prevents tenant spoofing.
Write quotas are enforced at the collector tier before events reach the broker. A tenant exceeding their quota gets a 429 response; their events are dropped or sampled at the collector rather than polluting shared broker partitions. Per-tenant quota metrics feed an autoscaling decision: if a tenant legitimately needs more headroom, ops can raise their quota.
Query isolation: the query API injects a mandatory tenant_id filter on every request. No query reaches the search backend without it. Row-level security in Elasticsearch provides a second enforcement layer.
PII redaction runs in the stream processor tier before anything touches durable storage. Regex and ML-based classifiers scrub credit card numbers, SSNs, and email addresses. Redaction rules are configurable per tenant.
Cost and key trade-offs
| Decision | Trade-off |
|---|---|
Kafka partition key = tenant_id | Simple quota enforcement; risk of hot partitions for whale tenants |
Full-text index on message | Enables grep-style search; roughly doubles index size vs. field-only |
| Daily time-bucketed indices | O(1) retention enforcement; slightly more shard overhead |
| Parallel write to object storage | Increases write amplification ~2x; makes archive free of hot-store dependency |
At-least-once + event_id dedup | Simpler and cheaper than exactly-once; small duplicate window is acceptable |
Self-observability: instrument consumer group lag (leading indicator of pipeline health), ingest bytes/sec per tenant (quota monitoring), hot-store disk utilization, and query latency p99 per tenant. These four metrics cover the most common failure modes.
The hardest ongoing operational challenge is the field cardinality problem — tenants naturally want to log everything, and without active allowlisting, mapping explosion will silently degrade cluster performance for everyone. This is a social and tooling problem as much as a technical one: provide good SDKs, enforce schema guidelines, and alert when a tenant's field count approaches limits.