Case study: design a metrics monitoring system
A senior-level walkthrough of a metrics and alerting system for a large fleet: sizing from series, zone-aware sharded ingestion with idempotent appends, the query path, histogram error, alert grouping and inhibition, and cardinality.
Case studyApplied32 min readUpdated
- 1 architecture diagram
- 2 API designs
- 5 code samples
- 6 interviewer follow-ups
- 5 self-checks
On this page16 sectionsHLDLLDSenior depth
Read first: A framework for system design interviews, Replication and sharding, Observability: metrics, logs and traces
- Size a metrics system from series, sample rate and bytes per sample, and say which number decides each component.
- Shard ingestion by series across zone-aware replicas, and make appends idempotent so that retries are safe.
- Serve recent queries from ingesters and old ones from blocks, with a query frontend that splits, caches and limits.
- Choose histogram buckets by their error, and say why percentiles must be merged as histograms.
- Evaluate alert rules with a pending period, then group and inhibit notifications, and keep the alert path independent.
5 code samples (229 lines), collapsed so the explanation stays in focus.
A metrics system takes millions of samples a second from a whole fleet, answers dashboard queries in about a second and evaluates alert rules around the clock. It has an unusual shape: the writes are huge and constant, the reads are small, recent and repetitive, nothing is ever updated, and old data is summarised. It also has an odd requirement: it must be more reliable than anything it watches, because it is the thing that notices when they fail. Datadog, Prometheus with a long-term store such as Thanos or Mimir, and Google's Monarch all solve this problem, with different trade-offs. This case study designs one for 100,000 hosts. It builds on the time-series databases lesson for storage and on SLOs and alerting for what the alerts are for.
| Ask | Why it matters |
|---|---|
| How many hosts, services and series, and how often is each sampled? | Active series and the sample rate drive memory, index size and ingest throughput |
| Do producers push, or does the server pull? Are there short-lived jobs? | The collection protocol, service discovery, and what "no data" means |
| Who reads, and how? Dashboards, ad hoc queries, alert rules | Dashboards repeat the same recent queries, rules never stop, ad hoc queries are the heavy ones |
| How fresh must data be, how long is it kept and at what resolution? | A few seconds of delay is acceptable, and retention tiers set the storage bill |
| One team or many tenants? | Isolation, per-tenant limits, and who pays for cardinality |
| What must survive what? | The system has to outlive the incident it detects: ingestion and alerting come before long-range queries |
Functional: ingest counters, gauges and histograms with labels; query by name and labels over a time range with aggregation (sum by label, rate, quantile); dashboards; alert rules with a pending period, grouping, silencing and routing; retention with rollups. Non-functional: a million samples a second from ten million series, dashboard queries in about a second, an alert within a minute or two of the event, ingestion more available than the services it watches (say 99.99%), a few bytes per sample, and isolation between tenants. Out of scope: storing logs and traces (the same shape with different stores), anomaly detection and the UI.
State assumptions aloud. They are illustrative.
hosts: 100,000 x 100 series each = 10M active series
interval 10 s: 1M samples/s, 86 billion samples a day
raw at 16 B a sample: 16 MB/s, 1.4 TB a day
compressed at about 2 B a sample: 2 MB/s, 173 GB a day
15 days of raw data: 2.6 TB
rollups, 5 min x 4 aggregates = 13% of the samples:
23 GB a day, 9 TB for 13 months
head, 2 h in memory: 7.2B samples x 2 B = 14 GB
plus 10M series x about 1 KB = 10 GB; x3 replicas = about 75 GB
reads: 5,000 dashboards x 12 panels every 30 s = 2,000 queries/s
100,000 rules every 60 s = 1,700 queries/sThree conclusions come out of it. The bytes are small: 2 MB/s of compressed samples is nothing for the network, so ingestion is limited by CPU and memory per series and not by bandwidth. The head is the expensive part, so series count (cardinality) sets the machine count. And the read load is steady and repetitive: rules and dashboards repeat the same queries, so caching and splitting pay off. The 2 bytes per sample comes from a measured mix in the time-series lesson; a fleet of noisy floats would need four times as much.
- body
- a batch of series, each with its labels and samples [(timestamp, value)], compressed
- note
- the tenant comes from the credential, and every limit is per tenant
- 202accepted. Resending a batch is safe: samples that are already stored change nothing
- 400some samples rejected (out of order, too old, conflicting value, too far in the future), with counts per reason. The agent drops these and does not retry them
- 429over the tenant's limits (active series, samples a second), with Retry-After. 5xx: retry with backoff
- note
- the step and the range choose the resolution that is read (raw, 5-minute or 1-hour rollups). Limits apply to series, samples and range per query
- 200returns, for each matching series, its labels and a list of (timestamp, value) points at the step
Alert rules are written as groups (name, interval, and a list of rules with an expression, a for duration, labels and annotations) through a rules API. The rest of the contract is conventions: labels name series and are not free text, timestamps come from the producer, and every limit is a visible number with a visible error.
The write path runs along the top. Agents on every host scrape local targets and push batches. Distributors are stateless: they authenticate the tenant, enforce limits, check labels and send each series to the three ingesters that the hash ring assigns to it. An ingester appends to its write-ahead log, adds the sample to the in-memory head and, every two hours, cuts a block and uploads it to object storage. A compactor merges blocks, removes duplicate replicas, downsamples and enforces retention. The read path runs along the middle. A query frontend splits and caches queries, and queriers read recent samples from ingesters and old ones through store gateways that serve the blocks, merge the results and drop the duplicates that replication created. The bottom row is alerting: a ruler evaluates rules by querying and hands alerts to Alertmanager, which groups them and reaches a person. This split (a write path, a read path and a separate alerting path that share storage) follows the open-source Cortex, Mimir and Thanos family. Monarch, Google's system, also separates ingestion, interactive queries and standing queries, and keeps recent data in memory in regional zones.
| Component | Job | State | Scales by |
|---|---|---|---|
| Distributors | Authenticate, limit, validate, shard and replicate writes | None | Adding instances behind a load balancer |
| Ingesters | Log, head, flush blocks | Yes: head and log, rebuilt from the log | Series, through the hash ring |
| Block storage | Hold blocks for retention | Yes: durable object storage | Capacity, effectively unlimited |
| Store gateways, queriers, query frontend | Answer queries | Caches only | Query load |
| Ruler | Evaluate rules | Rule state, restorable | Rule groups, through a ring |
| Alertmanager | Dedupe, group, inhibit, route | Silences and a notification log, replicated | A small cluster |
| Pull: the server scrapes targets | Push: agents send to the server | |
|---|---|---|
| Discovery | The server needs service discovery to know the targets | Agents know where the server is, and no discovery is needed centrally |
| Health | A failed scrape is itself a signal (up is 0), so dead and idle differ | Silence is ambiguous: dead or idle? Needs heartbeats |
| Short-lived jobs | Often finished before a scrape, so a gateway is needed | A natural fit |
| Firewalls | The server must reach every target | Agents only dial out |
| Control | The server sets interval and rate, and a target can be inspected with a browser | Clients set the volume, and a buggy client can flood |
Large systems combine them: an agent on each host scrapes its local targets, which keeps the pull semantics (a failed scrape is data) where they are cheap, and pushes batches to the central write path, which crosses firewalls and scales as stateless receivers. The agent keeps a bounded queue on disk, so a network outage becomes a delay and not a gap.
Sharding by series. A distributor hashes each series' sorted label set to a 64-bit series id and places it on a hash ring of ingesters, exactly like the distributed cache. Sharding by series spreads load evenly, because the most popular metric name may hold a million series that spread across every ingester, where sharding by metric name or by host would create hot spots. The price is that a query for one metric must ask every ingester, which the block indexes and the frontend's caching make acceptable.
Replication across zones. Each series goes to three ingesters in three different zones, and a write succeeds when two acknowledge it. Losing an ingester, or a whole zone, leaves two of three replicas, so writes continue and readers merge and deduplicate what comes back. A returning ingester replays its log and catches up through normal ingestion. Some designs put a durable log such as Kafka between the distributors and the ingesters, so that the write path only appends and ingesters consume at their own pace. That decouples write availability from ingester health, and it costs another system and some latency.
Back-pressure and what to drop. The monitoring system must never take production down with it, so everything is bounded. Agents queue to a size and then drop the oldest data, counting what they drop. Distributors answer 429 with Retry-After when a tenant is over its limits. After an outage the agents hold a backlog, and replaying it all at once would flood the ingesters, so catch-up is rate-limited and the freshest data goes first: it is better to lose ten minutes of old samples than to delay the present.
Appends must be idempotent. The network offers at-least-once delivery, so a batch may arrive twice, or once after a timeout the sender cannot distinguish from a loss, and with three replicas a retry reaches some replicas that already have the data. The head therefore decides each sample on its own: it is accepted if it extends its series in time order, ignored if it repeats the last sample, and rejected, with a reason, if it conflicts, comes out of order, is older than the window the head still holds or lies too far in the future. A rejection that a retry cannot fix is a permanent error that the agent must drop, so that one bad sample cannot block a queue.
C# · AddResult, Head
using System;
using System.Collections.Generic;
using System.Linq;
public enum AddResult { Accepted, Duplicate, OutOfOrder, Conflict, TooOld, Future }
// The in-memory head of a series store. A sample is accepted only if it extends its series in time order and falls inside
// the window the head still holds. Everything else is rejected with a reason, so retries and late data are harmless.
public sealed class Head
{
private readonly Dictionary<string, List<(long Time, double Value)>> series = new Dictionary<string, List<(long, double)>>();
private readonly long maxFuture; // clock skew tolerated, in seconds
public long MinValidTime { get; private set; } // samples older than this belong to a block that was already cut
public Dictionary<AddResult, int> Outcomes { get; } = new Dictionary<AddResult, int>();
public Head(long maxFutureSeconds) { maxFuture = maxFutureSeconds; }
public int SampleCount => series.Values.Sum(s => s.Count);
public AddResult Add(string seriesKey, long time, double value, long now)
{
var result = Decide(seriesKey, time, value, now);
Outcomes[result] = Outcomes.GetValueOrDefault(result) + 1;
return result;
}
private AddResult Decide(string seriesKey, long time, double value, long now)
{
if (time > now + maxFuture) return AddResult.Future;
if (time < MinValidTime) return AddResult.TooOld;
if (!series.TryGetValue(seriesKey, out var samples)) series[seriesKey] = samples = new List<(long, double)>();
if (samples.Count > 0)
{
var last = samples[samples.Count - 1];
if (time == last.Time) return value.Equals(last.Value) ? AddResult.Duplicate : AddResult.Conflict; // a retry is fine, a different value is not
if (time < last.Time) return AddResult.OutOfOrder; // a compressed chunk can only be appended to
}
samples.Add((time, value));
return AddResult.Accepted;
}
// Cut a block: samples before `cutoff` leave the head (a real system writes them to storage) and the valid window moves up.
public int Cut(long cutoff)
{
int removed = 0;
foreach (var samples in series.Values) removed += samples.RemoveAll(s => s.Time < cutoff);
MinValidTime = cutoff;
return removed;
}
// A fingerprint of the whole content, to compare two heads.
public string Fingerprint() => string.Join("|", series.OrderBy(s => s.Key).Select(s => s.Key + ":" + string.Join(",", s.Value.Select(v => v.Time + "=" + v.Value))));
}C# · An agent sends 10 series of 100 samples each. The reply is lost, so it sends the whole…
using System;
using System.Diagnostics;
using System.Linq;
// An agent sends 10 series of 100 samples each. The reply is lost, so it sends the whole batch again.
var batch = (from s in Enumerable.Range(0, 10) from i in Enumerable.Range(0, 100) select ("cpu{host=h" + s + "}", 1_700_000_000L + i * 10L, (double)(s * 100 + i))).ToList();
var head = new Head(maxFutureSeconds: 60);
long now = 1_700_001_000;
foreach (var (key, time, value) in batch) head.Add(key, time, value, now);
string afterFirstSend = head.Fingerprint();
foreach (var (key, time, value) in batch) head.Add(key, time, value, now); // the retry
Debug.Assert(head.Fingerprint() == afterFirstSend && head.SampleCount == 1_000); // retrying changed nothing
Debug.Assert(head.Outcomes[AddResult.Accepted] == 1_000 && head.Outcomes[AddResult.Duplicate] == 10 && head.Outcomes[AddResult.OutOfOrder] == 990);
// A different value at the time of the last sample is a conflict, an older time is out of order, and a bad clock is refused.
Debug.Assert(head.Add("cpu{host=h0}", 1_700_000_990L, 1, now) == AddResult.Conflict);
Debug.Assert(head.Add("cpu{host=h0}", 1_700_000_005L, 1, now) == AddResult.OutOfOrder);
Debug.Assert(head.Add("cpu{host=h0}", now + 3_600, 1, now) == AddResult.Future);
// After a block is cut, older samples are too old, and newer ones are still accepted.
Debug.Assert(head.Cut(1_700_000_500) == 500 && head.SampleCount == 500);
Debug.Assert(head.Add("cpu{host=h0}", 1_700_000_400L, 1, now) == AddResult.TooOld);
Debug.Assert(head.Add("cpu{host=h0}", 1_700_001_000L, 1, now) == AddResult.Accepted);The retry delivered 1,000 samples again and changed nothing: ten were recognised as duplicates (the last sample of each series), and 990 were refused as out of order, because a compressed chunk can only be appended to. That is the honest limit of an append-only head, and it is enough, since the agent drops those as permanent rejections, and the store holds each sample exactly once.
A query enters the query frontend, which does the work that makes the rest cheap: it splits a seven-day range query into one-day pieces aligned to the step, so that repeated and overlapping queries hit a results cache; it queues requests per tenant with fair scheduling, so that one heavy dashboard cannot starve the rest; and it retries failed pieces. A querier then chooses its sources by time: recent samples from the ingesters (the head, which is why a fresh sample is visible within seconds), and older ones from store gateways that read blocks from object storage through caches of block indexes and chunks. It merges, drops the duplicate samples that replication created, and evaluates the expression (rate, sum by, quantile).
- Resolution follows the range and the step. A 30-day chart at a one-hour step reads the one-hour rollups, a few hundred points per series, and not 260,000 raw samples. The block's resolution is chosen from the step.
- Recording rules pre-compute expensive aggregations (the request rate summed over a million series) on a schedule and store the result as a new series, which turns a heavy query into a light one at the price of the stored series.
- Limits protect the store. A maximum number of series, samples and time range per query, a timeout, and a per-tenant concurrency cap. One careless query must not take the reads down.
- The 9 a.m. dashboard. A hundred people open the same dashboard, and the frontend's cache and request coalescing answer a hundred identical queries with one execution, the same cure as for the stampede in the cache consistency lesson.
Latency percentiles and "the share of requests under 300 ms" come from histograms: counters of how many requests fell in each bucket. Histograms from many instances are merged by adding their bucket counts, and the percentile is read from the merged histogram, never averaged across instances (the sketches lesson showed the average of p99s was 69% too high). What a histogram cannot do is tell you where inside a bucket the values lie, so a percentile is found by interpolation and its error depends on the bucket layout, which someone has to choose. The sample counts 1,000,000 lognormal latencies into three layouts and compares the estimates with the true values.
C# · 1,000,000 request latencies in ms: lognormal with a median of 80 ms.
using System;
using System.Diagnostics;
using System.Linq;
// 1,000,000 request latencies in ms: lognormal with a median of 80 ms.
var latencyRandom = new Random(31);
double Gauss() => Math.Sqrt(-2 * Math.Log(1 - latencyRandom.NextDouble())) * Math.Cos(2 * Math.PI * latencyRandom.NextDouble());
double[] latencies = Enumerable.Range(0, 1_000_000).Select(_ => 80 * Math.Exp(0.7 * Gauss())).ToArray();
double[] sortedLatencies = latencies.OrderBy(x => x).ToArray();
double TrueQuantile(double q) => sortedLatencies[(int)(q * (sortedLatencies.Length - 1))];
// All a histogram knows is a count per bucket: bucket b holds the values above bounds[b - 1] and up to bounds[b].
long[] CountInto(double[] bounds)
{
var counts = new long[bounds.Length + 1];
foreach (double x in latencies)
{
int b = Array.BinarySearch(bounds, x);
counts[b < 0 ? ~b : b]++;
}
return counts;
}
// A quantile is found by locating the bucket that holds the rank and interpolating linearly inside it, which is what
// Prometheus's histogram_quantile does.
double EstimateQuantile(double q, double[] bounds, long[] counts)
{
double rank = q * latencies.Length;
long below = 0;
for (int b = 0; b < bounds.Length; b++)
{
if (below + counts[b] >= rank)
{
double lower = b == 0 ? 0 : bounds[b - 1];
return lower + (bounds[b] - lower) * (rank - below) / counts[b];
}
below += counts[b];
}
return bounds[^1];
}
// The share of requests at or under a limit, the SLI, interpolated the same way when the limit is not a bucket boundary.
double ShareUnder(double limit, double[] bounds, long[] counts)
{
int b = Array.FindIndex(bounds, x => x >= limit);
long below = counts.Take(b).Sum();
double lower = b == 0 ? 0 : bounds[b - 1];
return (below + counts[b] * (limit - lower) / (bounds[b] - lower)) / latencies.Length;
}
double[] libraryBuckets = { 5, 10, 25, 50, 100, 250, 500, 1_000, 2_500, 5_000, 10_000 }; // a client library's default buckets, in ms
double[] growth25 = Enumerable.Range(0, 40).Select(i => 5 * Math.Pow(1.25, i)).ToArray(); // 40 buckets, each 25% wider
double[] growth2 = Enumerable.Range(0, 400).Select(i => Math.Pow(1.0202, i)).ToArray(); // 400 buckets, each 2% wider
double[] withBoundary = libraryBuckets.Append(300).OrderBy(x => x).ToArray(); // the library's buckets plus one at the 300 ms SLO
double Error(double q, double[] bounds) => (EstimateQuantile(q, bounds, CountInto(bounds)) - TrueQuantile(q)) / TrueQuantile(q);
Debug.Assert(Math.Abs(TrueQuantile(0.99) - 408.7) < 0.1);
Debug.Assert(Math.Abs(Error(0.5, libraryBuckets) - 0.042) < 0.002 && Math.Abs(Error(0.99, libraryBuckets) - 0.152) < 0.002 && Math.Abs(Error(0.999, libraryBuckets) - 0.289) < 0.002);
Debug.Assert(new[] { 0.5, 0.9, 0.99, 0.999 }.All(q => Math.Abs(Error(q, growth25)) < 0.025)); // 40 buckets: within 2.5% everywhere
Debug.Assert(new[] { 0.5, 0.9, 0.99, 0.999 }.All(q => Math.Abs(Error(q, growth2)) < 0.002)); // 400 buckets: within 0.2%
// The SLI "faster than 300 ms": exact when 300 is a bucket boundary, overstating the bad requests by 43% when it is not.
double trueShare = latencies.Count(x => x <= 300) / (double)latencies.Length;
double libraryShare = ShareUnder(300, libraryBuckets, CountInto(libraryBuckets));
double boundaryShare = ShareUnder(300, withBoundary, CountInto(withBoundary));
Debug.Assert(Math.Abs(trueShare - 0.97042) < 0.0001 && Math.Abs(boundaryShare - trueShare) < 1e-9);
Debug.Assert(Math.Abs(libraryShare - 0.95766) < 0.0001);
Debug.Assert(Math.Abs((1 - libraryShare) / (1 - trueShare) - 1.43) < 0.01);| Layout | Buckets | Error at p50 | p90 | p99 | p99.9 |
|---|---|---|---|---|---|
| A client library's default (5 ms to 10 s, uneven) | 11 | +4.2% | +16.2% | +15.2% | +28.9% |
| Each bucket 25% wider than the last | 40 | +0.7% | +1.8% | +1.9% | +2.3% |
| Each bucket 2% wider than the last | 400 | 0.0% | 0.0% | 0.0% | +0.1% |
The default layout puts the p99 of 409 ms in the bucket from 250 to 500 and reports 471. The SLI shows the stakes: with no boundary at 300 ms the histogram says 95.77% of requests were fast enough when the truth is 97.04%, which overstates the bad requests by 43%, and a burn-rate alert built on it fires as if the service were worse than it is. A boundary at the SLO threshold made the SLI exact. The cost is series: in a classic histogram every bucket is a series, so 400 buckets multiplies a metric's cardinality by 400. Hence the compromise, an exponential layout with a modest growth factor (a relative error you can state) plus boundaries at your SLO thresholds, and the newer native or exponential histogram formats and DDSketch, which keep sparse buckets with a fixed relative error in one series per histogram instead of one series per bucket.
A ruler evaluates each rule group on its interval (say every minute) by running the rule's expression against the read path. Rule groups are spread over rulers through a hash ring, so every group has one owner at a time, and rules only need fresh data, so their queries are answered mostly from the ingesters, without reading old blocks. Many systems offer an evaluation delay, so that a rule never sees a minute that is still being ingested and reads a gap as "no data". The result of each evaluation drives a small state machine: the condition must hold for the rule's for duration before the alert fires, so a blip leaves it pending and never pages, and a condition that stops holding resolves it at once. The ruler stores the pending state, or restores it after a restart, so a restart does not reset every timer.
Firing alerts are sent to Alertmanager, which does what turns a stream of alerts into something a person can act on. It deduplicates the alert that every ruler replica resends each interval. It inhibits alerts that a more fundamental one explains (if the cluster is down, do not also page for each of its hosts). It groups the rest by labels, waiting a moment for related alerts to arrive and sending one notification that lists them. Then it routes by label to a receiver (pager, chat, email, webhook), with retries, silences and reminder intervals, and the delivery itself is the problem of the notification service. Alertmanager runs as a small cluster whose members share a notification log, so that one of them sends and the others see that it did.
C# · RuleState, AlertRule, Alert, …
using System;
using System.Collections.Generic;
using System.Linq;
public enum RuleState { Inactive, Pending, Firing }
// One alert rule's state machine. The condition must hold for `forMinutes` in a row before the alert fires, so a blip never pages.
public sealed class AlertRule
{
private readonly int forMinutes;
private int pendingSince = -1;
public RuleState State { get; private set; } = RuleState.Inactive;
public AlertRule(int forMinutes) { this.forMinutes = forMinutes; }
// Called once per evaluation interval (one minute here) with the result of the rule's query.
public RuleState Evaluate(int minute, bool conditionHolds)
{
if (!conditionHolds)
{
pendingSince = -1;
State = RuleState.Inactive; // resolved, or never fired
}
else
{
if (pendingSince < 0) pendingSince = minute;
State = minute - pendingSince >= forMinutes ? RuleState.Firing : RuleState.Pending;
}
return State;
}
}
public sealed record Alert(string Name, Dictionary<string, string> Labels)
{
public string Label(string name) => Labels.TryGetValue(name, out var value) ? value : "";
}
// While a source alert fires, mute the target alerts that have the same values for the `Equal` labels.
public sealed record InhibitRule(string SourceName, string TargetName, string[] Equal);
public static class Notifier
{
// The notifications that go out for a set of firing alerts: inhibited alerts are dropped, the rest are grouped by the
// `groupBy` labels, and each group becomes one notification that lists all its alerts.
public static List<(string Group, int Alerts)> Notifications(List<Alert> firing, string[] groupBy, InhibitRule[] inhibit)
{
var active = firing.Where(a => !inhibit.Any(r =>
a.Name == r.TargetName && firing.Any(s => s.Name == r.SourceName && r.Equal.All(l => s.Label(l) == a.Label(l))))).ToList();
return active
.GroupBy(a => string.Join("/", groupBy.Select(l => l == "alertname" ? a.Name : a.Label(l))))
.OrderBy(g => g.Key)
.Select(g => (g.Key, g.Count()))
.ToList();
}
}The test runs the state machine over three conditions, and then fails a whole cluster: 300 hosts down, 150 services slow, one alert that notices the cluster is down, and one unrelated alert in another cluster.
C# · The `for` clause (5 minutes here): '#' means the condition holds in that minute, '.'…
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
// The `for` clause (5 minutes here): '#' means the condition holds in that minute, '.' means it does not.
List<RuleState> Run(int forMinutes, string pattern)
{
var rule = new AlertRule(forMinutes);
return pattern.Select((c, minute) => rule.Evaluate(minute, c == '#')).ToList();
}
Debug.Assert(!Run(5, "###..###..###..").Contains(RuleState.Firing)); // blips of three minutes never fire
var sustained = Run(5, "..#########..");
Debug.Assert(sustained.FindIndex(s => s == RuleState.Firing) == 7); // pending from minute 2, firing once it has held for 5
Debug.Assert(sustained[11] == RuleState.Inactive); // resolved as soon as the condition stops holding
// A cluster fails: 300 hosts down, 150 services slow, one rule that notices the whole cluster is down, and one unrelated alert.
var firingAlerts = new List<Alert>();
for (int host = 0; host < 300; host++) firingAlerts.Add(new Alert("InstanceDown", new Dictionary<string, string> { ["cluster"] = "eu1", ["instance"] = "host-" + host }));
for (int service = 0; service < 150; service++) firingAlerts.Add(new Alert("HighLatency", new Dictionary<string, string> { ["cluster"] = "eu1", ["service"] = "svc" + service }));
firingAlerts.Add(new Alert("ClusterDown", new Dictionary<string, string> { ["cluster"] = "eu1" }));
firingAlerts.Add(new Alert("HighLatency", new Dictionary<string, string> { ["cluster"] = "us2", ["service"] = "svc9" }));
var inhibitRules = new[] { new InhibitRule("ClusterDown", "InstanceDown", new[] { "cluster" }), new InhibitRule("ClusterDown", "HighLatency", new[] { "cluster" }) };
Debug.Assert(firingAlerts.Count == 452); // 452 alerts, so 452 pages if each were sent on its own
var grouped = Notifier.Notifications(firingAlerts, new[] { "alertname", "cluster" }, Array.Empty<InhibitRule>());
Debug.Assert(grouped.Count == 4);
Debug.Assert(grouped.Select(g => g.Group + "=" + g.Alerts).SequenceEqual(new[] { "ClusterDown/eu1=1", "HighLatency/eu1=150", "HighLatency/us2=1", "InstanceDown/eu1=300" }));
var inhibited = Notifier.Notifications(firingAlerts, new[] { "alertname", "cluster" }, inhibitRules);
Debug.Assert(inhibited.Select(g => g.Group + "=" + g.Alerts).SequenceEqual(new[] { "ClusterDown/eu1=1", "HighLatency/us2=1" }));A three-minute blip never leaves the pending state, a sustained failure fires after five minutes, and it resolves the minute the condition ends. The cluster failure produced 452 alerts. Grouping by alert name and cluster turned them into 4 notifications, and inhibition by the cluster-level alert left 2: the cause, and the unrelated alert that should not be hidden. That is the difference between a pager that is useful in an outage and one that is unusable. Two more points complete it:
- Page on symptoms. The rules that page are SLO burn-rate rules (see SLOs and alerting), and the cause alerts exist to be inhibited, or to explain a page.
- Watch the watchers. A heartbeat rule that always fires goes through the whole path to an external service that pages when the heartbeat stops. And an independent black-box probe from outside the system's own failure domain tells you when the monitoring itself is down.
Volume is predictable, cardinality is not: one deploy that adds a label with unbounded values can multiply a tenant's series by a thousand in minutes (the observability lesson has the arithmetic). The defences work at three points.
- At the door. Per-tenant limits on active series, samples a second, labels per series and label length, enforced by the distributors with a 429 and a clear message that names the metric. Reject the new series that exceed the limit and keep accepting samples for the existing ones, so that the tenant loses the new data and not everything.
- By detection. A top-N report of metrics and labels by series count from the index. Counting distinct series per metric exactly costs memory, so an approximate counter such as HyperLogLog (see the sketches lesson) is enough to spot a runaway metric early.
- By isolation. Give each tenant a subset of the ingesters and queriers, a shuffle shard, so that a tenant that blows its limits or runs a query of death affects only the nodes it was given, and other tenants' subsets mostly do not overlap with it. Charge the cost of series to the owning team, and the labels get reviewed.
| Failure | What happens | Defence |
|---|---|---|
| An ingester dies | Its replicas keep serving, and its head is rebuilt from the log | Three replicas in three zones, quorum of two, log replay, the ring marks it unhealthy |
| A whole zone is lost | Writes continue at two of three replicas | Zone-aware replication |
| Backlog flood after an outage | Agents resend everything at once and the ingesters saturate | Per-tenant rate limits, rate-limited catch-up, fresh data first, drop what is too old |
| Cardinality explosion | Head memory and index grow until an ingester runs out of memory | Limits at the distributor, drop the label at the agent, shuffle sharding to contain it |
| An expensive query | One query starves the rest | Per-tenant queues and concurrency, limits on series, samples and range, timeouts |
| The 9 a.m. dashboard | Thousands of identical queries at once | Step-aligned splitting, a results cache, request coalescing |
| Late or skewed data | Out-of-order rejections, or future timestamps poisoning the head | A bounded out-of-order window, reject beyond a clock tolerance, count rejections |
| Object storage unavailable | Ingesters cannot flush, so heads grow, and old queries fail | Heads sized for hours of delay, alerts on flush lag, recent queries still served |
| The alert path fails silently | Nothing pages during an outage | A heartbeat that must always arrive, an independent Alertmanager cluster, external probes |
| The monitor depends on what it monitors | An outage in the shared network or cluster blinds the monitoring | A separate failure domain for the monitoring, and black-box probes from outside |
Interviewer follow-upL5Should the system pull or push metrics?How to answer
Pull gives free health information (a failed scrape is a signal), central control of rate, and easy debugging, but needs service discovery and reach into every network and misses short-lived jobs. Push crosses firewalls, suits short-lived jobs and scales as stateless receivers, but silence is ambiguous and clients control the volume. The usual answer is both: a local agent scrapes its host and pushes to the central write path, with a bounded disk queue.
Interviewer follow-upL5How do you keep storage small at a million samples a second?How to answer
Compress each series (delta-of-delta timestamps and XORed values, about 2 bytes a sample for a typical mix, 128 bits raw), keep recent data in memory with a log, cut immutable blocks that compaction merges, and roll old data up into sums, counts, minima and maxima at five-minute and one-hour resolution while dropping the raw data after weeks. Estimate it: 86 billion samples a day at 2 bytes is 173 GB a day.
Interviewer follow-upL6A tenant's cardinality explodes and the ingesters start running out of memory. What do you do?How to answer
First stop the growth: enforce the tenant's series limit at the distributors, which rejects new series with a clear error while existing ones keep working. Find the metric and label from the top-series report and drop or aggregate the label at the agents. Contain the damage with shuffle sharding so that other tenants' ingesters were never in play, add ingesters if memory is short, and recover by letting the runaway series age out of the head. Then add a label review and a per-team series budget.
Interviewer follow-upL6The monitoring system is part of the infrastructure that is failing. How do you still get paged?How to answer
Put the alert path in a separate failure domain (another region or account, no shared network or identity system with production), keep the rule evaluation on recent data in the ingesters so object storage is not needed, and run a heartbeat alert that always fires and is watched by an external service that pages when it stops. Add black-box probes from outside, a runbook for when the monitoring itself is down, and page on symptoms so that a partial failure still trips the rule.
Interviewer follow-upL6How accurate is a p99 from histogram buckets?How to answer
As accurate as the layout allows, because the estimate is interpolated inside a bucket. In the test the default client buckets gave a p99 of 471 ms against the true 409 (+15%), a layout with each bucket 25% wider gave +1.9%, and each bucket 2% wider gave 0.0%. Choose an exponential layout with a stated relative error, add a boundary at each SLO threshold so the SLI is exact (otherwise the bad requests were overstated by 43%), and remember that cardinality grows with the bucket count unless the format stores sparse buckets.
Interviewer follow-upL7How would you serve 13 months of history cheaply and still answer queries quickly?How to answer
Keep it as blocks in object storage, compacted into large blocks with their own indexes, and downsampled into five-minute and one-hour rollups of sum, count, min, max and counter increase (about 9 TB for 13 months in the estimate, against 2.6 TB for 15 days of raw data). Queries choose the resolution from range and step, store gateways cache index headers and hot chunks, and the query frontend splits by day and caches results. Recording rules cover the dashboards that are expensive at any resolution, and retention tiers by tenant control the bill.
- Clarify and size. Series, interval, tenants, freshness, retention. Say "ten million series, a million samples a second, about 2 bytes a sample".
- The shape. Write-heavy, append-only, recent and repetitive reads, old data summarised. Say the design follows from it.
- Write path. Agents, distributors, a hash ring by series, three zone-aware replicas with a quorum, a log and a head, blocks to object storage, idempotent appends and bounded back-pressure.
- Read path. Query frontend, queriers, store gateways, resolution by range, recording rules, limits.
- Percentiles. Histograms merged by adding buckets, the layout chosen for its error, a boundary at each SLO.
- Alerting. A ruler with a pending state, then dedupe, inhibit, group and route, with a heartbeat on the path.
- Cardinality and tenants. Limits, detection, shuffle sharding.
- Failure. The monitor must outlive the incident: independent failure domain, external probes.
A metrics system is a write-heavy time-series store with an inverted index over labels. For ten million series at ten seconds it takes a million samples a second, about 2 MB/s and 173 GB a day compressed, with a head of about 75 GB across three replicas. Distributors shard each series by hash to three ingesters in three zones with a quorum of two, each ingester appends to a log and an in-memory head and cuts blocks to object storage, and a compactor merges and downsamples them. Appends are idempotent: in the test a retried batch of 1,000 samples left the head unchanged, with 10 duplicates and 990 out-of-order rejections. Queries pass through a frontend that splits, caches and limits, and queriers merge ingester and block data and drop replica duplicates. Percentiles come from merged histograms whose bucket layout sets the error (a client library's defaults were 15% off at p99, a 2%-wide layout 0.0%, and a missing boundary at the SLO overstated bad requests by 43%). Alert rules have a pending state, and Alertmanager dedupes, inhibits and groups: 452 alerts became 4 notifications and 2 with inhibition. Cardinality is bounded by limits, detection and shuffle sharding, and the whole system has to survive the incident it detects, with an independent alert path and a heartbeat.
Try answering out loud before you reveal each answer.
QuestionSize the head of a metrics system with ten million series sampled every ten seconds, two hours of data in memory, 2 bytes a sample and 1 KB of overhead a series.Reveal answer
A million samples a second for 7,200 seconds is 7.2 billion samples, 14.4 GB at 2 bytes. The series overhead is 10 million × 1 KB = 10 GB. That is about 24 GB, or about 75 GB with three replicas, which is why cardinality (series), and not the sample rate, decides how many ingesters you need.
QuestionAn agent's batch times out and it sends the same batch again. What stops duplicates and corruption, and what does the agent do with the rejections?Reveal answer
The head accepts a sample only if it extends its series in order, ignores a repeat of the last sample, and rejects the rest with a reason, so the second send changes nothing: in the test 10 duplicates and 990 out-of-order rejections and an identical head. The rejections are permanent, so the agent drops them. Only overload (429) and server errors are retried with backoff.
QuestionWhy shard ingestion by a hash of the series and not by metric name?Reveal answer
One metric name (an HTTP request counter) can have a million series, and sharding by name puts all of them, and all their traffic, on one node. Hashing each series spreads them evenly. The price is that a query for one metric has to ask every ingester, which the block indexes and the frontend's caching make acceptable.
QuestionA dashboard computes a 99th percentile from histogram buckets and jumps around by 15%. What do you change?Reveal answer
The bucket layout. The estimate is interpolated inside a bucket, so wide uneven buckets give large errors (+15% at p99 for the library defaults, +1.9% for buckets 25% wider than each other). Use an exponential layout with a relative error you can state, put a boundary at each SLO threshold, and consider an exponential or native histogram format so that finer buckets do not multiply the series.
QuestionA cluster fails and 452 alerts fire. How many pages should go out, and how do you get there?Reveal answer
Ideally one or two. Group by alert name and cluster, which turned 452 alerts into 4 notifications, and add an inhibition rule so that the cluster-down alert suppresses the instance and latency alerts of that cluster, which left 2: the cause, and the unrelated alert in another cluster. Page on symptoms such as SLO burn so that the cause alerts only explain.
- Tuomas Pelkonen and others, Gorilla: A Fast, Scalable, In-Memory Time Series Database (opens in a new tab), VLDB 2015, and Colin Adams and others, Monarch: Google's Planet-Scale In-Memory Time Series Database (opens in a new tab), VLDB 2020: the two production designs behind the shape described here.
- Grafana Labs, Mimir architecture (opens in a new tab): distributors, ingesters, the query frontend, queriers, store gateways, the compactor, the ruler and Alertmanager, in one open-source system.
- Prometheus, Storage (opens in a new tab) and Alertmanager (opens in a new tab): the head and blocks, and grouping, inhibition, silences and routing.
- Amazon Web Services, Workload isolation using shuffle-sharding (opens in a new tab), Amazon Builders' Library: limiting the blast radius of one tenant.
- Beyer, Jones, Petoff and Murphy (eds.), Site Reliability Engineering, O'Reilly, 2016, chapter Monitoring Distributed Systems (opens in a new tab): what makes a good page, and why monitoring must be simple enough to trust.