Design Metrics Monitoring
How to design a metrics monitoring system: collecting metrics from many servers, storing time series, serving dashboards, and sending alerts reliably.
On this page
A metrics monitoring system collects numeric measurements such as CPU use, request counts and error rates from every server, stores them as time series, shows them on dashboards and notifies the on-call engineer when an alert rule is broken. It combines three hard problems: a very large and steady stream of writes, a number of distinct time series that can grow without warning, and alerting that must keep working when the monitored systems fail.
What to measure is covered in Observability. This lesson designs the system that collects and stores the measurements, following A Framework for Any Design.
Clarify the problem
Design a metrics monitoring system.
Do you mean metrics only, which are numeric time series, or should I also cover logs and traces?
Metrics only.
How many servers are there, how many series does each one report, and how often does it report?
There are 100,000 servers, each reporting about 500 series every 10 seconds.
How long do we keep the data, and at what level of detail?
Full detail for a week, and coarser data for two years.
Then writes dominate and reads spike during incidents. I will give priority to alerts that still fire when parts of production are down, and to dashboards that load a one-hour range in about a second. I will accept losing a few seconds of samples, but not losing alerting.
Functional requirements:
- Collect labelled metrics, such as
service,hostandstatus, from every server. - Query by time range and labels, with sums, rates and percentiles.
- Evaluate alert rules and notify the on-call engineer.
Non-functional requirements:
- Ingest 5 million samples a second, with samples queryable within 30 seconds.
- Load a one-hour dashboard panel in about 1 second.
- Fire an alert within a minute of its hold duration, and keep alerting during partial outages.
- Keep raw data for 7 days and rollups for 2 years.
Out of scope: logs, traces, anomaly detection and the tooling that installs agents.
Estimate the scale
- Series: 100,000 servers × 500 series is 50 million active time series.
- Samples: 50 million series reporting every 10 seconds is a steady 5 million samples a second.
- Raw storage: a sample is a timestamp and a value, 16 bytes uncompressed. 5 million × 86,400 seconds is 432 billion samples a day, or 6.9 TB a day uncompressed. Compression, described in the deep dives, gets a sample down to about 2 bytes, which is 864 GB a day.
- Queries: during an incident, 2,000 dashboards with 20 panels each refreshing every 30 seconds make about 1,300 queries a second. Evaluating 100,000 alert rules every 30 seconds adds 3,300 a second.
How much storage do raw data for 7 days, 1-minute rollups for 30 days and 1-hour rollups for 2 years take together?
- 50 million series; 864 GB a day of raw samples after compression
- A rollup point stores 4 values (min, max, sum, count) at about 2 bytes each: 8 bytes
- 2 years ≈ 730 days
Show the working
- Raw: 864 GB × 7 ≈ 6 TB
- 1-minute: 50 × 106 × 1,440 × 8 B = 576 GB a day; × 30 ≈ 17 TB
- 1-hour: 50 × 106 × 24 × 8 B = 9.6 GB a day; × 730 ≈ 7 TB
- Total ≈ 6 + 17 + 7 = 30 TB
Estimate 30 TB (anything from 10 TB to 100 TB is a good answer)
Keeping raw samples for 2 years would take 864 GB × 730 ≈ 630 TB, about 20 times more.
Each active series costs about 1 KB of memory in the ingesters (its labels, index entries and the open compressed chunk). How much memory do the active series need?
- 50 million active series
- About 1 KB of memory per active series
Show the working
- 50 × 106 × 1 KB = 50 GB, before replication
Estimate 50 GB (anything from 15 GB to 150 GB is a good answer)
Memory grows with the number of series, not with the number of samples, which is why one bad label can take the system down.
Write the endpoint that the agents call to send data, the endpoint that dashboards call to query it, and the definition of an alert rule.
Compare with a model answer
Agents send compressed batches of many series. Dashboards send a query, a time range and a step. An alert rule is a query, a threshold, a hold duration and a notification target.
Define the API Optional
Optional in the interview. Sketch the API only if the interviewer asks, if an API choice shapes the design, or if time permits. Otherwise say "I'll skip the detailed API unless you want it" and go to the data model.
POST /v1/write from agents, every 10 s, compressed
body: [ { "labels": {"__name__": "http_requests_total", "service": "checkout",
"host": "web-17", "status": "500"},
"samples": [[1763114700, 48213]] }, ... ]
204 No Content
429 Too Many Requests tenant over its sample-rate limit (agent backs off)
GET /v1/query_range?q=sum by (status) (rate(http_requests_total{service="checkout"}[1m]))
&start=...&end=...&step=60s
200 { "series": [ { "labels": {"status": "500"}, "points": [[t, v], ...] } ] }
422 Unprocessable query would touch more than 100,000 series
Alert rule
expr: error ratio for checkout > 5%
for: 5m the condition must hold this long before firing
notify: team-checkoutThe API decision worth discussing is the step parameter. A panel 1,000 pixels wide shows about 1,000 points, but a week at a 10-second step has 60,480 points per series. Because the client sends the step, the server can choose the coarsest rollup tier that fills the panel, and it can refuse queries that touch too many series.
What identifies a series, how are its samples stored, and how does a query find the series that match service="checkout"?
Compare with a model answer
A series is identified by its metric name plus its labels, hashed to an id. Its samples are stored in compressed chunks that each cover a time range. An inverted index maps each label pair to the ids of its series, and a query intersects those lists.
Model the data
series id = hash(metric name + sorted labels)
labels {__name__="http_requests_total", service="checkout", host="web-17", status="500"}
chunk series_id, start_time, end_time, compressed bytes (120 samples, 20 minutes)
only the open chunk stays in memory; full ones go to local disk
index "service=checkout" -> [series ids, sorted]
"status=500" -> [series ids, sorted]
query {service="checkout", status="500"} = intersect the two lists
blocks every 2 hours: chunks + index for that window, written as immutable
files to object storage; compaction merges blocks and builds rollupsWrites are append-only, always at the current time, and reads ask for a time range over a set of series. Nothing is updated. This access pattern suits a time-series database, such as Prometheus, M3 or VictoriaMetrics. It keeps open chunks in memory and the last two hours on local disk, and writes older data as immutable compressed blocks to object storage.
Sketch the path from a server's counters to a dashboard and to a page on someone's phone. Which parts must keep working during an outage?
Compare with a model answer
The path is host agents, an ingest service, a log, a time-series store, a query service, and an alert evaluator that feeds a notifier, which pages through an outside provider. The alerting path must run separately from the systems it watches.
High-level design
- series in batch
- 500
1The agent on host web-17 reads its host's 500 series and sends them to the ingest service as one compressed batch.
- series in batch
- 500
2The ingest service checks the tenant's sample rate and appends the batch to the log, partitioned by series id.
- lag
- about 5 s
3The ingester that owns that partition appends each sample to the open in-memory chunk of its series, compressing it as it goes. It can be queried seconds later.
- error ratio
- 7%
- held for
- 0 min
4Checkout's error ratio rises above 5%. The evaluator runs the rule every 30 seconds, and the first time the condition is true the alert becomes pending.
- error ratio
- 7%
- held for
- 5 min
5The condition stays true for the 5 minutes in the rule's hold duration, so the alert fires.
- pages sent
- 1
6Two evaluator replicas run the same rules, so the notifier receives the alert twice. It removes the duplicate and sends one page.
- points per series
- 10,080
7The on-call engineer opens the checkout dashboard for the last 7 days. The query service uses the 1-minute rollup tier, which gives 10,080 points per series instead of the 60,480 raw points.
- new series refused
- 5 million
8A deploy adds a user_id label, and checkout starts creating 5 million new series. The ingesters refuse the new series beyond checkout's limit and alert the team, and the existing series keep being written.
- rules with data
- 0
- pages sent
- 2
9A network failure cuts off the time-series store. The rule queries fail or return nothing, and the evaluator treats that as a problem and fires a "monitoring has no data" alert.
- pages sent
- 3
10Then the notifier goes down as well. It normally sends the paging provider a heartbeat every minute, and when the heartbeats stop the provider pages the on-call engineer on its own, so silence is never mistaken for health.
Deep dives
Collecting metrics: pull, push or a local agent
There are three common ways to get samples from the servers into the system.
Central pull. A central collector keeps a list of targets, found through service discovery, and fetches each target's metrics over HTTP at a fixed interval. The system controls the pace, and a failed fetch shows that the target is down. The weaknesses are that the collector needs network access to every target, and that a job which starts and finishes between two fetches is never seen.
The application pushes directly. Each application sends its metrics to the ingest service. This works for short-lived jobs, serverless functions and hosts behind NAT, which cannot be reached by a collector. The weakness is that a silent target looks the same as a dead one, and a buggy client can flood ingest.
A local agent that pulls locally and pushes batches. An agent on each host reads the metrics of the processes on that host and sends one compressed batch every 10 seconds. Local reads detect dead processes, and the push works from any network. The cost is an agent on every host. The agent also sends an up series, and an alert on that series disappearing separates a dead host from a quiet one. This is the choice for 100,000 hosts.
| Option | Good at | Bad at | Pick it when |
|---|---|---|---|
| Central pull | The system sets the pace and cannot be flooded, and a failed fetch means the target is down. | It needs discovery and network access to every target, and short jobs can finish between fetches. | One cluster or data center that you control. |
| Application pushes directly | It works for short jobs, serverless functions and hosts behind NAT. | A quiet target looks the same as a dead one, and a buggy client can flood ingest. | Short-lived work with no stable address. |
| Local agent Usual default | It detects dead processes, sends one compressed batch per host, and works across networks. | An agent has to run on every host, and a dead agent needs its own detection. | Many hosts across regions and networks, which is this design. |
When the ingest service is slow or returns 429, the agent buffers a few minutes of samples on disk and retries with a random delay, so that 100,000 agents do not all retry at the same moment.
Storing time series
Compression works because neighbouring samples in a series look alike. Timestamps arrive every 10 seconds, for example 1000, 1010, 1020 and 1031. The database stores the first timestamp and then only the difference between consecutive gaps, which is 0 for the third sample and 1 for the fourth. Nearly all of those values are 0 and take one bit each. Values change slowly, so each value is XORed with the previous one, and an unchanged value becomes a single 0 bit. Together these reduce 16 bytes to about 2 bytes per sample.
Downsampling. People look at old data at a coarse resolution, so compaction rewrites it into the rollup tiers from the estimate. Each rollup point keeps the minimum, maximum, sum and count instead of only an average. That keeps maxima and longer averages correct, because the average is the total sum divided by the total count. Percentiles cannot be recovered from those four values. Latency is therefore recorded as a histogram, which is a count of requests for each latency bucket. Histogram buckets roll up correctly because they can be added together.
Cardinality. Every distinct combination of label values is a separate series, so labels multiply. 200 services × 50 endpoints × 10 status codes gives 100,000 series, which is fine. If a developer adds a user_id label, then 1 million users with 5 endpoint and status combinations each gives 5 million series, or 5 GB of ingester memory, from one line of code. Memory, index size and query cost all grow with the number of series, so this is the usual way such a system fails. Three measures protect it:
- Limit the number of active series for each team, and refuse new series beyond the limit while the existing ones keep working.
- Keep unbounded values such as user ids and request ids out of labels; they belong in logs and traces.
- Track the number of new series created per minute for each service and alert on a sudden jump, so that a bad deploy is noticed in minutes instead of when memory runs out.
The query path
A query such as "checkout error rate by status over the last hour" runs in four steps.
- Find the series. The query service intersects the index lists for
__name__=http_requests_totalandservice=checkout. If more than 100,000 series match, it rejects the query with a 422. - Pick a tier. It chooses the coarsest tier that is still finer than the step. A 7-day panel 1,000 points wide has a step of about 10 minutes, so 1,000 series need 10 million 1-minute points instead of 60 million raw ones.
- Fan out. Series are sharded across ingesters by id, so the query service asks every shard that holds a match for recent data, and object storage for older blocks, all in parallel.
- Aggregate early. Each shard returns partial sums grouped by
status, and the query service adds the partial results.
Alerting that keeps working during an outage
The hard problem is shared fate. If the monitoring system runs on the same cluster, network and service discovery as production, then the outage that needs an alert also takes alerting down, and the silence looks like good news. Three measures prevent this.
A separate failure domain. Run monitoring on its own machines and network path, with no dependency on anything it watches, such as production's database or authentication.
Treat missing data as a signal. A rule whose series have disappeared fires a "no data" alert, instead of quietly resolving.
A dead man's switch. An alert that is always firing sends a heartbeat to an outside paging provider every minute. If the heartbeats stop, the provider pages the on-call engineer, so even a complete failure of the monitoring stack produces a page. A small second stack in another region can also check that the main one is still working.
Bottlenecks and failures
At 10 times the scale, which is 500 million series, the ingest service and the log scale by adding nodes, but the ingesters need 500 GB of memory before replication. The index and the query fan-out break next, so put large tenants on their own shard groups, so that one team's huge query cannot slow everyone else. Storage grows to about 300 TB, which object storage handles cheaply.
| When this dies | What happens | What you do |
|---|---|---|
| An ingest node | Requests sent to it fail. | Agents retry on another node, and their disk buffer covers the gap. |
| An ingester | Its recent data is briefly unreadable. | A replacement replays the log, which is kept for a day, from its last flushed block. Two replicas per series keep reads available. |
| Object storage | Data older than about 2 hours cannot be read. | Recent dashboards and alerts still work from the ingesters. |
| The query service | Dashboards fail, and so does alert evaluation. | Run a stateless fleet, and give alerting its own query replicas so that dashboards cannot starve it. |
| The notifier | No pages are sent. | Run two or three notifiers that share deduplication state. If all of them die, the heartbeats stop and the provider pages anyway. |
What a strong answer sounds like
| Level | What the answer does |
|---|---|
| Junior | Stores samples in a database table and runs a cron job that checks thresholds. |
| Mid | Uses a time-series database, chooses push or pull with a reason, estimates storage and adds downsampling. |
| Senior | Sizes the system by series as well as samples, plans for cardinality explosions, explains compression and rollups, builds the query path around the step and fan-out, and keeps alerting working when both production and the monitoring stack fail. |
Your monitoring runs in the same data center as production, and that data center loses its network. What happens?
With the design as described so far, nothing would page. So I would run alerting outside production's failure domain, treat missing data as an alert, and send a heartbeat to an outside paging provider every minute, so that if the whole stack goes dark the provider pages on-call.
Follow-up questions
How do you compute p99 latency across 1,000 servers?
You cannot average each server's p99, because the average of percentiles is not the percentile of the combined traffic. Each server instead records latency as a histogram with counts per bucket, the query adds the bucket counts from all servers, and the 99th percentile is read from the combined histogram.
Why not store the samples in a regular SQL database?
A relational database can hold the rows, but 5 million inserts a second with indexes and row overhead would need a very large cluster, and it would not compress timestamps and values the way a time-series store does. Time-series stores also provide rollups, retention rules and range queries over label sets, which you would otherwise have to build yourself.
How do you avoid alert noise?
The hold duration keeps a short spike from paging anyone, because the condition must stay true for the whole period before the alert fires. The notifier also groups alerts that share labels such as the service, so one outage sends one page instead of hundreds, and it silences alerts that the on-call engineer has already acknowledged.
After your attempt, tick what you really did. Be strict: "I thought about it" is not "I said it out loud".