Collect millions of data points a second, store them cheaply, query them fast and alert on them.
“Design a metrics and monitoring system.”
It is short on purpose. Your first job is to make it specific.
| What they check | Why it matters |
|---|---|
| Pinning down the problem | “Monitoring” can mean collecting numbers, storing them, drawing dashboards or paging people. A strong candidate asks which, how long data is kept, and how fast a query and an alert must be. |
| Sizing the write path | Five million samples a second is the number that shapes everything. The interviewer wants you to see that this is a write-heavy, append-only workload, and to price storage per sample. |
| Understanding cardinality | The thing that really kills metrics systems is not volume, it is the number of distinct series. Naming this early, and showing how you cap it, is the senior signal. |
| Correct maths on stored data | You cannot average percentiles, and a rollup cannot give back raw samples. The interviewer checks that you know what downsampling loses. |
| Monitoring the monitor | The system must keep working during the outage it is meant to detect. Alert reliability, missing data and a watcher for the watcher are where real systems fail. |
A metrics system accepts a huge stream of tiny numbers (series identified by a name and labels, with a value every few seconds), stores them compactly in a time-series database, answers dashboard queries over time ranges, and runs alert rules that page a human. It is a write-heavy, append-only, read-by-time-range workload.
| Step | Minutes | What to get done |
|---|---|---|
| 1. Clarify | 4 | What is measured, push or pull, retention, query and alert latency, and what must survive an outage. |
| 2. Estimate | 4 | Series, samples per second, bytes per sample, storage per tier, and what cardinality does. |
| 3. API and data | 4 | Write and query calls, series identity, the label index and the compressed chunks. |
| 4. High-level design | 7 | Agents, gateways, queue, ingesters, long-term blocks, query layer, alert evaluator. |
| 5. Deep dives | 16 | Ingestion, storage and downsampling, cardinality, queries and percentiles, then alerting. |
| 6. Scale and failures | 7 | A label explosion, a dead ingester, a partition, late data, and watching the watcher. |
| 7. Wrap up | 3 | Recap, the trade-offs, and what you would build next. |
| Ask | Why you ask it | Typical answer | How it changes the design |
|---|---|---|---|
| What do we collect: infrastructure only, or application metrics with custom labels too? | Custom labels are where cardinality comes from. Infrastructure metrics are stable and predictable. | Both. Hosts and containers, plus application counters, gauges and histograms with labels. | We need per-tenant series limits and a way to drop labels, not just a big disk. |
| Push or pull? Do agents send data, or does the system fetch it? | It decides who controls the rate, how health checking works, and how it crosses firewalls. | Agents on every host collect locally. Short-lived jobs must push. | Pull for long-lived services (the server controls the rate and sees a dead target), plus a push gateway for batch jobs. |
| How many hosts, metrics and distinct series? How often do we sample? | Series count times sampling rate is the write rate. Series count alone sizes the index and memory. | 500,000 hosts, about 100 metrics each, a sample every 10 seconds. | 50M series and 5M samples a second. We shard writers by series and plan memory per series. |
| How long do we keep data, and at what resolution? | Keeping raw data forever is far too expensive. Retention tiers decide the storage bill. | Raw for 15 days. Coarser rollups for 13 months, then hourly for 5 years. | Downsampling jobs and several storage tiers, and queries that pick the right tier. |
| What queries must be fast, and how fast? | Dashboards ask for aggregates over many series, not single points. | Range queries with sum, rate and percentile grouped by a label. Under 2 seconds for 24 hours of data. | A query frontend with splitting and caching, and an index from labels to series. |
| How fast must an alert fire, and how many rules are there? | Alerting is a read workload that never stops, and it has its own reliability bar. | About 1 million rules, each checked every 30 to 60 seconds. A page within 2 minutes of a real problem. | A sharded evaluator reading recent data, and an alert manager that groups and deduplicates. |
| What happens to data and alerts if part of the system is down? | The monitoring system has to work in the middle of an outage. | Ingestion and alerting must stay available. A few minutes of delayed dashboards is acceptable. | Agent buffering, a queue between ingest and storage, replicated writers, and redundant evaluators. |
| Is it multi-tenant? Is there one cluster or many regions? | Tenants need isolation and limits. Regions decide whether we need a global query layer. | Many teams share one platform. Run per region, with a global view on top. | Per-tenant quotas, and a query layer that can fan out across regions. |
| Do we also store logs and traces? | Logs and traces are far larger and have different access patterns. | No. Metrics only, but we link to the logs and traces systems. | We keep high-cardinality detail out of metrics and point to logs and traces for it. |
| Do we need exact values or are approximations fine? | Exact percentiles over everything are very expensive. Approximations are cheap and good enough. | Approximate percentiles from histograms are fine. Counters must be exact. | Histograms with fixed buckets or a sketch, and exact counters. |
| Assumption | Value |
|---|---|
| Hosts | 500,000 |
| Metrics per host | about 100 (50M series) |
| Sampling interval | 10 seconds |
| Raw sample size | 16 bytes (8 timestamp + 8 value) |
| Compressed sample size | about 1.4 bytes (delta-of-delta + XOR, illustrative) |
| Head memory per active series | about 3 KB (illustrative) |
| Retention | raw 15 days, 5-minute rollups 13 months, 1-hour rollups 5 years |
| Values per rollup bucket | 4 (min, max, sum, count) |
| Alert rules | 1,000,000, each checked every 30 seconds |
| Dashboard load | 5,000 open dashboards, 12 queries each, refreshed every 30 seconds |
| What | Maths | Result |
|---|---|---|
| Active series | 500,000 hosts × 100 metrics | 50 million series |
| Samples per second | 50,000,000 ÷ 10 s | 5 million per second |
| Samples per day | 5,000,000 × 86,400 | 432 billion |
| Raw size per day | 432 billion × 16 bytes | 6.9 TB |
| Compressed per day | 432 billion × 1.4 bytes | about 600 GB |
| Raw tier, 15 days (one copy, and three copies) | 605 GB × 15, then × 3 | 9.1 TB, and 27 TB |
| Same 15 days without compression | 6.9 TB × 15 | 104 TB (11 times more) |
| Head memory for the newest data | 50,000,000 series × 3 KB, then × 3 copies | 150 GB, and 450 GB (about 30 ingesters at 15 GB each) |
| 5-minute rollups, 13 months | 50M × 288 buckets × 4 values × 1.4 B × 395 days | about 32 TB |
| 1-hour rollups, 5 years | 50M × 24 × 4 × 1.4 B × 1,825 days | about 12 TB |
| All three tiers, one copy | 9.1 + 32 + 12 | about 53 TB, against 1,100 TB for 5 years of raw |
| Alert evaluation reads | 1,000,000 rules ÷ 30 s = 33,000 evaluations a second × 20 samples each × 30 | about 20M samples a second, 4 times the ingest rate |
| Dashboard queries, uncached | 5,000 × 12 ÷ 30 s = 2,000 queries a second × (100 series × 8,640 samples) | about 1.7 billion samples a second (far too many to read raw) |
| Dashboard queries with caching | only the newest 30 s is new: 100 series × 3 samples = 300 per query | 2,880 times less work per refresh |
| One bad label (1 million values on 14 metrics) | 1,000,000 × 14 = 14 million new series | 28% more series, 42 GB more head memory, 169 GB a day more |
| Method | Path | Request | Response | Notes |
|---|---|---|---|---|
| POST | /v1/write | { samples: [{ name, labels, ts, value }] } (batched, compressed) | 204, or 429 with Retry-After, or 400 for a bad batch | Authenticate the tenant. Accept batches of thousands. 429 tells the agent to slow down and buffer. Reject a batch that would create too many new series, with a clear error. |
| GET | /v1/query_range | ?expr=sum(rate(http_requests_total{service="api"}[5m])) by (status)&start&end&step | 200 { series: [{ labels, points: [[ts, value]] }] } | The step sets the output resolution. The server picks a raw or rolled-up tier by range, and enforces limits on series, samples and time. |
| GET | /v1/series | ?match[]={service="api"}&start&end | 200 { series: [labels] } | Lists series that match a selector. Used by dashboards for drop-downs. Capped, because it can be huge. |
| PUT | /v1/rules/{group} | { rules: [{ name, expr, for, labels, annotations }] } | 200 { version } | Create or replace alert rules. Validate that the expression parses and is not too expensive. Store with a version. |
| POST | /v1/alerts (to the alert manager) | [{ labels, annotations, startsAt, endsAt }] | 200 | Evaluators send firing and resolved alerts. The manager groups, deduplicates, silences and routes them to notification channels. |
| Concept | What it is | Why it is shaped this way |
|---|---|---|
| Series | A unique metric name plus a sorted set of label pairs, such as http_requests_total{service=api, status=500} | Every distinct label set is a separate series. This is why cardinality is the main cost. |
| Series id | A small integer given to each series when first seen | Index and chunks refer to the id, not the long label text, which saves space. |
| Label index | For each label=value pair, a sorted list of series ids (a posting list) | To match {service=api, status=500} we intersect two sorted lists. No scan of all series. |
| Chunk | A block of compressed samples for one series over a short span | Delta-of-delta timestamps and XOR values make about 1.4 bytes a sample. |
| Block | An immutable set of chunks plus an index for a time span, such as 2 hours | Immutable blocks are easy to cache, copy to object storage, replicate and delete as a whole. |
| Head | The newest, still-mutable data in memory, backed by a write-ahead log | Writes go to memory fast, and the log makes a crash safe. |
-- A sample on the wire
http_requests_total{service="api", region="eu", status="500"} ts=1733300000 value=48211
-- Series identity: name + sorted labels -> id 7314902
-- Label index (posting lists, sorted series ids):
service="api" -> [ ..., 7314902, 7314911, ... ]
status="500" -> [ ..., 7314902, 9020331, ... ]
-- query {service="api", status="500"} = intersect the two lists, then read those chunks
-- Chunk for series 7314902, block 2024-12-04 08:00-10:00:
first ts, first value, then per sample: delta-of-delta of ts (often 0 = 1 bit),
and XOR with the previous value (often few bits when the value changes little)| Component | What it does |
|---|---|
| Agent (on every host) | Collects local metrics, adds labels, batches samples, and buffers them on disk if the network or gateway is down. |
| Ingest gateways | Authenticate the tenant, apply rate and series limits, validate the batch, and write to the queue. Stateless, so they scale out. |
| Queue | Holds samples between gateways and ingesters. It absorbs bursts, lets ingesters restart without data loss, and gives replay. Partitioned by series hash. |
| Ingesters | Own a slice of the series. Append to a write-ahead log and the in-memory head. Every two hours they cut an immutable block. |
| Compactor and downsampler | Merge small blocks into larger ones, build the index, write rollups, and upload blocks to object storage. Drop blocks past retention. |
| Query frontend and queriers | Split long ranges into days, cache results, choose a tier, fan out to ingesters and blocks, and merge the answer under limits. |
| Rule evaluators | Run alert and recording rules on a schedule, keep the pending, firing and resolved state, and send alerts to the alert manager. |
| Alert manager | Deduplicates the alerts from redundant evaluators, groups them, applies silences and inhibition, and routes them to people. |
| Meta-monitor | A small, separate system that watches the platform and pages if the platform stops reporting. It must not depend on the thing it watches. |
The problem: Five million samples a second arrive from half a million machines, in bursts. Agents fail and restart, networks drop, clocks differ, and a single slow storage node must not cause lost data or an outage. We also need to know when a machine has stopped reporting.
| Option | How it works | Good | Bad |
|---|---|---|---|
| Push from every host | Each agent sends its samples to a central endpoint on a schedule. | Works through firewalls and for short-lived jobs. Simple for the host. | The server does not control the rate. A dead host is silent, and silence looks like no data, not a failure. Bad agents can flood the system. |
| Pull (scrape) | The server keeps a list of targets (from service discovery) and fetches each one every 10 seconds. | The server sets the rate. A failed fetch is an immediate, visible signal that the target is down. Easy to test a target by hand. | Needs service discovery and network reach to every target. Short-lived jobs may finish before a scrape. Hard across firewalls and NAT. |
| Local agent scrapes, then pushes batches | A small agent on each host or cluster pulls from local targets, then pushes compressed batches to the gateways. | Local pull gives health signals, and batched push crosses networks. Agents can buffer, add labels and drop unwanted ones before the data leaves the machine. | One more piece to run and upgrade on every host. The agent itself must be monitored. |
| Stream everything through the queue first | All writers publish to a partitioned log. Ingesters read and write to storage at their own pace. | Decouples ingest from storage, absorbs bursts, and allows replay after a bug or a restart. | More infrastructure, and a little more delay. The queue itself needs capacity planning. |
The agent gets the best of both models: pull-style health (a failed local scrape is a clear signal) and push-style reach. It also does cheap, useful work at the edge: it batches (thousands of samples per request), compresses, adds labels, drops denied labels, and keeps a bounded disk buffer, so a ten-minute outage loses nothing.
The queue sits between the gateways and the writers. It is partitioned by a hash of the series, so every sample of a series lands on the same ingester, in order, and the ingester can append to one chunk. Ingesters acknowledge after writing the log, keep three copies, and can fall behind briefly without data loss. The cost is one more system to run, which we accept because it turns an outage of storage into a delay, not a loss.
| Problem | How we handle it |
|---|---|
| Out-of-order or late samples | Accept a small window (for example 10 minutes) into the open head. Older than that goes to a slower backfill path, or is dropped with a counter. |
| Clock skew between hosts | Use the agent's timestamp, but reject samples far in the future, and let the gateway stamp samples that have none. Watch for hosts with bad clocks. |
| Backpressure | Return 429 with Retry-After. Agents slow down and buffer, then drop the oldest data first when the buffer is full, and count what they dropped. |
| Duplicate batches after a retry | A sample is identified by (series, timestamp). Writing the same pair twice with the same value is ignored, so a retry is safe. |
| Knowing a host went quiet | Record an up metric for every scrape (1 or 0), so a dead target creates a 0, not just silence. |
The problem: We add 600 GB of compressed data a day and must keep years of history, and still answer a 30-day dashboard in seconds. Storing every raw sample forever is impossible, and reading billions of points for a long chart is too slow.
| Option | How it works | Good | Bad |
|---|---|---|---|
| A general relational database | One row per sample in a table with an index on (series, time). | Familiar tools and SQL. | Row overhead and index make each sample dozens of bytes, 20 times more than needed, and writes at 5M a second are far beyond a normal database. |
| A wide-column or key-value store | Key = (series, time bucket), value = a list of samples. | Scales out and handles writes well. Easy to shard. | Compression is weaker, the label index must be built separately, and aggregate queries are slow without extra work. |
| A purpose-built TSDB: in-memory head, WAL, immutable compressed blocks | Write to memory and a log. Cut an immutable block every 2 hours with chunks and an index. Compact blocks later. | Best compression (about 1.4 bytes a sample), fast ingestion, blocks are easy to cache, replicate, upload and delete. | A specialised system to build or run, and memory scales with the number of series. |
| A columnar warehouse | Store metrics in a column format, queried with SQL. | Good for analytical queries over huge ranges. Can reuse the warehouse. | Slower for the newest data and for many small point lookups. High ingest cost per sample. |
The workload is append-only, ordered by time and read as ranges, which is exactly what a TSDB is built for. Samples within one series change little, so storing the delta of the delta of timestamps (usually zero, one bit) and the XOR of the value against the last one (usually few bits) brings a sample from 16 bytes down to about 1.4. That 11-fold saving is the largest cost lever in the whole design.
Immutable blocks make everything else simple: they can be cached, copied to cheap object storage, replicated and deleted whole when they pass retention. We keep three tiers because the cost of keeping raw data grows without bound: raw for 15 days, 5-minute rollups for 13 months, and 1-hour rollups for 5 years. Each rollup bucket stores min, max, sum and count, so averages, rates and extremes still work, but a single sample cannot be recovered. That trade is deliberate.
| Tier | Resolution | Kept | Size (illustrative) | What you can still ask |
|---|---|---|---|---|
| Raw | 10 s | 15 days | about 9 TB (one copy) | Everything, including a single spike |
| 5-minute rollup | 5 min | 13 months | about 32 TB | Averages, sums, extremes and rates for a month-over-month view |
| 1-hour rollup | 1 h | 5 years | about 12 TB | Long trends and capacity planning, not an incident from last year |
The problem: A series is a unique set of labels, so every new label value makes a new series, and series count multiplies. One deploy that adds a user id or a request id as a label can add millions of series in minutes. Memory, the index, ingest cost and query time all grow with series, and the damage is slow to notice and hard to undo.
| Option | How it works | Good | Bad |
|---|---|---|---|
| Do nothing and add capacity | Let tenants create any labels they like, and buy more memory when it hurts. | No friction for teams. | One team can take the platform down for everyone, and the bill grows without a bound. |
| Hard limits per tenant and per metric | Count active series per tenant. Reject new series above the limit and tell the owner which metric grew. | A hard guarantee. One tenant cannot break the others. | A team can lose new data suddenly. Needs clear errors, alerts before the limit and a way to raise it. |
| Drop or aggregate labels at the edge | The agent or gateway removes denied labels (user id, request id, full URL) or replaces them with a fixed set before storage. | Stops the problem before it costs anything. Cheap and fast. | Needs rules and teamwork, and a dropped label cannot be recovered. |
| Move high-cardinality detail to logs and traces | Keep metrics for low-cardinality aggregates (service, region, status code) and answer per-user questions from logs or traces. | The right tool for each job. Keeps metrics cheap and fast. | Teams must learn which system to use, and link between them. |
Volume is easy to pay for; cardinality is what breaks the system, because index memory and query cost grow with the number of series, not with samples. So the defence has to be a hard cap: count active series per tenant (an approximate count from a HyperLogLog sketch is enough), reject new series above the limit, and warn the owner at 80%. The error names the metric that grew, so a team can fix it in minutes.
Prevention is cheaper than rejection. Rules at the edge drop labels that should never be labels (a user id, a request id, a raw URL with an id in it) and a daily report lists the top metrics by series count. The cultural rule is simple: if a label has an unbounded set of values, it belongs in a log or a trace, and the metric keeps only the aggregate.
| Label | Distinct values | Verdict |
|---|---|---|
| service | hundreds | Fine |
| region, status_code, method | tens | Fine |
| pod or container id | thousands, and churning | Careful: churn creates a new series every deploy |
| customer id | tens of thousands | Only with a limit, and only for key metrics |
| user id, request id, session id, raw URL | millions and unbounded | Never. Use logs or traces |
The problem: A dashboard refreshes every 30 seconds for thousands of people, each chart touching a hundred series over hours or weeks. Read naively that is billions of samples a second. And the most common thing people ask for, a percentile such as p99 latency, cannot be computed correctly from stored averages or from other percentiles.
| Option | How it works | Good | Bad |
|---|---|---|---|
| Query raw data every time | Each refresh reads every raw sample in the range and aggregates it. | Simple and exact. | About 1.7 billion samples a second for the dashboard load. Long ranges time out. |
| Query frontend: split, cache and pick a tier | Cut a long range into per-day parts, cache the finished parts, compute only the newest part, and read a rollup for long ranges. | 2,880 times less work per refresh. Immutable past data is perfectly cacheable. | More moving parts and cache invalidation for late data near the edge. |
| Precompute with recording rules | Compute expensive aggregates (for example per-service request rate) on a schedule and store them as new series. | Dashboards and alerts read a few cheap series instead of thousands. | Costs extra series and storage, and you must know the queries in advance. |
| Averages for latency | Store the mean (or each host's p99) and combine those. | Tiny to store. | Wrong. Averages hide the slow tail, and you cannot average percentiles into a real percentile. |
Most dashboard work is repeated, and most of the data in a long range is already final. The frontend splits a 7-day query into 7 daily parts, answers six of them from a cache, and computes only today. It also picks the tier by range: an hour of data from the raw tier, a month from 5-minute rollups. With step alignment so the same chart reuses the same cache keys, a refresh costs seconds of new data, not days.
For latency, store a histogram: a count of requests in each latency bucket. Buckets from different hosts can simply be added, and the percentile is read from the merged counts. Averaging each host's p99 gives a wrong answer, as the visualizer below shows. A mergeable sketch (t-digest or DDSketch) is the more precise alternative, with a small, bounded error.
| Question | Answer |
|---|---|
| Counter reset (a process restarts and its counter drops to 0) | A rate() function detects a drop and treats it as a reset, not as a negative rate. |
| A query that matches 50 million series | Enforce limits on series, samples and time per query. Reject it with an error that says why, so one query cannot hurt the cluster. |
| Tail latency of a fan-out query | A query touches many shards, so the slowest one sets the time. Use timeouts, hedged requests and partial results with a warning. |
| Late data inside a cached part | Do not cache the last few minutes. Mark newer parts as incomplete and recompute them. |
| Which rollup to read | The step decides: if a point is 1 hour wide, read the 1-hour rollup rather than 360 raw points. |
The problem: A million rules must be checked every 30 seconds on fresh data, page the right person once, not fifty times, and keep working when parts of the system are failing. A noisy alert system gets ignored, and a silent one is worse than none. And if the monitoring system itself dies, nobody gets a page about it.
| Option | How it works | Good | Bad |
|---|---|---|---|
| One central evaluator | A single process loads all rules and checks them in a loop. | Simple. No coordination. | A bottleneck at 33,000 evaluations a second, and a single point of failure for all alerting. |
| Sharded evaluators with HA pairs | Rule groups are spread over evaluators by hash. Each shard runs on two replicas that both evaluate, and the alert manager deduplicates. | Scales out, and no single failure stops alerting. Both replicas fire, so a dead one loses nothing. | Twice the read load, and the alert manager must deduplicate. Two replicas can briefly disagree. |
| Evaluate inside the storage layer | Run the rules where the data lives, as a streaming query on the incoming samples. | Very fast, and no re-reading of data. | Complex. Mixes concerns, and any storage failure hits alerting too. |
| Rely on a single external service | Send metrics to a vendor, and let it alert. | Little to run. | Still needs a watcher for the vendor, and may not fit your cost, privacy or latency needs. |
Spread rule groups across evaluators by hash, and run two replicas of every shard that both evaluate and both send. The alert manager deduplicates by label set, so one real problem is one page. Each alert goes through a small state machine: pending (the condition is true), firing (true for the whole for duration, say 5 minutes, which prevents flapping), then resolved. Evaluators read data slightly older than the ingestion lag, so a late sample does not cause a false alarm.
The hardest question is who watches the watcher. We run a small, independent system on separate infrastructure that checks the platform, plus a dead man's switch: an alert that always fires, sent to an external service that pages us if it ever stops arriving. Silence becomes a signal.
| Design choice | Why |
|---|---|
| Alert on symptoms (SLO burn rate), not causes | Users feel errors and slowness, not CPU. Burn-rate alerts page when the error budget is being spent too fast, with far fewer false pages. |
| A for duration on every alert | A spike for one scrape is noise. Five minutes of failing is a problem. |
| Group and inhibit | One broken database should be one page, not 400. Inhibition suppresses child alerts when the parent is firing. |
| No data is a decision | A rule whose series vanished stays silent unless you also alert on absence. Decide per rule, and use the up metric. |
| Reliable notification | Retry, fall back to a second channel, and track delivery. A page that never arrived is the same as no alert. |
| Test rules like code | Unit-test the expressions on sample data and backtest on past incidents before shipping them. |
| Bucket (ms) | ≤50 | ≤100 | ≤200 | ≤500 | ≤1000 | Requests | p99 |
|---|---|---|---|---|---|---|---|
| Shard A | 700 | 290 | 9 | 1 | 0 | 1,000 | 100 ms |
| Shard B | 3,000 | 2,000 | 2,900 | 1,010 | 90 | 9,000 | 500 ms |
| Merged buckets | 3,700 | 2,290 | 2,909 | 1,011 | 90 | 10,000 | 500 ms |
A simplified model with fixed numbers and no random values. Every size here is an illustrative assumption: 16 bytes a raw sample, about 1.4 bytes compressed, about 3 KB of head memory per series, and 4 values per rollup bucket. The extra label is counted as one new series per label value per metric that carries it. Real compression and memory depend on the engine and the data.
| Bottleneck | Fix |
|---|---|
| Series growth from one bad label | Series limits per tenant at the gateway, label rules at the edge, a warning at 80%, and a top-series report. The cheapest fix is before storage. |
| Head memory (150 GB for 50M series, 450 GB with 3 copies) | Many ingesters, each holding a slice. Keep blocks short (2 hours) so memory is released, and watch memory per series. |
| Alert evaluation reads (about 20M samples a second) | Recording rules for shared sub-expressions, evaluate on recent data only, and shard evaluators. Flag expensive rules. |
| Dashboard load at 9am | Query frontend with splitting and a results cache, tier selection, and per-tenant query limits. Recording rules for the busiest charts. |
| Object storage reads for long ranges | Read rollups, cache index and chunk files locally, and compact small blocks into larger ones. |
| A hot tenant on a few ingesters | Shard by series hash, not by tenant, and add a per-tenant rate limit and a per-tenant quota on ingesters. |
| Cross-region queries | Each region keeps its own data. A global query layer fans out and merges, and returns partial results with a warning if a region is slow. |
| Failure | How the design copes |
|---|---|
| An ingester dies | Two other copies hold its series. The queue replays what it missed, and the WAL restores its head on restart. Queries read the other copies meanwhile. |
| The network between agents and gateways breaks | Agents buffer on disk, then send the backlog with backoff. Old samples inside the accepted window are written, and the rest go to a backfill path. |
| Object storage is slow or down | Recent queries still use the heads. Long-range queries fail with a clear error or partial data, and compaction retries later. No new data is lost. |
| Storage cannot keep up with writes | The queue grows (lag), and the lag alert fires. Scale ingesters, and shed low-priority tenants if needed. No loss while the queue has room. |
| A rule evaluator dies | Its replica is already evaluating, and the alert manager deduplicates. A new instance takes over the shard and reloads the rule state. |
| The whole platform is down | The independent meta-monitor and the dead man's switch notice that data stopped, and page the on-call by a path that does not use the platform. |
Agents scrape locally, batch and buffer, and push through gateways with limits into a partitioned queue. Ingesters keep the newest data in memory with a write-ahead log, three copies each, and cut immutable compressed blocks every two hours. Blocks are compacted, downsampled into tiers and stored in object storage. A query frontend splits, caches and picks a tier, and percentiles come from mergeable histograms. Sharded evaluators with HA pairs and an alert manager page people, and an independent meta-monitor with a dead man's switch watches the platform. The key risk is cardinality, so we cap series per tenant.
| Decision | What we gain | What it costs |
|---|---|---|
| A purpose-built TSDB with compression | About 1.4 bytes a sample, so 11 times less storage than raw. | A specialised system, and memory that grows with series. |
| Downsampled tiers | Five years of history for about 53 TB instead of over 1,000 TB. | Old data loses detail and cannot give back single samples. |
| A queue between gateways and ingesters | Bursts and storage outages become delay, not loss, and we can replay. | Another system to run and a little extra latency. |
| Hard series limits per tenant | One team cannot take down the platform. | A team may be rejected suddenly, so we need warnings and clear errors. |
| Histogram buckets for latency | Percentiles that merge correctly across hosts. | Approximate answers, and many series per histogram. |
| Two evaluator replicas per shard | No single failure stops alerting. | Double the read load and a deduplication step. |
Show that you understand push versus pull, and what five million samples a second really means.
Where cost and correctness live. This is where interviewers separate levels.
Reading the data, and being paged correctly.
Where the interviewer changes the problem or asks what you would do on call.
A change in requirements is a test of whether you understand why your design looks the way it does.
| New requirement | What changes in the design |
|---|---|
| Sub-second resolution for a few key metrics | A separate fast path with short retention for a small set of series, and a high-resolution tier only for them. Cost is proportional to series times rate, so keep the set small. |
| Logs and traces too | Separate systems with their own storage, since logs and traces are much larger and indexed differently. Link them to metrics with exemplars and shared labels. |
| Strict global consistency across regions | Not worth it for monitoring. Prefer regional clusters with a fan-out query layer and regional alerting, so one region failing does not blind the rest. |
| A customer-facing metrics product (many external tenants) | Stronger isolation, per-tenant encryption and quotas, usage billing, a public API, and much tighter limits on cardinality and query cost. |
| Event or high-cardinality analytics (per user) | That is an analytics workload: a columnar store or a log pipeline, not a metrics store. Keep only aggregates in metrics. |
| Percentiles must be exact | Keep raw latencies for a short window, or use a high-precision sketch, and accept a much larger cost. Say what the cost is. |
| Retention must be 10 years at full resolution | Costs grow linearly. Use cheap object storage tiers, columnar compression and, for compliance data only, a separate archive path. |
| Only 1,000 hosts | A single Prometheus-style server with local disk and one alerting pair is enough. Do not build the distributed version before you need it. |
| Area | Weak | Good | Great |
|---|---|---|---|
| Requirements | Starts with boxes. Never asks about retention, cardinality or alert latency. | Asks about scale, retention, query and alert speed, and writes the scope down. | Also asks about push versus pull, tenants, what must survive an outage, and what no data means. |
| Estimation | No numbers, or only a daily total. | Gets series, samples per second and raw storage. | Prices compressed bytes per sample, memory per series and each retention tier, and shows alert reads exceed ingest. |
| Design | One database that does everything. | Agents, a queue, writers, storage, a query layer and an alerting path. | Series-hash sharding, head plus WAL plus immutable blocks, a query frontend with caching, and a watcher outside the platform. |
| Cardinality and correctness | Does not mention series count. Averages percentiles. | Knows what a series is and uses histograms. | Caps series per tenant at the edge, counts churn, explains why percentiles do not merge, and says what a rollup loses. |
| Trade-offs | Presents one solution as obviously right. | Compares push with pull, and raw with rollups. | States the cost of each choice, such as rollups losing detail and hard limits rejecting a team, and says when a simple design is enough. |
| Operations | No failure plan. | Mentions replication, retries and basic alerts. | Plans for a dead ingester, a label explosion, late data and an outage of the monitor itself, with a dead man's switch. |
| Mistake | Do this instead |
|---|---|
| Treating it as a big-data volume problem and ignoring cardinality | Name series count as the main risk, and add hard limits and label rules at the edge. |
| Storing every raw sample forever | Use compression, retention tiers and rollups, and say what they lose. |
| Averaging percentiles or storing only means for latency | Store mergeable histogram buckets or sketches, and compute the percentile after merging. |
| Letting dashboards read raw data on every refresh | Put a query frontend with splitting, caching, tier selection and limits in front. |
| Alerting on causes such as CPU, and with no for duration | Alert on symptoms and SLO burn rate, with a for duration, grouping and inhibition. |
| One evaluator and one alert manager | Shard evaluators, run replicas, and deduplicate in the alert manager. |
| No answer for who watches the monitor | Add an independent meta-monitor and a dead man's switch to an external service. |
| Allowing user ids or request ids as labels | Drop them at the edge and use logs or traces for per-request detail. |
The storage ideas this design builds on: time-ordered, append-only data.
Counters, gauges and histograms, and what the agents collect.
The alerting basics: symptoms, thresholds and on-call.
Burn-rate alerts, the best way to page on symptoms.
The partitioned log between gateways and ingesters.
How the head block survives a crash.
A cheap way to count active series per tenant.
How metrics, logs and traces fit together.