InterviewDryRun
Lesson 18 · 22 min video · free

Design a Metrics System

Every server in a large company reports CPU, memory, request rates and latencies every few seconds, and engineers expect dashboards to load instantly and alerts to fire within a minute. This lesson designs that metrics system for a hundred thousand servers: a label-based data model, collection agents, a buffered ingestion pipeline, a compressed time-series store with downsampling, and an alerting engine that keeps working when everything else is on fire.

What you will learn

  • A metric is a name plus labels; each unique combination is a time series.
  • Cardinality, the number of series, is the real scaling limit; guard against unbounded labels.
  • Buffer ingestion through a log so storage problems never drop data at the source.
  • Time-series storage compresses timestamps and values with deltas, down to a couple of bytes a point.
  • Downsample old data and keep raw points only for days.
  • Alerting must be independent of, and more reliable than, the systems it watches.

In this lesson

  1. The question
  2. Step 1: Clarify the requirements
  3. Step 2: The data model
  4. Step 3: Back-of-the-envelope estimates
  5. Step 4: Collecting metrics
  6. Step 5: The ingestion pipeline
  7. Step 6: Storing time series
  8. Step 7: Retention and downsampling
  9. Step 8: Queries and dashboards
  10. Step 9: Alerting
  11. Step 10: One alert, end to end
  12. Step 11: The cardinality problem
  13. Step 12: Failures
  14. Step 13: The follow-up questions
  15. Recap
Practice this question with Max

The question

Welcome to lesson eighteen of the InterviewDryRun system design course. Today we design a metrics and monitoring system: the thing that collects numbers like CPU usage, request rates and error counts from every server, draws them on dashboards, and wakes someone up when they go wrong.

Every company that runs software at scale has one, and it is one of the most important internal systems there is, because it is how engineers know whether everything else is working. That gives it an unusual requirement: it must keep working precisely when everything else is failing. A metrics system that falls over during an outage is worse than useless. Interviewers like this question because it combines a heavy write workload, a specialised storage problem, and that reliability twist.

Max asks

“Design a system that collects metrics from a hundred thousand servers and powers dashboards and alerts.”

That is how Max, our AI interviewer, asks it. Three things: collect, from a hundred thousand servers; dashboards, which means queries over time ranges; and alerts, which means continuous evaluation of rules. Each one gets its own part of the design. And the number, a hundred thousand servers, tells us to do the estimate carefully, because it decides almost everything about storage.

The plan: requirements, then the data model, because metrics have a particular shape, then numbers. Then collection, ingestion, the time-series database and its compression, retention and downsampling, queries and dashboards, alerting, the cardinality problem, and failures. Then the follow-up questions.

Step 1: Clarify the requirements

Functional requirements
  1. 01
    CollectSystem and application metrics, every 10 seconds
  2. 02
    StoreRaw for weeks, summarised for a year or more
  3. 03
    QueryGraphs over time, filtered and grouped by labels
  4. 04
    DashboardsMany panels, refreshing every few seconds
  5. 05
    AlertsRules on metrics; notify within a minute

Start with questions, and be clear about what this system is not. Logs, which are text records of individual events, and traces, which follow single requests across services, are related but separate systems. Metrics are numbers sampled over time. Say that we focus on metrics.

We collect two kinds: system metrics from every machine, like CPU, memory, disk and network, and application metrics that services report themselves, like requests per second, error counts and latency. Ask how often. Every ten seconds is a common default. And how long to keep data. A typical answer: full detail for a couple of weeks, and summaries for a year or more, for capacity planning.

Queries: plot a metric over time, filter by labels like service or region, and aggregate, for example the total request rate of a service across all its servers, or the ninety-ninth percentile latency. Dashboards run many such queries and refresh every few seconds. And alerts: rules like error rate above one percent for five minutes, evaluated continuously, notifying the right team within a minute or so.

Non-functional requirements
  1. 01
    Huge write rateMillions of data points a second
  2. 02
    Fast recent queriesDashboards in under a second
  3. 03
    Never miss an alertMore reliable than what it watches
  4. 04
    Tolerates small lossA missing point is fine; a missing hour is not
  5. 05
    Cost efficientPetabytes if stored naively

The qualities. The write rate is enormous and constant, every server reporting every ten seconds, forever. Writes dominate; reads are comparatively rare, but must be fast, especially for recent data.

Alerting must be the most reliable part. Interviewers often probe this. If the metrics system is slow or down during an incident, nobody gets paged, and the incident gets worse unseen.

On the other hand, we can tolerate small losses: a single missing ten-second point does not change any graph. That is a useful relaxation, and you should say it out loud, because it lets us choose speed and availability over strict durability for individual points. And cost: stored naively, this data would be huge, so compression will be central.

Step 2: The data model

A metric data point
http_requests_total{service="checkout", region="ap-south",
                    host="web-0412", status="500"}  1729.0  @ 1730288400

name + labels  = one time series
value          = a number (counter, gauge, histogram bucket)
timestamp      = seconds or milliseconds

Before estimating, look at the data's shape. A data point is a metric name, a set of labels, a value and a timestamp. For example, http requests total, with labels for service, region, host and status code, has the value one thousand seven hundred and twenty-nine at this moment.

The crucial concept is the time series: one unique combination of name and labels. The request counter for the checkout service, in one region, on host four-twelve, with status five hundred, is one series. Change any label value, a different host or status, and it is a different series. Each series is just a long list of timestamp and value pairs.

Metric types matter too. A counter only goes up, like total requests, and we compute rates from it. A gauge goes up and down, like memory in use. A histogram counts observations into buckets, like how many requests took under ten, fifty or two hundred milliseconds, which lets us estimate percentiles later by combining buckets across servers. Note that you cannot average percentiles from different servers; you must combine histograms. That is a subtle point interviewers like.

Step 3: Back-of-the-envelope estimates

Sizing it
Servers100,000
Series per serverabout 1,000system + app metrics
Active series100 million
Interval10 seconds10 million points a second
Raw size16 bytes a point160 MB/s, 14 TB a day
Compressedabout 1.5 bytes a pointabout 1.3 TB a day

Now the numbers.

A hundred thousand servers, each producing about a thousand series, counting system metrics and all the application metrics of the services on it. That is a hundred million active time series. This number, the count of series, is called cardinality, and it is the most important number in this design.

Each series reports every ten seconds, so ten million data points a second. That is the write rate. It is high, but each point is tiny.

Stored naively, a point is a timestamp and a value, eight bytes each, sixteen bytes. Ten million a second is a hundred and sixty megabytes a second, fourteen terabytes a day, several petabytes a year. But time-series data compresses extremely well, as we will see, to around one and a half bytes a point. That turns fourteen terabytes a day into about one point three. Retention and downsampling then keep the total manageable.

One more number: the index. A hundred million series, each with a name and several labels, needs an index from label values to series, so a query like service equals checkout can find its series quickly. That index must live largely in memory, and it grows with cardinality, not with time. Remember this: it is why cardinality, not data volume, is usually what breaks metrics systems.

Step 4: Collecting metrics

Push or pull?
Pull (scrape)Push
Howcollector fetches each target's /metricsagent sends to collector
Knows target is downyes, the scrape failsonly by absence
Short-lived jobsmay be missedeasy
Behind firewallshardereasy
Control of loadcollector sets the pacesenders can flood

How do metrics get from a hundred thousand servers into our system? There are two models, and interviewers almost always ask you to compare them.

In the pull model, each service exposes its current metrics on an HTTP endpoint, and collectors scrape every target every ten seconds. The collectors need a list of targets, which comes from service discovery. A big advantage: if a scrape fails, we know immediately that the target is down, which is itself a valuable signal.

In the push model, an agent on each machine collects metrics from local services and pushes them to the collection tier. Push works better for short-lived jobs, which may finish before anyone scrapes them, and for machines behind firewalls that collectors cannot reach.

A practical answer combines them: a lightweight agent on every host scrapes the local services, which keeps the convenience of the pull format and detects dead processes locally, then batches, compresses and pushes everything to the ingestion tier. Short-lived jobs push directly to a small gateway. Pull's real downside at our scale is a central scraper needing to reach a hundred thousand machines; the local agent removes that. Make the trade-off clear, then pick.

The agent also protects the system. It can buffer a few minutes of data on local disk if the ingestion tier is unreachable, drop or aggregate metrics that exceed limits, and add standard labels like region and host, so services do not each have to.

Step 5: The ingestion pipeline

Ingestion
CLIENTHost agentsscrape, batch, pushEDGEIngest gatewaysvalidate, limitQUEUEDurable logpartitioned by seriesSTORETSDB writersby series shardWORKERStream rulespre-aggregation, alerts

Agents push batches to a fleet of stateless ingest gateways. Gateways authenticate the sender, validate the data, and enforce limits, such as a maximum number of series per service, which we will come back to when we talk about cardinality.

Then they write to a durable, partitioned log, like the message queue from lesson fifteen, partitioned by a hash of the series. This buffer is important. If the storage tier is slow, or being upgraded, or recovering from a failure, data piles up in the log instead of being dropped or pushing back onto every server in the company. Ingestion and storage can fail independently.

Storage writers consume the log. Because partitions are by series, each writer always receives all the points for its series, in order, which is exactly what time-series compression needs.

Other consumers can read the same log: stream processors that pre-compute common aggregations, like total request rate per service, and can even evaluate the most critical alerts directly on the stream. The log turns one firehose into something several systems can consume at their own pace.

Step 6: Storing time series

Inside a time-series store
  1. 01
    Head block in memoryThe last two hours, per series, appended
  2. 02
    Write-ahead logRecover the head block after a crash
  3. 03
    Immutable blocksEvery 2 hours, compressed to disk
  4. 04
    Inverted indexLabel value to series ids, per block
  5. 05
    CompactionMerge small blocks into bigger ones

Why not use a general-purpose database? Because the access pattern is very specific: writes are almost always appends of the newest point to each series, and reads ask for a range of time across a set of series. A specialised time-series store does both far better. Here is how one works.

Recent data, say the last two hours, lives in memory in a head block: for each series, a buffer of the newest points. Every incoming batch is also appended to a write-ahead log on disk, so a crash can rebuild the head block.

Every two hours, the head block is compressed and written to disk as an immutable block, covering that time range for all the series on this node. Old blocks are merged into larger ones in the background, which keeps the number of files small.

Each block has an inverted index, like a search engine's: for every label and value, the list of series ids that have it. A query for service equals checkout and status equals five hundred intersects two lists, finds the matching series, and reads their points for the time range. This is what makes label filtering fast.

Why points compress to under 2 bytes
timestamps: 1000, 1010, 1020, 1030, 1041
deltas:           10,   10,   10,   11
delta of deltas:         0,    0,    1    → mostly a single bit

values:    52.1, 52.1, 52.3, 52.3
XOR with previous value → mostly zero bits → a few bits each

Now the compression trick, which is worth explaining because it is elegant. Timestamps arrive at regular intervals. Store the first one, then the difference between consecutive timestamps, and then the difference between those differences, which is almost always zero. A zero takes a single bit.

Values change slowly too. XOR each value with the previous one; if they are equal, the result is zero, and if they are close, most of the bits are zero. Store only the meaningful bits. Together, a sixteen-byte point usually shrinks to between one and two bytes. That is roughly a ten times saving, which is the difference between a system that costs a fortune and one that is affordable.

Sharding: spread series across storage nodes by hashing the series, with each shard replicated two or three times, consuming the same log partitions. Replicas are simple here: each one consumes the log independently and builds its own copy. If a node dies, its replica serves queries, and a replacement rebuilds from the log and from blocks in object storage.

Step 7: Retention and downsampling

Keeping a year affordable
AgeResolutionStored as
0 to 15 days10 seconds, rawlocal SSD blocks
15 to 90 days1 minuteobject storage
90 days to 2 years1 hourobject storage

Raw ten-second data for two years would be hundreds of terabytes, and nobody needs ten-second detail from last year. So data gets coarser as it ages. This is called downsampling.

Keep raw points for about two weeks, which covers investigating recent incidents. Then, a background job rolls them up into one-minute points, and later into one-hour points. Each rollup keeps the minimum, maximum, sum and count for the interval, not just the average, so that graphs still show spikes and rates can still be computed correctly.

Older blocks move from local SSDs to object storage, which is far cheaper, and queries over long ranges read the downsampled data, which is small. A query for the last year of a metric then touches about nine thousand hourly points instead of three million raw ones. The query engine picks the resolution automatically from the time range.

Step 8: Queries and dashboards

The query path
last 15 daysolderCLIENTDashboardsrefresh every 10 sSERVICEQuery frontendsplit, cache, limitSERVICEQueriersfan out, mergeSTORERecent datastorage nodesSTOREOld blocksobject storage

Dashboards send queries like: the rate of five hundred errors for the checkout service over the last six hours, summed by region. They hit a query frontend first.

The frontend splits long time ranges into pieces, for example per day, caches the results of pieces that are complete, because the past does not change, and only recomputes the most recent piece on each refresh. Many people looking at the same dashboard during an incident share those cached results. It also enforces limits, so one enormous query cannot overwhelm the system for everybody.

Queriers fan out to the storage shards that hold the matching series, and to object storage for older ranges. Each shard does as much aggregation as it can locally, summing its own series, so only small partial results travel back to be merged. Pushing computation to the data is the key to making queries over thousands of series fast.

Pre-aggregation helps the most common dashboards. If everyone looks at the total request rate per service, compute it once at ingestion time, in the stream processors, and store it as its own small series. The dashboard then reads one series instead of summing ten thousand on every refresh.

Step 9: Alerting

An alerting pipeline you can trust
  1. 01
    Rules evaluated every 30 to 60 sQuery, compare, keep state
  2. 02
    For a durationFire only if true for 5 minutes
  3. 03
    Deduplicate and groupOne page per incident, not 500
  4. 04
    RouteTo the owning team's on-call
  5. 05
    Watch the watcherA dead-man's switch from outside

Alert rules are queries with a threshold, evaluated every thirty to sixty seconds by a rule evaluator: for example, the error rate of checkout is above one percent. The evaluator keeps state per alert: pending, firing or resolved.

Require a condition to hold for some duration, like five minutes, before firing, so a single spike does not wake someone at three in the morning. Flapping alerts are how teams learn to ignore their pager, which is dangerous.

Firing alerts go to an alert manager that deduplicates, groups related alerts, so a data centre problem produces one page rather than five hundred, applies silences during planned maintenance, and routes to the right team's on-call schedule through the notification system from lesson six.

Now the reliability twist. The alerting path must keep working when the rest of the system is struggling. Run rule evaluation close to recent data, independent of the dashboard query path, replicated, with high priority for resources. And add a dead-man's switch: an alert that always fires, sent to an external service. If that external service stops hearing it, the alerting pipeline itself is broken, and it pages someone through a completely separate path. Watching the watcher is the detail interviewers remember.

Step 10: One alert, end to end

Following one bad minute
  1. 01
  2. 02
  3. 03
  4. 04
  5. 05
  6. 06

Let me walk one real incident through the whole system, because interviewers love to see that the pieces connect. At ten past two, a bad deploy makes the checkout service start returning errors on a fifth of its requests. Every ten seconds, the agent on each checkout host scrapes the local metrics endpoint and reads the request counter, now growing quickly with the status label set to five hundred.

The agent batches those samples with everything else it scraped, compresses them, and sends them to a collector. The collector does not interpret anything. It checks the batch is well formed, applies the per-tenant limits, and appends it to the ingest log, partitioned by a hash of the series. Within about a second, the samples are durable, even if every database node restarted right now.

Storage writers read their partitions of the log and append the samples to in-memory blocks for each series. Because the same series always lands on the same writer, the writer can compress the new value against the previous one. Every two hours those blocks are flushed to disk as immutable files, but for alerting, the in-memory head block is what matters, and it is already up to date.

Meanwhile, the rule engine runs every thirty seconds. It evaluates the rule: the rate of five hundred responses divided by the rate of all responses, over the last five minutes, grouped by service. For checkout, the answer jumps from a tenth of a percent to twenty percent. The rule says the condition must hold for two minutes before firing, which stops a single noisy scrape from waking someone up at night.

Two minutes later the alert fires. The router groups it with related alerts from the same service, so the engineer gets one page, not forty, and attaches a link to the checkout dashboard. The engineer opens the dashboard, which queries the same storage through the query layer, sees errors started exactly at the deploy time, and rolls back. Total time from first bad request to page: about two and a half minutes. Say that number in the interview. It shows you understand that scrape interval, evaluation interval and the hold duration all add up to the detection delay, and that each is a knob you can turn, trading noise for speed.

Step 11: The cardinality problem

How one label explodes
http_requests_total{service, endpoint, status}
  20 endpoints x 5 statuses x 1,000 hosts = 100,000 series   fine

http_requests_total{service, endpoint, status, user_id}
  x 10 million users = 1 trillion series                    disaster

The most common way metrics systems fail in real life is not too many points; it is too many series. Suppose a developer adds a user id label to the request counter, wanting per-user graphs. Twenty endpoints times five statuses times a thousand hosts was a hundred thousand series. Times ten million users, it is a trillion. The index explodes, memory runs out, and the whole system slows for everyone.

Defences come in layers. Limits at ingestion: a maximum number of series per metric and per service, beyond which new series are dropped and the team is alerted. Validation rules that reject labels known to be unbounded, like user ids, request ids and full URLs. And visibility: a page that shows each team how many series they produce, so cost is visible.

And the education point: per-user or per-request data belongs in logs or traces, not metrics. Metrics answer how many and how fast, aggregated. Saying that distinction clearly shows you understand the whole observability picture, not just this system.

Step 12: Failures

What breaks
  1. 01
    Storage node diesReplica serves; replacement rebuilds from log
  2. 02
    Ingestion overloadedLog absorbs it; agents buffer locally
  3. 03
    Query of deathLimits, timeouts, separate pools
  4. 04
    Region outageEach region monitors itself; cross-region watchers

If a storage node dies, its replicas keep serving, and a replacement catches up from the log and from blocks in object storage. Because the log keeps a few hours of data, nothing is lost.

During a big incident, every service emits more errors, and more people open dashboards at once, exactly when the system is most needed. The log absorbs write bursts, agents buffer locally, and queries have strict limits and timeouts, with separate resource pools for alerting so that a flood of dashboard queries cannot starve alert evaluation.

And regions. Run a metrics stack in each region, monitoring that region, so a regional outage does not blind every other region. A small global layer, and a few cross-region watchers, check that each regional stack is alive. The system that tells you a region is down must not live only in that region.

Step 13: The follow-up questions

Max asks

“How would you show the ninety-ninth percentile latency across a thousand servers?”

Each server reports a histogram: counts of requests in latency buckets. To get the overall percentile, sum the bucket counts across all servers, then find the bucket where the cumulative count crosses ninety-nine percent, and interpolate. Averaging each server's own ninety-ninth percentile would be mathematically wrong. Histograms are mergeable; percentiles are not.

Max asks

“A team says their dashboard is slow. How do you investigate?”

Check which queries the dashboard runs and how many series each touches: often one panel sums a hundred thousand series over thirty days. Fixes include adding a pre-aggregated series at ingestion, shortening the default time range, making sure long ranges use downsampled data, and caching. The query frontend's logs of expensive queries make this a quick investigation.

Max asks

“Why not just store metrics in the same system as logs?”

Max asks

“What happens if the monitoring system itself goes down during an incident?”

that is the worst possible time to lose it, so the alerting path must be the most reliable part. Run the rule engine and the alert router in at least two zones, keep them reading from the in-memory head blocks rather than long-term storage, and add a dead man's switch: an alert that always fires, sent to an outside service. If the outside service stops hearing it, it pages someone, because silence means the monitoring is broken, not that everything is healthy.

Logs are large, unstructured text, queried by searching. Metrics are tiny numbers, queried by aggregating over time. Storing metrics as log lines would cost ten to a hundred times more space and make aggregation slow. Many companies link the two, for example jumping from a spike on a graph to the logs for that minute, but they are stored by different engines designed for each shape.

Recap

Your 45 minutes
  1. 01
    0 to 5: requirementsCollect, store, query, alert; alerts most reliable
  2. 02
    5 to 10: model and numbersName + labels = series; 100 M series, 10 M points/s
  3. 03
    10 to 20: collection and ingestAgent pull + push; gateways; durable log
  4. 04
    20 to 35: storage and queriesHead block, compression, index, downsampling, fan-out
  5. 05
    35 to 45: alerts and limitsIndependent alerting, dead-man's switch, cardinality

On the clock: five minutes of requirements, noting that alerting must be the most reliable part. Five minutes on the data model and the numbers: a hundred million series, ten million points a second.

Ten minutes on collection and ingestion: local agents, push versus pull, gateways with limits, and a durable log as a buffer.

Fifteen minutes on storage and queries: an in-memory head block, delta and XOR compression, an inverted index on labels, downsampling and fan-out queries. And the last ten on alerting with its own reliability, and on cardinality, the problem that actually breaks these systems. If you mention the dead-man's switch and unbounded labels, you will sound like someone who has carried a pager.

Metrics systems have many layers, and it is easy to spend all your time on storage and forget alerting. Practicing out loud is how you learn to balance it. 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 nineteen.

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.