Courses / System Design Interview / Chapter 43
Module 9 · Design Problems IV: Platforms and Money · Chapter 43 of 49
Design a Metrics Monitoring and Alerting System
Builds on Back-of-the-Envelope Estimates, Design a Distributed Key-Value Store, Distributed Monitoring: Metrics, Logs and Traces and Monitoring Server-Side Errors. Next up: Design a Chat Assistant like ChatGPT.
Part 1 · Requirements and estimates
What the system must do
A metrics system turns the numbers that servers report into charts and, when something breaks, into a message to a person. Both jobs depend on the same stream of samples, and both are needed at the moment when everything else is failing.
The functional requirements are these. Services and machines expose numbers, and the system collects them regularly and stores them as time series. People query a series over a range and see it on a dashboard. Engineers write alert rules, and when a rule's condition holds, the right team is notified, once, not hundreds of times. People can mute an alert for a while, for example during planned maintenance. Old data is kept at a coarser resolution than new data. The monitoring chapter and the server errors chapter covered what to measure and how to choose alert conditions. This chapter designs the system that stores the numbers and runs the rules.
The non-functional requirements are unusual because the system watches everything else. It must be more available than the services it watches, or it fails exactly when it is needed. It must keep accepting samples at a steady, high rate. Queries must be fast enough for a person looking at a dashboard during an incident. An alert must reach a person within a minute or two of the condition becoming true, and a failure of the system must not silently stop alerts. And storage must stay affordable, because the data grows with every series and every second.
Sizing the system
The assumptions are 4,000 machines exposing 150 series each, 1,500 service instances exposing 500 series each, one sample per series every 15 seconds, and 15 days of retention. We keep 3,000 alert rules, each evaluated once a minute, and 400 people with a dashboard open, each sending a query every 30 seconds. The disk figure uses the formula in the Prometheus storage documentation, retention in seconds times samples ingested per second times bytes per sample. The same page says Prometheus averages only 1 to 2 bytes per sample, so we use 2 as a careful assumption and 16, an 8-byte timestamp and an 8-byte value, for the uncompressed case.
import sys # Assumptions, each a named line. hosts = 4_000 # machines that expose metrics # processor, memory, disk and network series series_per_host = 150 services = 1_500 # service instances # request counts, latency buckets, errors series_per_service = 500 scrape_s = 15 # seconds between samples of one series retention_days = 15 # an 8-byte timestamp and an 8-byte value bytes_raw = 16 # an assumption: the top of "1 to 2 bytes" bytes_packed = 2 rules = 3_000 # alert rules, one evaluation a minute # people with a dashboard open, 1 query per 30 s dashboards_open = 400
Python 3.12.10. Run: uv run --python 3.12 metrics_load.py. Part 1 of 2; save all parts in one file, metrics_load.py.
series = hosts * series_per_host + services * series_per_service samples_s = series / scrape_s per_day = samples_s * 86_400 total = per_day * retention_days print(sys.version.split()[0]) print(f"active series : {series:,.0f}") print(f"samples per second : {samples_s:,.0f}") print(f"samples per day : {per_day / 1e7:,.1f} crore") print(f"disk, 16 bytes a sample : {total * bytes_raw / 1e12:,.2f} TB") packed_gb = total * bytes_packed / 1e9 print(f"disk, 2 bytes a sample : {packed_gb:,.0f} GB") print(f"rule evaluations : {rules / 60:,.0f} per second") dash = dashboards_open / 30 print(f"dashboard queries : {dash:,.0f} per second") # the same arithmetic for the one million series on the scene one_m = 1_000_000 s = one_m / scrape_s print() print(f"1 M series, samples/s : {s:,.0f}") day_gb = s * 86_400 * bytes_packed / 1e9 print(f"1 M series, a day : {day_gb:,.1f} GB") print(f"1 M series, {retention_days} days : " f"{s * 86_400 * retention_days * bytes_packed / 1e9:,.0f} GB")
Continues metrics_load.py (part 2 of 2), same file.
3.12.10 active series : 1,350,000 samples per second : 90,000 samples per day : 777.6 crore disk, 16 bytes a sample : 1.87 TB disk, 2 bytes a sample : 233 GB rule evaluations : 50 per second dashboard queries : 13 per second 1 M series, samples/s : 66,667 1 M series, a day : 11.5 GB 1 M series, 15 days : 173 GB
Output of the script.
What the numbers decide
There are 13.5 lakh active series, and since each is sampled every 15 seconds the system ingests 90,000 samples a second, or 777.6 crore a day. That is a steady write load with no peaks to speak of, because collectors scrape on a timer. It is write-heavy, and the writes are tiny appends. Reads are small by comparison: 50 rule evaluations and about 13 dashboard queries a second.
| Number | What it decides |
|---|---|
| 90,000 samples a second | Writes spread over several ingesters, sharded by series |
| 1.87 TB raw, 233 GB packed | Compression is not optional: it divides the disk bill by about 8 |
| 50 rule evaluations a second | Alerting is a small, separate workload |
| 13 dashboard queries a second | Queries can run against the same store as long as writes are isolated |
Disk at 16 bytes a sample: ≈ 1.4 TB (compression is worth about 8 times)
Read it as steps
10 lakh series sampled every 15 seconds need about 173 GB for 15 days at two bytes a sample.
The estimate scene repeats the arithmetic for a round 10 lakh series. It adds nothing new: 66,667 samples a second, 13 lakh seconds in 15 days and 2 bytes a sample give 173 GB. The point is how much depends on the one assumption about bytes per sample, which is why the fourth lesson measures it on data of our own instead of trusting a figure.
Part 2 · Data model: series, labels and cardinality
Series, samples and labels
The monitoring chapter introduced time series and labels. This lesson makes them exact. In the Prometheus data model a sample is one point: a 64-bit floating point value and a timestamp in milliseconds. A label such as route="/login" or status="500" splits one metric into many series, and a series is the stream of samples for one metric name and one set of labels.
The identity of a series is its metric name plus its full set of labels. Change one label's value, or add or remove a label, and it is a different series. The data model page lists some rules for names. Metric names should match [a-zA-Z_:][a-zA-Z0-9_:]*, label names should match [a-zA-Z_][a-zA-Z0-9_]*, names outside those patterns need quoting in queries, and label names that begin with two underscores are reserved for internal use. A label with an empty value counts as if the label did not exist. Our store is stricter than that page on purpose. It accepts only those patterns and refuses a label value of more than 128 characters, our own limit, so a bad name or a huge value is refused when the sample arrives and does not corrupt an index or fill memory later.
Labels are what make metrics useful. A single counter of requests becomes a count per route, per status, per instance. A query can add the series together across instances, or pick out only the 500s. The price is that every distinct combination of label values is stored as its own series with its own samples.
Cardinality
Cardinality is the number of distinct series a metric has. It is the product of the number of values of each label, counting only combinations that occur. A request counter with 4 methods, 5 statuses and 50 routes has at most 1,000 series. Add an instance label for 200 servers and it has up to 2 lakh. Add a user_id label for 1 lakh users and the upper bound is 2,000 crore, which no store should be asked to hold.
The Prometheus guidance on naming says exactly this: every unique combination of label pairs is a new series, which can dramatically increase the data stored, and labels must not hold dimensions with high cardinality, such as user ids or email addresses. The cost of the mistake is not linear. One engineer adding one label to one metric can multiply the series count of the whole system, and the first sign is a full disk or an ingester out of memory.
| Label | Distinct values | Safe as a label? |
|---|---|---|
| method, status | A handful | Yes: a small, fixed set |
| route | Tens to hundreds | Yes, if routes are templates like /users/:id and not real paths |
| instance | Hundreds to thousands | Yes; it is the dimension you aggregate over |
| user_id, session id, request id | Lakhs or unbounded | No: put it in a log or a trace |
The defences are of three kinds. Review: labels are part of the review of the code that emits metrics. Limits: the store caps the series a metric may have and counts what it drops, so a bad deploy hurts one metric and not the system. And visibility: a dashboard of series per metric makes the next explosion easy to find. The script below tests the second defence and measures what series cost.
Counting series, in code
The Store keeps the newest sample of each series. Keeping only the newest sample lets the script measure the cost of the series themselves, apart from the samples. It refuses bad metric and label names, long label values and samples that are not numbers, treats empty values as absent, makes label order irrelevant, refuses a sample older than the one it holds and stops creating series for a metric past a limit. The script then sends 10 lakh requests twice, once with labels route only and once with a random user id added, and measures with tracemalloc how much memory the in-process index takes.
import random, re, sys, tracemalloc NAME = re.compile(r"[a-zA-Z_][a-zA-Z0-9_]*") METRIC = re.compile(r"[a-zA-Z_:][a-zA-Z0-9_:]*") MAX_VALUE = 128 # longest label value we accept class Store: """Maps a series (name plus labels) to its newest sample. Refuses bad names; stops creating series past a limit.""" def __init__(self, limit_per_metric): self.limit, self.series, self.dropped = limit_per_metric, {}, 0 self.count, self.late = {}, 0 def key(self, name, labels): if not (isinstance(name, str) and METRIC.fullmatch(name)): raise ValueError(f"bad metric name {name!r}") clean = {} for k, v in labels.items(): if (not (isinstance(k, str) and NAME.fullmatch(k)) or k.startswith("__")): raise ValueError(f"bad label name {k!r}") v = str(v) if len(v) > MAX_VALUE: raise ValueError(f"label value over {MAX_VALUE} chars") # empty value equals no label if v != "": clean[k] = v return name, tuple(sorted(clean.items()))
Python 3.12.10. Run: uv run --python 3.12 cardinality.py. Part 1 of 4; save all parts in one file, cardinality.py.
def add(self, name, labels, t, value): key = self.key(name, labels) if (type(t) is not int or isinstance(value, bool) or not isinstance(value, (int, float))): raise ValueError("bad time or value") old = self.series.get(key) if old is None: if self.count.get(name, 0) >= self.limit: self.dropped += 1 return False self.count[name] = self.count.get(name, 0) + 1 elif t < old[0]: self.late += 1 # older than what we hold return False # keep only the newest sample: we measure the cost of series self.series[key] = (t, value) return True rng = random.Random(3) methods = ["GET", "POST", "PUT", "DELETE"] statuses = ["200", "400", "404", "500", "503"] routes = [f"/r{i}" for i in range(50)] print(sys.version.split()[0]) print("possible series for http_requests_total") n = len(methods) * len(statuses) * len(routes) print(f" method x status x route : {n:,}") print(f" add instance (200 servers) : {n * 200:,}") with_users = n * 200 * 100_000 print(f" add user_id (1,00,000 users) : {with_users:,}")
Continues cardinality.py (part 2 of 4), same file.
Reading the run
The possible series grow from 1,000 to 2 lakh to 2,000 crore as labels are added, which is arithmetic. The measured part is the second block. With the route label alone, 10 lakh requests create 50 series. With a user id added, the same 10 lakh requests create 9,06,308 series, almost one new series per request, because most users appear once. The toy index then holds 366 MB, or 404 bytes per series, in this Python process. A real time series database uses its memory differently, so the number is only a way to feel the cost. It shows what matters: memory follows the number of series, not the number of requests.
The limit works as intended. With a limit of 1,000 series, the first 1,000 user ids are stored and the other 4,000 are dropped and counted, so the metric stops growing and the system tells someone it is dropping. The four bad label names are refused: one with a hyphen, one starting with a digit, a reserved double-underscore name and one with a space. An empty label equals no label, and label order does not change the series, so a program that adds labels in a different order does not create a second series by accident.
The last block feeds the store bad input. A sample older than the one held is refused and counted, because the store keeps only the newest. Not-a-number and infinity are valid floating point values, so they are stored. A metric name with a space or a leading digit, a label name with a trailing newline, a label value of 10 lakh characters, text in place of a number and a fractional time are each refused. The label-name pattern is matched in full: an earlier version used match with a closing $, and that lets a trailing newline through.
A developer adds a customer id label to a latency histogram. What happens and what stops it?
- Every distinct customer creates new series for every histogram bucket, so series and memory grow with the customer count. A review rule, a per-metric series limit and a series-per-metric dashboard all catch it.
Why does an empty label value count as no label?
- So a program that sometimes sets a label to an empty string does not create a second series for the same thing. The run shows the two give the same key.
Part 3 · High-level design
The parts
The design has a write path that never stops and a read path that runs on timers. The monitoring chapter explained pull and push collection, and this design pulls: collectors scrape the servers on a timer, which also tells us when a server stops answering. The collectors are many, so the scraping load is spread, and each one forwards samples to the store.
| Part | Owns | State |
|---|---|---|
| Collectors | Scrape targets on a schedule, attach labels, forward samples | Which targets they own; little else |
| Ingesters | Accept samples for the series they own, keep recent ones in memory and in a log | Recent data, replicated on two ingesters |
| Time-series store | Blocks of older samples on disk, queries over ranges | Durable, compacted over time |
| Rule evaluator | Runs alert and recording rules on a timer | Rule state: which alerts are pending or firing |
| Alert manager | Groups, mutes and routes alerts to people | Silences and what it has already sent |
| Dashboards and API | Range queries for people and tools | None |
Nothing here is on the request path of a user. That frees the design to prefer steady throughput and to lose a little rather than block: a collector that cannot reach an ingester buffers for a short time and then drops, since a missing sample is a smaller problem than an overloaded system.
The path, end to end
Watch for one error spike travelling from a server to a phone
Read it as steps
Collectors scrape targets and write to ingesters, a rule evaluator reads the store, and firing alerts reach an on-call person.
Read the scene from left to right. A collector asks a server for its metrics and gets a reply. It sends each sample to the ingester that owns the series, and the ingester writes it to the store. Once a minute the rule evaluator queries the store. When a rule's condition has held for its duration, the alert is firing and goes to the alert manager, which decides whether to notify, whom, and when. The evaluator and the alert manager are separate so that evaluation stays simple, while all the noisy logic about people lives in one place.
A dashboard query takes the other path and touches no rule state. For the last two hours it reads the ingesters, which hold recent samples in memory; for older ranges it reads blocks from the store, and it merges the two. A range query is cheap per series, so the costs to watch are the number of series a query selects and the length of the range, which is why the query layer caps both and answers a 30-day graph from rollups, as the last lesson describes. At 13 queries a second the read path is small, but it must stay fast during an incident, when everyone opens the same dashboard.
Spreading series over ingesters
One machine cannot hold 13.5 lakh active series with their recent samples and take 90,000 writes a second, so the series are sharded. The key is the series identity, the metric name plus sorted labels, and the placement rule is consistent hashing with virtual nodes, from the key-value store chapter. Each series lives on two ingesters, the first two distinct nodes clockwise from its hash, so that one crash loses no recent data.
The script places 40,000 series on four ingesters with 64 virtual nodes each and two copies. It checks that the load is even, that sorting the labels gives one identity whatever order they arrive in, that a label value which looks like two labels stays one series, and what happens when an ingester is dead or when none is left. The identity is the name plus the sorted pairs written as JSON, so quoting keeps one value from pretending to be two labels; an earlier plain k=v,k=v text gave one value of 1,b=2 the same identity as two labels.
import bisect, hashlib, json, sys from collections import Counter VNODES, RF = 64, 2 def h(text): return int(hashlib.md5(text.encode()).hexdigest()[:12], 16) def series_id(name, labels): # sorted, so label order cannot change where a series lives; # JSON quoting, so a value cannot pretend to be another label pairs = sorted((k, str(v)) for k, v in labels.items()) return name + json.dumps(pairs, separators=(",", ":")) class Ring: def __init__(self, nodes): self.points = sorted((h(f"{n}#{i}"), n) for n in nodes for i in range(VNODES)) self.keys = [p for p, _ in self.points] self.nodes = set(nodes)
Python 3.12.10. Run: uv run --python 3.12 ingester_ring.py. Part 1 of 3; save all parts in one file, ingester_ring.py.
def owners(self, sid, alive=None): """The first RF distinct nodes clockwise from the hash.""" alive = self.nodes if alive is None else alive want = min(RF, len(alive)) if want == 0: raise ValueError("no ingester is alive") i, out = bisect.bisect(self.keys, h(sid)), [] while len(out) < want: n = self.points[i % len(self.points)][1] if n in alive and n not in out: out.append(n) i += 1 return out
Continues ingester_ring.py (part 2 of 3), same file.
print(sys.version.split()[0]) ring = Ring(["ing-1", "ing-2", "ing-3", "ing-4"]) ids = [series_id("cpu_seconds_total", {"host": f"h{i}", "core": c, "mode": m}) for i in range(5000) for c in range(4) for m in ("user", "system")] print(len(ids), "series") load = Counter(n for sid in ids for n in ring.owners(sid)) print("copies held per ingester:") for n, c in sorted(load.items()): print(f" {n}: {c:,}") print("copies in total :", sum(load.values()), "= series x", RF) s1 = series_id("m", {"a": 1, "b": 2}) s2 = series_id("m", {"b": 2, "a": 1}) print("same series, labels swapped:", s1 == s2) tricky = series_id("m", {"a": "1,b=2"}) print("one label that looks like two:", tricky != series_id("m", {"a": "1", "b": "2"})) alive = {"ing-1", "ing-2", "ing-3"} # ing-4 has crashed lost = sum(1 for sid in ids if not set(ring.owners(sid, alive)) & alive) changed = sum(1 for sid in ids if "ing-4" in ring.owners(sid)) print("series with ing-4 as an owner:", changed) print("series with no live owner :", lost) print("owners with one node left :", ring.owners(ids[0], {"ing-2"})) try: ring.owners(ids[0], set()) except ValueError as e: print("nobody alive:", e)
Continues ingester_ring.py (part 3 of 3), same file.
Part 4 · Storage and compression
Why compression works on this data
A sample is 16 bytes before compression, an 8-byte timestamp and an 8-byte value. At 90,000 samples a second that is 1.87 TB over 15 days, so the design must do better. A general compressor helps a little, but the data has a structure that a purpose-made scheme can use. Two observations are enough.
The first is about timestamps. A collector samples every 15 seconds, so each timestamp is almost exactly 15 seconds after the last. The step between timestamps is nearly the same each time, and the change of the step, the delta of delta, is nearly always 0. A zero can be written in a single bit. The second is about values. A gauge such as memory changes little between samples, and many series are constant. If the new value is XOR-ed with the previous one as a 64-bit pattern, the result is zero when they are equal, and when they differ only slightly it has long runs of zero bits at both ends. Only the middle bits then need writing.
This is a scheme of our own, built here so that its cost can be measured. It is not a copy of any product's format. The layout is below.
| Part | Bits written | When |
|---|---|---|
| Count, first timestamp, first value | 32, 64, 64 | Once per series chunk |
| First step between timestamps | 32 | Once |
| Change of step is 0 | 1 (a 0 bit) | Most of the time |
| Change of step small | 2 + 7, 3 + 9 or 4 + 12 bits | Jitter of a few milliseconds |
| Change of step large | 4 + 32 bits | A missed scrape |
Encoding and decoding
The code has helpers that write a change of step into a bit buffer in the smallest of four forms, and write an XOR in one of three forms, plus matching readers. The decoder must give back every timestamp and every 64-bit value exactly, including special values such as not-a-number and negative zero, because a database that changes a value is worse than no database. The functions refuse a step that does not fit in 32 bits, which a real system would handle by starting a new chunk. They also refuse a negative, fractional or oversized timestamp and a value that is not a number, and the reader refuses a chunk that ends too early. A first version accepted a negative timestamp and read it back as a number near 2^64, so it silently changed data.
import math, random, struct, sys class Bits: """Append bits, then read them back.""" def __init__(self, data=None): self.bits = [] if data is None else data self.pos = 0 def put(self, value, n): for i in range(n - 1, -1, -1): self.bits.append((value >> i) & 1) def get(self, n): if self.pos + n > len(self.bits): raise ValueError("the chunk ends too early") v = 0 for _ in range(n): v = (v << 1) | self.bits[self.pos] self.pos += 1 return v def size_bytes(self): return (len(self.bits) + 7) // 8 def fbits(x): return struct.unpack(">Q", struct.pack(">d", x))[0]
Python 3.12.10. Run: uv run --python 3.12 tsdb_codec.py. Part 1 of 10; save all parts in one file, tsdb_codec.py.
def bitsf(b): return struct.unpack(">d", struct.pack(">Q", b))[0] # (flag bits, flag length, payload bits, lowest dod, highest dod) BUCKETS = [(0b10, 2, 7, -63, 64), (0b110, 3, 9, -255, 256), (0b1110, 4, 12, -2047, 2048)] def put_dod(w, dod): """Write a change of step: 1 bit when it did not change.""" if dod == 0: w.put(0, 1) return for flag, nflag, nbits, lo, hi in BUCKETS: if lo <= dod <= hi: w.put(flag, nflag) w.put(dod - lo, nbits) return if not -2**31 < dod < 2**31: raise ValueError("step change over 32 bits") w.put(0b1111, 4) w.put(dod + 2**31, 32)
Continues tsdb_codec.py (part 2 of 10), same file.
def get_dod(r): if r.get(1) == 0: return 0 for _flag, _n, nbits, lo, _hi in BUCKETS: if r.get(1) == 0: return r.get(nbits) + lo return r.get(32) - 2**31 def put_xor(w, x, block): """Write the XOR of two values. block is the last (lead, trail).""" if x == 0: w.put(0, 1) return block lead = min(64 - x.bit_length(), 31) trail = (x & -x).bit_length() - 1 if block and lead >= block[0] and trail >= block[1]: w.put(0b10, 2) w.put(x >> block[1], 64 - block[0] - block[1]) return block n = 64 - lead - trail w.put(0b11, 2) w.put(lead, 5) w.put(n % 64, 6) # 64 is written as 0 w.put(x >> trail, n) return lead, trail
Continues tsdb_codec.py (part 3 of 10), same file.
Measuring bytes per point
The test data has four kinds of series of 1,000 points each, with timestamps 15 seconds apart. About half the steps have a jitter of up to 8 milliseconds, and one scrape is missed at point 400. The series are a constant gauge, a counter that grows by 0 to 20 per sample, a gauge that does a random walk rounded to two decimals, and uniformly random floats, the worst case. After the measurements, the script round-trips six awkward series, and 300 random ones, through the encoder and the decoder.
3.12.10 1000 points per series, 16 bytes raw each constant gauge 1,013 bytes 1.01 per point round trip True counter, +0 to 20 2,520 bytes 2.52 per point round trip True gauge, 2 decimals 8,005 bytes 8.01 per point round trip True random floats 8,069 bytes 8.07 per point round trip True assumed mix, 60% constant, 30% counters, 10% decimal gauges: 2.16 bytes per point empty round trip True one point round trip True duplicate timestamps round trip True time going backwards round trip True nan, inf, -0.0 round trip True huge step change round trip True step over 2^31 rejected: timestamp step does not fit in 32 bits negative timestamp rejected: timestamp: whole ms, 0 or more timestamp over 2^63 rejected: timestamp: whole ms, 0 or more fractional timestamp rejected: timestamp: whole ms, 0 or more text as a value rejected: a value must be a number cut at bit 10 rejected: the chunk ends too early cut at bit 100 rejected: the chunk ends too early cut at bit 150 rejected: the chunk ends too early random series that failed the round trip: 0 of 300
Output of the script.
Reading the numbers
The constant gauge costs 1.01 bytes a point. Most of that is the timestamps, since each value costs one bit. The counter costs 2.52 bytes, because a whole number stored as a 64-bit float has long runs of zero bits at the low end, so the XOR window is short. The gauge with two decimals costs 8.01 bytes, and the random floats 8.07: a value like 40.37 is not exactly representable in binary, so its low bits look random, and the XOR scheme has little to remove. The honest reading is that the scheme gives 1 to 2.5 bytes a point on constant and whole-number series, and only half the raw 16 bytes on series whose low bits are noise.
An assumed mix of 60 percent constant series, 30 percent counters and 10 percent decimal gauges comes to 2.16 bytes per point. That mix is a guess, and the measured number is the one to use with a real system's data, not ours. It lands near the 1 to 2 bytes a sample the Prometheus documentation reports for its own storage, but our data and our encoding are different, so the comparison is only about the order of magnitude.
The correctness checks matter as much. Empty, one-point, duplicate-timestamp and backwards-timestamp series all round-trip, and so do not-a-number, infinity and negative zero, because the scheme compares bit patterns and not numeric values. A step larger than 31 bits, a negative or fractional timestamp, a text value and a truncated chunk are refused with a clear error. And 300 random series with arbitrary steps and values round-trip with 0 failures.
Why is the delta of delta of timestamps almost always zero?
- Collectors sample on a fixed timer, so each step between timestamps is almost the same as the last. The change of the step is 0, which costs a single bit.
Why do the 2-decimal gauge and the random floats cost about 8 bytes a point?
- Their low bits look random, so XOR with the previous value leaves a wide window of changed bits. A constant or integer-valued series leaves almost nothing to write.
Why compare bit patterns, not numbers, when checking the round trip?
- NaN is not equal to itself and negative zero equals zero as a number, so a numeric comparison would hide exactly the cases where a codec changes a value.
Part 5 · The alert pipeline
From a rule to a notification
An alert rule, as the monitoring chapter showed, has a condition, a duration and a destination. In this design the work is split in two. The rule evaluator runs each rule on a timer against the store and keeps the state of every alert it has produced. The alert manager receives the alerts and decides what a person hears. Prometheus works the same way: its alerting rules have an optional for clause, elements that are active but not yet firing are pending, and firing alerts are sent to Alertmanager. The server errors chapter showed the better condition for a service level objective, a multiwindow burn rate; here it is just a rule whose output is a labelled alert.
Without more logic, the pipeline would be noisy. Ten machines with the same problem would page ten times. The evaluator sends the same firing alert every cycle, and a person would be paged every cycle. A planned change would page the team for every machine it touches. The alert manager exists to prevent exactly these. The server errors chapter named its three jobs, grouping, inhibition and silences. This lesson runs grouping, deduplication and silences. Inhibition, which mutes some alerts while a related alert is firing, is set in the same configuration and is not run here.
Timing is part of grouping. The Alertmanager configuration has group_wait, the delay before the first notification for a new group, with a default of 30 seconds; group_interval, the wait before further notifications for a group that has changed, default 5 minutes; and repeat_interval, the wait before repeating a notification that has not changed, default 4 hours. The first gives related alerts time to arrive together, so one message lists them all. Our script uses 30 seconds, 1 minute and 5 minutes so that it fits in a short simulated run.
The design of the simulation
The simulation has six instances in two clusters, mum and del. The rule fires when an instance's error ratio exceeds 5 percent for 60 seconds, evaluated every 15 seconds. Five Mumbai instances go bad from second 60, but one of them, mum-5, only for 30 seconds, which is shorter than the duration. Three of them, mum-1 to mum-3, recover at second 330. Another, mum-4, is bad until second 450, but it is silenced until second 300. Delhi's one instance goes bad from second 120 to second 600.
Alerts are grouped by cluster. To model two evaluators for high availability, the script gives the alert manager every batch twice. The alert manager deduplicates by a fingerprint of the alert's labels, so the second copy changes nothing. A notification is sent when the group is new and the wait has passed, when its set of live alerts has changed and the interval has passed, or when nothing has changed and the repeat interval has passed. Silences are checked at each tick, so a silence ending changes the set of live alerts without any event.
The pipeline in code
import sys EVAL_S = 15 # error ratio above 5% for 60 seconds FOR_S, THRESHOLD = 60, 0.05 GROUP_WAIT, GROUP_INTERVAL, REPEAT = 30, 60, 300 def fp(labels): return tuple(sorted(labels.items())) class Rule: """Per series: inactive -> pending -> firing, back to inactive.""" def __init__(self): # fingerprint -> first time above self.active = {}
Python 3.12.10. Run: uv run --python 3.12 alert_pipeline.py. Part 1 of 5; save all parts in one file, alert_pipeline.py.
def evaluate(self, now, samples): """samples: {instance: value}. Alerts to send now.""" out = [] for inst, value in samples.items(): if (isinstance(value, bool) or not isinstance(value, (int, float)) or value != value): continue # no usable value: keep its state labels = {"alertname": "HighErrors", "instance": inst, "cluster": inst.split("-")[0]} key = fp(labels) if value > THRESHOLD: since = self.active.setdefault(key, now) if now - since >= FOR_S: out.append((labels, "firing")) elif key in self.active: if now - self.active[key] >= FOR_S: out.append((labels, "resolved")) # a blip shorter than FOR_S vanishes del self.active[key] return out class Manager: def __init__(self): # fingerprint -> (labels, state) self.alerts = {} self.groups = {} # cluster -> group state self.silences = [] # (matchers, start, end)
Continues alert_pipeline.py (part 2 of 5), same file.
def silence(self, matchers, start, end): if not matchers: raise ValueError("a silence needs at least one matcher") if end <= start: raise ValueError("a silence must end after it starts") self.silences.append((matchers, start, end)) def silenced(self, labels, now): return any(s <= now < e and all(labels.get(k) == v for k, v in m.items()) for m, s, e in self.silences) def receive(self, now, batch): for labels, state in batch: key = fp(labels) if self.alerts.get(key, (None, None))[1] == state: # same alert again: nothing to do continue self.alerts[key] = (labels, state) self.groups.setdefault(labels["cluster"], dict( born=now, last=None, sent=set()))
Continues alert_pipeline.py (part 3 of 5), same file.
def tick(self, now): for cluster, g in self.groups.items(): live = {l["instance"] for l, st in self.alerts.values() if st == "firing" and l["cluster"] == cluster and not self.silenced(l, now)} if g["last"] is None: due = bool(live) and now - g["born"] >= GROUP_WAIT elif live != g["sent"]: due = now - g["last"] >= GROUP_INTERVAL else: due = bool(live) and now - g["last"] >= REPEAT if due: gone = sorted(g["sent"] - live) extra = f" gone {gone}" if gone else "" print(f" t={now:>3}s notify {cluster}:", f"firing {sorted(live)}{extra}") g["last"], g["sent"] = now, live rule, am = Rule(), Manager() print(sys.version.split()[0]) for matchers, start, end in [({}, 0, 10), ({"instance": "x"}, 10, 10)]: try: am.silence(matchers, start, end) except ValueError as e: print("silence rejected:", e) am.silence({"instance": "mum-4"}, 0, 300)
Continues alert_pipeline.py (part 4 of 5), same file.
Reading the timeline
The first two lines refuse a silence with no matchers, which would mute everything, and one that ends before it starts. The last line feeds the rule values that are not usable numbers: not-a-number, a missing value and text are skipped and keep their state, while infinity is above the threshold and goes pending. One bad value must not crash the evaluator or resolve an alert. Now the timeline. The mum instances cross the threshold at second 60 but must hold for 60 seconds, so they fire at 120, and with the 30-second group wait the first notification is at 150. It names mum-1, mum-2 and mum-3, and not mum-4, which is silenced, and not mum-5, whose 30-second blip never lasted long enough to fire. It is one message for three machines. del-1 fires at 180 and is notified at 210.
At second 300 the silence on mum-4 ends. The set of live alerts has changed, so the group notifies again: now four instances, with no new evaluation event, only the passing of time. At 330 the first three recover, and at 360 the next notification says that mum-4 is still firing and the other three are gone. At 450 mum-4 recovers, and the group's last message says nothing is firing and mum-4 has gone. del-1 is still firing at 510, 300 seconds after its first message, so the repeat interval sends a reminder. It recovers at 600.
Five properties follow from the run. Each distinct problem produced a single message per change, not one per evaluation. The duplicate batches from the second evaluator caused no extra notifications. A blip shorter than the duration never paged anyone. A silence hid an alert and then stopped hiding it without any event. And resolution is a notification too, because a person who was told about a problem needs to hear that it is over.
Why does the evaluator send the same firing alert every cycle, and why is that harmless?
- The evaluator only reports what is firing now and does not track who has been told. The alert manager deduplicates by a fingerprint of the labels, so a repeat changes nothing and causes no new message.
What does the duration on a rule do in the run?
- It stops mum-5, which was bad for only 30 seconds, from ever firing. Instances above the threshold for the full 60 seconds fire.
Part 6 · Rollups, retention, high availability and failures
Rollups and retention
The monitoring chapter showed downsampling, and the same idea sets the storage plan here. Raw samples at 15 seconds are kept for the 15 days of the sizing. Older data is replaced by rollups: five-minute rows with the minimum, maximum, sum and count of each bucket, and later hourly rows made from the five-minute ones. Keeping the sum and the count and not the average allows rollups to be combined correctly, since averages of averages are wrong.
The reason is the cost of reading. A graph of 30 days of one series reads 1,72,800 points from the raw tier, 8,640 from five-minute rollups and 720 from hourly ones. Across 10 lakh series, the raw read is 17,280 crore points. The program prints the same three totals in crore: 17,280, 864 and 72. The query layer picks the coarsest tier that still gives enough points for the width of the chart, so that a 30-day graph never touches raw samples.
Prometheus groups ingested samples into two-hour blocks, keeps a write-ahead log in 128 MB segments that can be replayed after a crash, and compacts the initial blocks into longer ones in the background. With neither retention flag set it keeps data for 15 days. We borrow the shape of that design: a log for recent data, immutable blocks on disk, and compaction.
High availability
Local storage on one machine is not clustered or replicated, as the Prometheus documentation notes plainly, so a monitoring system has to build availability around it. The ingesters of the third lesson keep two copies of recent data. For the whole pipeline, one pattern is to run two identical replicas, each scraping the same targets and storing its own copy, and to merge their answers when reading. The documentation for Alertmanager says it can be run as a cluster, with silences and notification state replicated between the peers, and advises pointing each Prometheus at all the Alertmanagers instead of load balancing in front of them.
The script runs the replica idea on one day of 15-second samples, 5,760 of them. Each replica misses 2 percent of scrapes at random. Replica A is also down for 100 minutes. The merge takes, for each timestamp, the first value present in either replica. Two real replicas scrape at slightly different times and their values differ a little, so a real merge would have to align time buckets and choose one replica's value for each, which this script does not do: its counters are identical on both sides to keep the demonstration simple.
import random, sys # Part 1: what a 30-day graph reads, raw against rolled-up data. SERIES = 1_000_000 span_days = 30 TIERS = [("raw, 15 s", 15), ("rollup, 5 min", 300), ("rollup, 1 hour", 3600)] for name, step in TIERS: points = span_days * 86_400 // step total = points * SERIES / 1e7 print(f"{name:15}: {points:>8,} points,", f"{total:>6,.0f} crore for 10 lakh series") # Part 2: two replicas scrape the same targets and each misses scrapes. rng = random.Random(9) STEP, N = 15, 5760 # one day of 15-second samples def scrape(down_from=None, down_to=None, miss=0.02): got = {} for i in range(N): t = i * STEP if down_from is not None and down_from <= t < down_to: continue # the replica was down if rng.random() < miss: continue # a scrape failed # a counter, the same on both sides got[t] = float(i) return got
Python 3.12.10. Run: uv run --python 3.12 replica_merge.py. Part 1 of 3; save all parts in one file, replica_merge.py.
def merge(*replicas): """One series from replicas of one target: first value present.""" out = {} for r in replicas: for t, v in r.items(): out.setdefault(t, v) return dict(sorted(out.items())) def covered(series): return len(series) / N
Continues replica_merge.py (part 2 of 3), same file.
print(sys.version.split()[0]) # replica A down for 100 min a = scrape(down_from=40_000, down_to=46_000) b = scrape() print(f"replica A alone : {covered(a):.1%} of samples") print(f"replica B alone : {covered(b):.1%} of samples") m = merge(a, b) print(f"merged : {covered(m):.1%} of samples") # both down for 50 minutes c = scrape(down_from=41_000, down_to=44_000) m2 = merge(a, c) print(f"merged, both down for 50 minutes: {covered(m2):.1%}") gaps, prev = [], None for t in m2: if prev is not None and t - prev > 60: gaps.append((prev, t)) prev = t print("gaps longer than a minute:", [(g0, g1) for g0, g1 in gaps]) print("merge of nothing:", merge()) print("merge keeps order:", list(m2) == sorted(m2))
Continues replica_merge.py (part 3 of 3), same file.
Failures and trade-offs
The worst failure is a silent one: the alerting system itself stops and nobody notices. The defence is the one from the server errors chapter: monitor the monitor from outside with a separate, simple system, and keep a dead man's switch, an alert that is always firing, so that its absence at the receiving end shows the pipeline has broken. A second failure is overload: a cardinality explosion fills ingester memory. The series limit from the second lesson contains it, and the dropped-series counter is itself alerted on. A third is a notification storm. Grouping and inhibition handle most of it, and a rate limit on the notification channel is the last guard.
Some failures are intended trade-offs. If an ingester cannot keep up, we drop samples rather than slow the services, because a gap in a graph is cheaper than a slow service. If the evaluator cannot read the store, it must not resolve alerts, since a missing answer is not evidence of health. And when the alert manager is unreachable, the evaluator keeps trying, and a second path, such as a direct message from a very simple watchdog, covers the case where the whole chain is down.
| Choice | Gain | Cost |
|---|---|---|
| Pull collection | Collector sees a dead target at once | Needs a route to every target; short-lived jobs need a push path |
| Two copies per series | A lost ingester loses no recent data | Twice the memory for recent data |
| Custom encoding | About 2 bytes a point on ordinary data | Needs code and tests; poor on noisy decimal values |
| Rollup tiers | Cheap long-range graphs | Detail is gone; keep min, max, sum and count |
| Separate alert manager | One place for grouping, silences and routing | One more component that must be highly available |
All chapters · Previous: Design a Calendar Service like Google Calendar