How to Alert When Prometheus Stops Seeing Your Service: Tell a Crash From a Removed Target From a Renamed Metric, Use absent() Without False Alarms, and Test Every Silent Failure With promtool
Run a real Prometheus 3.16.0 against two pretend services, break them four different ways, and learn which of up == 0, absent(), a replica count and an instance-vanished rule catches each failure,...
In a famous Sherlock Holmes story, the clue that solves the case is a dog that did nothing in the night. Monitoring has the same trap. The failures that hurt most often make everything go quiet: a service crashes, a server is taken out of rotation, an upgrade renames a metric. Nothing is wrong with the data Prometheus can see, because the data is gone. An alert written as “page me when the error rate is high” has nothing left to judge, so it does not fire. Worse, if it was already firing, it stops.
Table Of Content
- What you will build
- The words you need first
- Prerequisites
- Step 1: Download Prometheus and check that both programs run
- Put both programs where your shell and the lab can find them
- Check that it worked
- Step 2: See the silent failure in a unit test before you touch a server
- What the rule says, from the inside out
- Write a test in which the service stops
- What this proves
- Step 3: Build a small lab with two pretend services and a real Prometheus
- The pretend service
- The Prometheus configuration
- The lab script, in five pieces
- Run the first scenario
- How to read the output
- Check that it worked
- Step 4: Break the services and watch the error alert go quiet
- What happened
- Why this matters
- Step 5: Catch a crashed service with up == 0
- What you should see
- Now remove the targets instead of crashing them
- What happened this time
- Step 6: Catch a vanished job with absent()
- What you should see
- Which labels does an absent() alert carry?
- Step 7: Catch a metric that vanished while the service is up
- Why it fires twice
- Fix it with a guard
- Step 8: Catch a job that is only partly gone
- How the two rules work
- ReplicasLow: how many healthy replicas are left
- InstanceVanished: which instance left
- What you should see
- The alert needs history
- Step 9: Find out how long each alert takes to notice
- Reading the timeline
- Step 10: Add a watchdog for the monitoring system itself
- Step 11: Lock it all in with tests and a gate that plants mistakes
- Healthy services that fail half of their requests
- Both services crash
- Both targets leave service discovery
- The counters are renamed
- One of two targets leaves
- Stale marker or samples that just stop
- No data at all
- One script for the whole gate
- Plant mistakes and see whether the tests notice
- What the results say
- See a failure with your own eyes
- Step 12: Confirm the whole thing end to end
- Common mistakes and how to avoid them
- Where to go next
- Sources and further reading
In this tutorial you will fix that. You will run a real Prometheus 3.16.0 on your own machine, point it at two pretend services, and break the services on purpose: they crash, they disappear from service discovery, an upgrade renames their counters, and one of the two goes away. For each failure you will write the alert that notices it and watch it fire on the real server. Along the way you will learn what up, absent(), staleness and the lookback window actually do, using measurements instead of folklore. At the end you will pin the behavior down with promtool unit tests, then plant fourteen mistakes in the rules to check that the tests notice them.
Nothing here needs Docker, a Kubernetes cluster, a cloud account or Alertmanager. If you want to know what happens to an alert after it fires, the earlier posts How to Alert on Your SLO Without Paging for Noise and How to Route Alerts in Alertmanager cover the routing half of the pipeline. This post covers the half that decides whether an alert fires at all.
What you will build
- seven alerting rules in
rules.yml:HighErrorRate,TargetDown,TargetMissing,MetricMissing,ReplicasLow,InstanceVanishedandWatchdog; - a pretend service,
exporter.py, and a lab,live_lab.py, that starts a real Prometheus, breaks two copies of the service in five different ways and prints which alerts fire and when; - nine
promtooltest files, a short CI script,ci.sh, andmutants.py, which plants fourteen mistakes in the rules and counts how many the tests catch.
The words you need first
Prometheus has a small vocabulary. Read these once and the rest of the post will make sense.
- Metric and time series. A metric is a named measurement, such as
app_requests_total. A time series is that name plus a set of labels, for exampleapp_requests_total{path="/orders"}, together with its history of samples, which are numbers with timestamps. A counter is a metric that only goes up; you alert on how fast it grows, usingrate(). - Scrape, target, job and instance. Prometheus collects data by scraping: on a schedule it fetches a web page, usually
/metrics, from each target. Targets are grouped into a job (hereapi) and each one has an instance label such as127.0.0.1:9101. - Service discovery. How Prometheus learns which targets exist: a file, Kubernetes, a cloud API. When a target leaves the list, for example because a pod was deleted, Prometheus stops scraping it.
- The
upseries. After every scrape Prometheus stores one extra series calledup. The documentation describes its value as “1 if the instance is healthy, i.e. reachable, or 0 if the scrape failed”. - Stale marker. A special sample that tells queries “this series has ended”. The documentation says: “If a target scrape or rule evaluation no longer returns a sample for a time series that was previously present, this time series will be marked as stale. If a target is removed, the previously retrieved time series will be marked as stale soon after removal.”
- Lookback. When a query asks for a series at one moment, Prometheus uses “the newest sample that is less than the lookback period ago”, and “The lookback period is 5 minutes by default”. That is how a series that merely stops receiving samples, with no stale marker, keeps answering queries for five more minutes.
- Alerting rule. A PromQL expression,
expr, that Prometheus evaluates again and again. The documentation says: “Whenever the alert expression results in one or more vector elements at a given point in time, the alert counts as active for these elements’ label sets.” An alert with aforclause first waits in the pending state, and only then becomes firing. - promtool. The checker that ships with Prometheus.
promtool check rulesreads a rules file for mistakes, andpromtool test rulesruns unit tests: you give it made-up samples and the alerts you expect, and it tells you whether your rules agree.
Prerequisites
- Operating system: tested on Windows 11 with Git Bash. Prometheus also publishes Linux and macOS archives; I did not test those, and the lab scripts add
.exeto program names only on Windows. - Prometheus 3.16.0, released on November 5, 2026. The Windows archive is about 117 MB and holds both
prometheusandpromtool. - Python 3.10 or newer (tested with 3.13.14). The lab uses only the standard library.
- Free ports: 9101, 9102 and 9190 on your own machine. The lab listens only on 127.0.0.1.
- Prior knowledge: you can read YAML and you know that a metric has labels. You do not need to have run Prometheus before, and no Alertmanager is involved.
- Time: about an hour, most of it reading. Each live experiment takes about 40 seconds.
Step 1: Download Prometheus and check that both programs run
Prometheus is one program written in Go. The release archive contains the server, prometheus, and the checker you will use throughout this post, promtool. Download the archive for your system from the v3.16.0 release page, which is also linked from prometheus.io/download. On Windows the file is prometheus-3.16.0.windows-amd64.zip. The release page lists a SHA-256 digest for every file, so compare it with the one for your download before you unpack it (Get-FileHash in PowerShell, sha256sum on Linux). My download matched.
Put both programs where your shell and the lab can find them
mkdir absent-lab
cd absent-lab
export PROM_DIR="/c/tools/prometheus-3.16.0.windows-amd64"
export PATH="$PATH:$PROM_DIR"
prometheus --version | head -1
promtool --version | head -1
Replace the folder in the third line with wherever you unpacked the archive. Two things are happening. The shell finds promtool through PATH, and the Python lab scripts you will write in a moment find prometheus through the PROM_DIR variable. All the files you create in this post go into the absent-lab folder.
prometheus, version 3.16.0 (branch: HEAD, revision: e2e28adeee2c5883d000fc82aca6008cfbf7e96d)
promtool, version 3.16.0 (branch: HEAD, revision: e2e28adeee2c5883d000fc82aca6008cfbf7e96d)
Check that it worked
Both lines should name version 3.16.0. If your shell says “command not found”, the PATH line did not take effect or the folder is wrong. The long hexadecimal revision on your machine will be the same as mine if you downloaded the same release.
Step 2: See the silent failure in a unit test before you touch a server
Start with the alert most teams already have: page me when more than 5 percent of requests fail. Create rules.yml in your absent-lab folder with this content.
# rules.yml
groups:
- name: api
rules:
# 1. The ordinary alert. It can only judge data that exists.
- alert: HighErrorRate
expr: |
sum(rate(app_errors_total{job="api"}[5m]))
/ sum(rate(app_requests_total{job="api"}[5m])) > 0.05
for: 5m
labels:
severity: page
annotations:
summary: More than 5 percent of api requests fail
What the rule says, from the inside out
rate(app_errors_total{job="api"}[5m]) is how fast the error counter has been growing per second, averaged over the last five minutes. sum() adds that up across all instances of the job. Dividing by the same sum for app_requests_total gives the share of requests that fail, and > 0.05 keeps the result only when that share is above 5 percent. for: 5m says the condition must hold for five minutes before the alert starts firing. The severity label is what a routing system such as Alertmanager would use to decide who gets paged.
Write a test in which the service stops
promtool test rules needs no running server. You describe a few time series sample by sample, then say which alerts you expect at which moment. Create test_silent.yml:
# test_silent.yml: the error alert is blind to a service that has stopped
rule_files:
- rules.yml
evaluation_interval: 1m
tests:
- interval: 1m
input_series:
- series: 'app_requests_total{job="api", instance="10.0.0.1:9100", path="/orders"}'
values: '0+600x9 stale'
- series: 'app_errors_total{job="api", instance="10.0.0.1:9100", code="500"}'
values: '0+300x9 stale'
alert_rule_test:
- eval_time: 8m
alertname: HighErrorRate
exp_alerts:
- exp_labels: {severity: page}
exp_annotations: {summary: More than 5 percent of api requests fail}
- {eval_time: 20m, alertname: HighErrorRate, exp_alerts: []}
The notation 0+600x9 means “start at 0 and add 600, nine times”, which gives ten samples, one per minute, from minute 0 to minute 9: the request counter grows by 600 a minute and the error counter by 300, so half of the requests fail. The word stale after the space adds a stale marker at minute 10, which is what Prometheus writes when a series ends. The test file says interval: 1m for the samples and evaluation_interval: 1m for the rules. The documentation for the notation says that “'_' represents a missing sample from scrape” and that “'stale' indicates a stale sample”; you will use both later.
The two checks are the heart of the test. At minute 8 the alert should be firing with the labels and summary shown. At minute 20, ten minutes after the service stopped, exp_alerts: [] says that no alert should be firing at all. Run the checker and the test:
promtool check rules rules.yml
promtool test rules test_silent.yml
Checking rules.yml
SUCCESS: 1 rules found
Processing test file: test_silent.yml
SUCCESS
What this proves
The test passed, which means the two checks are true: the alert fires while the service is failing half of its requests, and it is gone when the service has stopped. That is the problem in one screen. An error-rate alert cannot tell “everything is fine” from “nothing is running”, because in both cases it has no errors to show you. The rest of this post is about the alerts that can.
Step 3: Build a small lab with two pretend services and a real Prometheus
Unit tests with made-up samples are fast, but they only prove what you told them. To learn how a real Prometheus behaves, you need a real one scraping something that you can break. The lab has three parts: a pretend service, a configuration for Prometheus, and a script that starts everything, causes a failure and reports what the alerts did.
The pretend service
Create exporter.py. It is a tiny web server that answers /metrics in the plain-text format Prometheus reads.
# exporter.py
"""A tiny pretend service that serves Prometheus metrics.
Run it by hand: python exporter.py 9101 0.5 (port, then the share of requests that fail)
The lab imports the Exporter class and breaks it on purpose.
"""
import sys
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
class Exporter:
def __init__(self, port, error_rate=0.0):
self.port = port
self.error_rate = error_rate
self.requests = 0
self.errors = 0
self.renamed = False # True after a pretend upgrade renamed the two counters
self.running = True
owner = self
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
if self.path != "/metrics":
self.send_error(404)
return
body = owner.render().encode()
self.send_response(200)
self.send_header("Content-Type", "text/plain; version=0.0.4")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, *args):
pass
self.server = ThreadingHTTPServer(("127.0.0.1", port), Handler)
self.server.daemon_threads = True
def render(self):
prefix = "app_http" if self.renamed else "app"
return (
"# TYPE app_info gauge\n"
'app_info{version="1.0"} 1\n'
f"# TYPE {prefix}_requests_total counter\n"
f'{prefix}_requests_total{{path="/orders"}} {self.requests}\n'
f"# TYPE {prefix}_errors_total counter\n"
f'{prefix}_errors_total{{code="500"}} {self.errors}\n'
)
def _tick(self):
while self.running:
time.sleep(0.1)
self.requests += 10
self.errors += round(10 * self.error_rate)
def start(self):
threading.Thread(target=self.server.serve_forever, daemon=True).start()
threading.Thread(target=self._tick, daemon=True).start()
return self
def stop(self):
"""Stop answering: the next scrape gets 'connection refused', like a crashed process."""
self.running = False
self.server.shutdown()
self.server.server_close()
if __name__ == "__main__":
port = int(sys.argv[1]) if len(sys.argv) > 1 else 9101
rate = float(sys.argv[2]) if len(sys.argv) > 2 else 0.0
Exporter(port, rate).start()
print(f"serving http://127.0.0.1:{port}/metrics (error rate {rate})", flush=True)
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
pass
Three metrics come out of it: app_info, which is always there, and the two counters app_requests_total and app_errors_total. A background thread adds 10 requests every tenth of a second, and a share of them, set by error_rate, count as errors. Setting renamed makes the same numbers appear as app_http_requests_total and app_http_errors_total, which is what an upgrade that renames a counter looks like from outside. stop() closes the listening socket, so the next scrape gets “connection refused”, exactly like a crashed process. Note that the error counter is exported with the value 0 from the start; that detail matters later.
The Prometheus configuration
Create prometheus.yml:
# prometheus.yml
global:
scrape_interval: 1s
scrape_timeout: 1s
evaluation_interval: 1s
rule_files:
- rules_lab.yml
scrape_configs:
- job_name: api
file_sd_configs:
- files:
- targets.json
refresh_interval: 1s
A real Prometheus scrapes every 15 seconds to a minute and judges alerts over windows of minutes. Waiting for that in a tutorial would take hours, so this configuration scrapes and evaluates every second, and the lab script will rewrite every duration in rules.yml such as 5m into 5s. Every minute in the rules becomes a second in the lab. The targets come from file_sd_configs, which means Prometheus reads a JSON file called targets.json and re-reads it every second. Deleting a target from that file is the lab’s stand-in for what Kubernetes service discovery reports when a pod is deleted.
The lab script, in five pieces
Create live_lab.py from the five blocks below, one after the other in the same file. The first piece sets up the constants. Notice that ALERTS is read from your rules.yml, so the report only lists the alerts you have written so far. SCENARIOS names the five ways the lab can break the services and the error rate they start with.
# live_lab.py
"""Run a real Prometheus against two pretend services and break them in different ways.
python live_lab.py run every scenario
python live_lab.py die gone run only the scenarios you name
Needs the prometheus program: put it on PATH or set PROM_DIR to the folder that holds it.
Every minute in rules.yml becomes a second here, so a 5 minute alert takes 5 seconds.
"""
import json
import os
import re
import shutil
import subprocess
import sys
import time
import urllib.parse
import urllib.request
from pathlib import Path
from exporter import Exporter
HERE = Path(__file__).resolve().parent
EXE = ".exe" if os.name == "nt" else ""
PROM = str(Path(os.environ["PROM_DIR"]) / f"prometheus{EXE}") if "PROM_DIR" in os.environ else "prometheus"
API = "http://127.0.0.1:9190"
WATCH_SECONDS = 30
ALERTS = re.findall(r"- alert: (\w+)", (HERE / "rules.yml").read_text(encoding="utf-8"))
SCENARIOS = { # name: (what happens, error rate before it happens)
"errors": ("both services start failing half of their requests", 0.0),
"die": ("both services crash while half of their requests fail", 0.5),
"gone": ("both targets leave service discovery while half of their requests fail", 0.5),
"renamed": ("an upgrade renames the counters while half of the requests fail", 0.5),
"one_gone": ("one of two targets leaves service discovery while half of the requests fail", 0.5),
}
def get(path):
with urllib.request.urlopen(API + path, timeout=3) as response:
return json.load(response)["data"]
def active_alerts():
alerts = get("/api/v1/alerts")["alerts"]
return sorted(alerts, key=lambda a: sorted(a["labels"].items())) # the same order on every run
The second piece is the Lab class. It rewrites the rules with seconds instead of minutes, starts two exporters on ports 9101 and 9102, writes targets.json and starts Prometheus on port 9190 with its data in a throwaway folder. Then it waits until Prometheus answers /-/ready. write_targets writes the file to a temporary name and renames it, so Prometheus never reads half a file. On Windows the rename can fail with “Access is denied” if Prometheus happens to have the old file open at that instant, so the method retries for a few seconds.
# live_lab.py (continued)
class Lab:
def __init__(self, name, error_rate):
self.dir = HERE / "work" / name
shutil.rmtree(self.dir, ignore_errors=True)
self.dir.mkdir(parents=True)
rules = (HERE / "rules.yml").read_text(encoding="utf-8")
shrunk = re.sub(r"(\d+)m\b", r"\1s", rules) # every minute becomes a second
(self.dir / "rules_lab.yml").write_text(shrunk, encoding="utf-8", newline="\n")
shutil.copy(HERE / "prometheus.yml", self.dir / "prometheus.yml")
self.exporters = [Exporter(9101, error_rate).start(), Exporter(9102, error_rate).start()]
self.write_targets(self.exporters)
log = open(self.dir / "prometheus.log", "w")
self.proc = subprocess.Popen(
[PROM, "--config.file=prometheus.yml", "--storage.tsdb.path=data",
"--web.listen-address=127.0.0.1:9190", "--log.level=warn"],
cwd=self.dir, stdout=log, stderr=subprocess.STDOUT)
for _ in range(100):
try:
urllib.request.urlopen(API + "/-/ready", timeout=1).close()
break
except OSError:
time.sleep(0.2)
else:
raise SystemExit("Prometheus did not become ready; see " + str(self.dir / "prometheus.log"))
def write_targets(self, exporters):
tmp = self.dir / "targets.json.tmp"
tmp.write_text(json.dumps([{"targets": [f"127.0.0.1:{e.port}" for e in exporters]}]), encoding="utf-8")
for _ in range(50): # Windows refuses to replace a file that Prometheus has open at that moment
try:
os.replace(tmp, self.dir / "targets.json")
return
except PermissionError:
time.sleep(0.1)
raise SystemExit("could not replace targets.json")
def close(self):
self.proc.terminate()
self.proc.wait(15)
for e in self.exporters:
e.stop()
The third piece is the part you will enjoy: inject breaks things. errors makes both services fail half of their requests. die stops both services. gone empties targets.json. renamed switches the counter names. one_gone removes one of the two targets from the file.
# live_lab.py (continued)
def inject(name, lab):
first = lab.exporters[0]
if name == "errors":
for e in lab.exporters:
e.error_rate = 0.5
elif name == "die":
for e in lab.exporters:
e.stop()
elif name == "gone":
lab.write_targets([])
elif name == "renamed":
for e in lab.exporters:
e.renamed = True
elif name == "one_gone":
lab.write_targets([first])
def label_text(alert):
labels = {k: v for k, v in alert["labels"].items() if k != "alertname"}
return "{" + ", ".join(f'{k}="{v}"' for k, v in sorted(labels.items())) + "}"
The fourth piece runs one scenario. It waits until both targets are healthy and, for the scenarios that start with failing requests, until HighErrorRate is firing. It remembers which alerts were firing before the change, makes the change, and then asks Prometheus for its active alerts every half second for 30 seconds. Prometheus lists an alert at /api/v1/alerts while it is pending or firing, and the script records when each one first appears in each state and when it disappears.
# live_lab.py (continued)
def run(name):
what, start_rate = SCENARIOS[name]
lab = Lab(name, start_rate)
try:
for _ in range(120): # wait until both targets are healthy and the starting state is reached
names = {a["labels"]["alertname"] for a in active_alerts() if a["state"] == "firing"}
up = get("/api/v1/query?query=" + urllib.parse.quote('count(up{job="api"} == 1)'))["result"]
healthy = bool(up) and up[0]["value"][1] == "2"
if healthy and (start_rate == 0.0 or "HighErrorRate" in names):
break
time.sleep(0.5)
else:
raise SystemExit(f"{name}: the starting state was not reached")
time.sleep(2)
before = {a["labels"]["alertname"] for a in active_alerts() if a["state"] == "firing"}
t0 = time.monotonic()
inject(name, lab)
seen = {}
while True:
t = time.monotonic() - t0
alerts = active_alerts()
now = {a["labels"]["alertname"] for a in alerts}
for a in alerts:
rec = seen.setdefault(a["labels"]["alertname"], {"pending": None, "firing": None, "labels": label_text(a), "n": 0})
rec["n"] = max(rec["n"], sum(1 for b in alerts if b["labels"]["alertname"] == a["labels"]["alertname"]))
if a["state"] == "pending" and rec["pending"] is None:
rec["pending"] = t
if a["state"] == "firing" and rec["firing"] is None:
rec["firing"] = t
for gone in (set(seen) | before) - now:
seen.setdefault(gone, {"pending": None, "firing": None, "labels": "", "n": 0}).setdefault("ended", t)
if t > WATCH_SECONDS:
break
time.sleep(0.5)
end_firing = {a["labels"]["alertname"] for a in alerts if a["state"] == "firing"}
print(f"scenario {name}: {what}")
cells = {}
width = max(map(len, ALERTS)) + 2
for alert in ALERTS:
rec = seen.get(alert)
if alert in before:
if alert in end_firing:
cells[alert], line = "stays", "was firing and is still firing"
else:
cells[alert], line = "RESOLVES", f"was firing; gone at +{rec['ended']:.1f} s"
elif rec and rec["firing"] is not None:
cells[alert] = "FIRES"
line = f"pending +{rec['pending']:.1f} s, firing +{rec['firing']:.1f} s, {rec['n']} series {rec['labels']}"
if alert not in end_firing:
cells[alert] = "fires, ends"
line += f"; gone at +{rec['ended']:.1f} s"
else:
cells[alert], line = "-", "silent"
print(f" {alert:<{width}}{line}")
print()
return cells
finally:
lab.close()
The last piece is the entry point. It prints the Prometheus version, runs the scenarios you name on the command line (or all five), and, when there is more than one, prints a table at the end.
# live_lab.py (continued)
def main():
wanted = sys.argv[1:] or list(SCENARIOS)
print(subprocess.run([PROM, "--version"], capture_output=True, text=True).stdout.splitlines()[0])
results = {name: run(name) for name in wanted}
if len(wanted) > 1:
width = max(map(len, ALERTS)) + 2
print("what each alert does in each scenario")
print(f"{'':<{width}}" + "".join(f"{name:<13}" for name in wanted))
for alert in ALERTS:
print(f"{alert:<{width}}" + "".join(f"{results[name][alert]:<13}" for name in wanted))
if __name__ == "__main__":
main()
Run the first scenario
python live_lab.py errors
prometheus, version 3.16.0 (branch: HEAD, revision: e2e28adeee2c5883d000fc82aca6008cfbf7e96d)
scenario errors: both services start failing half of their requests
HighErrorRate pending +1.0 s, firing +6.2 s, 1 series {severity="page"}
How to read the output
The first line is the version of the Prometheus that was started. Each indented line is one alert from your rules.yml. pending +1.0 s means the alert first appeared in the pending state one second after the lab made its change, and firing +6.2 s means it became firing about five seconds later, which is the for time (5m in the file, 5s in the lab). 1 series is the number of label sets the alert has, and the braces show the labels of the first one. Here the only label is severity, because sum() removed all the others. The word silent would mean that the alert never became active during the 30 seconds.
Check that it worked
You should see one line for HighErrorRate with a pending time near one second and a firing time near six seconds. If the script stops with “Prometheus did not become ready”, open work/errors/prometheus.log; the usual causes are a port that is already in use (9101, 9102 or 9190) or PROM_DIR pointing at the wrong folder.
Step 4: Break the services and watch the error alert go quiet
Now the experiment this post exists for. The die scenario starts with both services failing half of their requests, waits until HighErrorRate is firing, and then stops both services.
python live_lab.py die
scenario die: both services crash while half of their requests fail
HighErrorRate was firing; gone at +4.7 s
What happened
The alert that was firing, because half of the requests were failing, stopped firing a few seconds after the services died. The services did not get better; they stopped existing. This is the same thing the unit test showed, now on a real server. There is a short delay rather than an instant reset because rate() looks at the samples inside its window, five seconds in the lab and five minutes in production, and the last real samples stay inside that window for a while. In test_die.yml, which you will write in Step 11, the last sample is from minute 9, and the alert is still firing at minute 12 and gone at minute 14.
Why this matters
If this were production, the page for “half of our requests fail” would resolve itself at the moment the service went down completely. Every alert in the rest of this post exists to make sure that something is still shouting when the data disappears.
Step 5: Catch a crashed service with up == 0
The first alert is the simple one. When a scrape fails, Prometheus still stores a sample for up, and its value is 0. Add this rule to the end of rules.yml, keeping the indentation:
# rules.yml (continued)
# 2. The scrape fails. Prometheus still stores up = 0, so a comparison can see it.
- alert: TargetDown
expr: up{job="api"} == 0
for: 5m
labels:
severity: page
annotations:
summary: "{{ $labels.instance }} cannot be scraped"
It has one series per instance, so the alert tells you which instance cannot be scraped, and the {{ $labels.instance }} template puts its name in the summary. Run the same scenario again:
python live_lab.py die
scenario die: both services crash while half of their requests fail
HighErrorRate was firing; gone at +3.9 s
TargetDown pending +0.7 s, firing +5.9 s, 2 series {instance="127.0.0.1:9101", job="api", severity="page"}
What you should see
TargetDown goes pending within about a second, because the first failed scrape writes up = 0 at once, and it fires after its for time. The line says 2 series, one for each service. This is the failure that the phrase “alert when the target is down” usually refers to, and it is a good alert. It is also the only one of the failures in this post that it catches.
Now remove the targets instead of crashing them
Run the gone scenario. It empties targets.json, which is what happens when a deployment is deleted, a host is decommissioned, or a relabeling or discovery change quietly drops the targets from the list.
python live_lab.py gone
scenario gone: both targets leave service discovery while half of their requests fail
HighErrorRate was firing; gone at +4.7 s
TargetDown silent
What happened this time
TargetDown is silent. When a target is removed from service discovery, Prometheus stops scraping it. It has no failed scrape to record, so it stores no up = 0; it writes stale markers and the up series simply ends. An expression that says up{job="api"} == 0 compares nothing with 0 and returns nothing, and an empty result means no alert. You now have an outage, with no services at all, that none of your alerts mentions.
Step 6: Catch a vanished job with absent()
PromQL has a function for exactly this. The documentation says: “absent(v instant-vector) returns an empty vector if the vector passed to it has any elements (float samples or histogram samples) and a 1-element vector with the value 1 if the vector passed to it has no elements. This is useful for alerting on when no time series exist for a given metric name and label combination.” Add this rule:
# rules.yml (continued)
# 3. The job has no up series at all, so there is nothing for == 0 to compare.
- alert: TargetMissing
expr: absent(up{job="api"})
for: 5m
labels:
severity: page
annotations:
summary: Prometheus has no up series for job api
python live_lab.py gone
scenario gone: both targets leave service discovery while half of their requests fail
HighErrorRate was firing; gone at +9.8 s
TargetDown silent
TargetMissing pending +8.3 s, firing +12.9 s, 1 series {job="api", severity="page"}
What you should see
TargetMissing now fires, and TargetDown is still silent, which is correct: the two alerts cover different failures. Look at the pending time. It is about eight seconds in this run, not one, and that delay is real Prometheus behavior worth knowing. Two things happen between your change and the moment the series ends, and together they explain roughly the eight seconds (the exact figure varies from run to run, because the discovery throttle can add anything up to five seconds). Prometheus passes discovery updates on to its scraper with a backoff that grows up to a maximum of five seconds (updatert: 5 * time.Second in discovery/manager.go). Then the scrape loop for the removed target waits before it writes the stale markers, because, in the words of a comment in scrape.go, “the target may be recreated, so we wait just over 2 scrape intervals before creating them.” With the one-second interval of the lab that wait is about two seconds. With a normal 15-second interval it is about 31 seconds, before for starts counting.
Which labels does an absent() alert carry?
The alert above has one label from the selector, job="api", plus the severity label from the rule. This is the part of absent() that surprises people, and the documentation describes it with three examples. You can check all of them on your own machine with a test that needs no rules. Create test_labels.yml:
# test_labels.yml: which labels does absent() keep? (no rules needed, only expressions)
evaluation_interval: 1m
tests:
- interval: 1m
input_series: []
promql_expr_test:
- expr: absent(nonexistent{job="myjob"})
eval_time: 1m
exp_samples:
- {labels: '{job="myjob"}', value: 1}
- expr: absent(nonexistent{job="myjob", instance=~".*"})
eval_time: 1m
exp_samples:
- {labels: '{job="myjob"}', value: 1}
- expr: absent(nonexistent{job=~"my.*"})
eval_time: 1m
exp_samples:
- {labels: '{}', value: 1}
- expr: absent(sum(nonexistent{job="myjob"}))
eval_time: 1m
exp_samples:
- {labels: '{}', value: 1}
- expr: absent_over_time(nonexistent{job="myjob"}[1h])
eval_time: 1h
exp_samples:
- {labels: '{job="myjob"}', value: 1}
promtool test rules test_labels.yml
Processing test file: test_labels.yml
SUCCESS
The checks passing tell you four things. absent() copies the label from an equality matcher such as job="myjob" into its result. It ignores a regex matcher, even the harmless instance=~".*", and in the third check a selector with only a regex matcher produces a result with no labels at all. Wrapping the selector in sum() also loses the labels, because the sum has none. The rule for absent_over_time() is the same. In practice, keep the matchers in an absent() rule as plain equalities and put every label you need for routing, such as severity or team, in the rule’s own labels: block.
Step 7: Catch a metric that vanished while the service is up
The third failure is the sneakiest. The service is healthy, the scrape succeeds, up is 1, and yet the counter you alert on is gone, because an upgrade renamed it. Your error-rate alert quietly stops working and nothing else changes. The same absent() function catches it, with the metric name instead of up. Add this rule:
# rules.yml (continued)
# 4. The service answers, but the counter we alert on is gone.
- alert: MetricMissing
expr: absent(app_requests_total{job="api"})
for: 10m
labels:
severity: ticket
annotations:
summary: api is up but app_requests_total is gone
python live_lab.py renamed
scenario renamed: an upgrade renames the counters while half of the requests fail
HighErrorRate was firing; gone at +4.7 s
TargetDown silent
TargetMissing silent
MetricMissing pending +1.6 s, firing +11.9 s, 1 series {job="api", severity="ticket"}
It fires. HighErrorRate resolves as the old counters end, and MetricMissing fires after its longer for of ten seconds (10m in the file; a rename is not urgent, so this one files a ticket rather than paging). So far so good. Now run the crash scenario again with the same rules:
python live_lab.py die
scenario die: both services crash while half of their requests fail
HighErrorRate was firing; gone at +4.8 s
TargetDown pending +1.6 s, firing +6.8 s, 2 series {instance="127.0.0.1:9101", job="api", severity="page"}
TargetMissing silent
MetricMissing pending +1.6 s, firing +12.0 s, 1 series {job="api", severity="ticket"}
Why it fires twice
When the services crash, MetricMissing fires as well as TargetDown. That is not a bug in Prometheus; it is how a failed scrape works. A comment in scrape.go says: “A failed scrape is the same as an empty scrape, we still call sl.append to trigger stale markers.” As far as the counters are concerned, a service that cannot be scraped has stopped exporting them, so absent() is true. You get two alerts for one cause, and the one that says “the counter is gone” points the person who is on call in the wrong direction.
Fix it with a guard
The fix is to say that the metric is missing while the target is healthy. Replace the rule with this version:
# rules.yml (replace MetricMissing)
# 4. The service answers, but the counter we alert on is gone.
# The guard keeps this quiet while TargetDown or TargetMissing already explain it.
- alert: MetricMissing
expr: absent(app_requests_total{job="api"}) and on() (up{job="api"} == 1)
for: 10m
labels:
severity: ticket
annotations:
summary: api is up but app_requests_total is gone
The new part is and on() (up{job="api"} == 1). The documentation for the and operator says: “vector1 and vector2 results in a vector consisting of the elements of vector1 for which there are elements in vector2 with exactly matching label sets.” With on() and no label names, every element matches every other, so the right-hand side works as a switch: it is on when at least one target in the job has up == 1, and off when none has, either because they are all down or because the up series do not exist. Run both scenarios again:
python live_lab.py die
python live_lab.py renamed
scenario die: both services crash while half of their requests fail
HighErrorRate was firing; gone at +3.8 s
TargetDown pending +0.7 s, firing +5.8 s, 2 series {instance="127.0.0.1:9101", job="api", severity="page"}
TargetMissing silent
MetricMissing silent
scenario renamed: an upgrade renames the counters while half of the requests fail
HighErrorRate was firing; gone at +4.1 s
TargetDown silent
TargetMissing silent
MetricMissing pending +1.0 s, firing +10.8 s, 1 series {job="api", severity="ticket"}
In the crash, MetricMissing is now silent and TargetDown carries the message. In the rename, it still fires. Each failure now has exactly one alert that names it.
Step 8: Catch a job that is only partly gone
absent(up{job="api"}) is true only when there is no up series at all for the job. If two of three replicas vanish, the third one’s series keeps it false. Two more rules handle that case. Add both:
# rules.yml (continued)
# 5. Fewer healthy replicas than expected. "or vector(0)" keeps it alive at zero.
- alert: ReplicasLow
expr: (count(up{job="api"} == 1) or vector(0)) < 2
for: 5m
labels:
severity: page
job: api
annotations:
summary: Fewer than 2 healthy api replicas
# rules.yml (continued)
# 6. Which instance left? It was there 15 minutes ago and is not there now.
- alert: InstanceVanished
expr: up{job="api"} offset 15m unless up{job="api"}
for: 2m
labels:
severity: ticket
annotations:
summary: "{{ $labels.instance }} stopped reporting"
How the two rules work
ReplicasLow: how many healthy replicas are left
ReplicasLow counts the healthy replicas and compares the count with the number you expect, 2 in this lab. The part that is easy to forget is or vector(0). When no replica is healthy, count() has nothing to count and returns an empty result, and empty < 2 is still empty, so the alert would stay silent exactly when all replicas are gone. The documentation for or says: “vector1 or vector2 results in a vector that contains all original elements (label sets + values) of vector1 and additionally all elements of vector2 which do not have matching label sets in vector1.” vector(0) is a vector with one element, the value 0 and no labels, so the left side supplies the count when there is one and the zero takes over when there is not. Because count() drops all labels, the rule adds job: api itself.
InstanceVanished: which instance left
InstanceVanished answers a different question: not “how many” but “which one”. The offset modifier “allows changing the time offset for individual instant and range vectors in a query”, so up{job="api"} offset 15m is every up series as it was 15 minutes ago. The unless operator keeps the elements of its left side “for which there are no elements in vector2 with exactly matching label sets”. Together they read: “instances that were there 15 minutes ago and are not there now”, and the labels, including instance, come along with the alert.
python live_lab.py one_gone
scenario one_gone: one of two targets leaves service discovery while half of the requests fail
HighErrorRate was firing and is still firing
TargetDown silent
TargetMissing silent
MetricMissing silent
ReplicasLow pending +7.8 s, firing +12.9 s, 1 series {job="api", severity="page"}
InstanceVanished pending +7.8 s, firing +9.8 s, 1 series {instance="127.0.0.1:9102", job="api", severity="ticket"}; gone at +21.7 s
What you should see
One of the two targets left, so TargetMissing and TargetDown stay silent, as they should: the job still has a healthy member and nothing is down. ReplicasLow fires, because only one replica is healthy. InstanceVanished fires with 1 series, and the label shows the instance that left, 127.0.0.1:9102. HighErrorRate stays firing because the remaining service still fails half of its requests. The last line of the InstanceVanished row says the alert is gone again after about 22 seconds. That is a property of the expression and not a fault: once the offset window moves past the moment the instance vanished, the left side is empty. ReplicasLow is the alert that stays on; InstanceVanished is the one that tells you who to look for.
The alert needs history
InstanceVanished compares with the past, so it cannot fire for a series that is younger than its offset. The lab output above does not show this, because the up series were already more than 15 seconds old when they vanished. The promtool timeline in Step 9 does show it: there the series start at minute 0, and the alert cannot start before minute 15. It is a feature as much as a limit, because instances that live for only a few minutes, such as short-lived autoscaled pods, never trigger it.
Step 9: Find out how long each alert takes to notice
You have now seen that the same disappearance can be noticed after one second or after eight. A stale marker makes a series disappear at once; a series whose samples simply stop stays visible until the lookback runs out. The documentation spells out one case where that happens: “Some exporters, which put their own timestamps on samples, get a different behaviour: series that stop being exported take the last value for (by default) 5 minutes before disappearing.” A timeline made with promtool shows the difference in minutes. The script below asks promtool to check, for every minute from 0 to 39, that no alert is firing, and reads the failures as a list of the minutes in which the alert was in fact firing. It also adds one extra probe rule built on absent_over_time(), which the documentation says is “useful for alerting on when no time series exist for a given metric name and label combination for a certain amount of time”.
# timeline.py
"""Ask promtool when an alert fires for a made-up series, by checking 'no alert' at every minute.
python timeline.py prints one line per case: the minutes at which each alert is firing
"""
import os
import re
import subprocess
import tempfile
from pathlib import Path
HERE = Path(__file__).resolve().parent
PROMTOOL = str(Path(os.environ["PROM_DIR"]) / ("promtool.exe" if os.name == "nt" else "promtool")) if "PROM_DIR" in os.environ else "promtool"
MINUTES = 40
PROBE = """ - name: probe
rules:
- alert: AbsentOverTime10m
expr: absent_over_time(up{job="api"}[10m])
"""
WATCH = ["TargetDown", "TargetMissing", "AbsentOverTime10m", "InstanceVanished"]
CASES = [ # title, series in promtool notation
("up reads 1 for 10 minutes, then 0", ['up{job="api",instance="a"} 1x9 0x40']),
("up reads 1 for 10 minutes, then a stale marker", ['up{job="api",instance="a"} 1x9 stale']),
("up reads 1 for 10 minutes, then the samples just stop (no stale marker)", ['up{job="api",instance="a"} 1x9 _x40']),
]
def firing_minutes(series, alerts):
rules = (HERE / "rules.yml").read_text(encoding="utf-8").rstrip("\n") + "\n" + PROBE
lines =["rule_files:", " - rules.yml", "evaluation_interval: 1m", "tests:", " - interval: 1m", " input_series:"]
lines += [f" - series: '{s.split(' ', 1)[0]}'\n values: '{s.split(' ', 1)[1]}'" for s in series]
lines += [" alert_rule_test:"]
for minute in range(MINUTES):
for alert in alerts:
lines += [f" - eval_time: {minute}m", f" alertname: {alert}", " exp_alerts: []"]
with tempfile.TemporaryDirectory() as tmp:
Path(tmp, "rules.yml").write_text(rules, encoding="utf-8", newline="\n")
Path(tmp, "probe.yml").write_text("\n".join(lines) + "\n", encoding="utf-8", newline="\n")
done = subprocess.run([PROMTOOL, "test", "rules", "probe.yml"], cwd=tmp, capture_output=True, text=True, encoding="utf-8")
text = done.stdout + done.stderr
fired = {a: [] for a in alerts}
for chunk in re.split(r"alertname: ", text)[1:]:
m = re.match(r"(\w+), time: (\S+?),", chunk)
if m and "Labels:" in chunk.split("got:", 1)[-1]:
fired[m.group(1)].append(minutes(m.group(2)))
return fired
def minutes(text):
"""Turn promtool's '15m0s' style durations into whole minutes."""
parts = {unit: int(n) for n, unit in re.findall(r"(\d+)([hms])", text)}
return parts.get("h", 0) * 60 + parts.get("m", 0)
def ranges(minutes):
if not minutes:
return "never"
minutes = sorted(set(minutes))
return f"from minute {minutes[0]} to {minutes[-1]}" if minutes[-1] - minutes[0] + 1 == len(minutes) else str(minutes)
if __name__ == "__main__":
for title, series in CASES:
print(title)
result = firing_minutes(series, WATCH)
for alert in WATCH:
print(f" {alert:<19}{ranges(result[alert])}")
python timeline.py
up reads 1 for 10 minutes, then 0
TargetDown from minute 15 to 39
TargetMissing never
AbsentOverTime10m never
InstanceVanished never
up reads 1 for 10 minutes, then a stale marker
TargetDown never
TargetMissing from minute 15 to 39
AbsentOverTime10m from minute 19 to 39
InstanceVanished from minute 17 to 24
up reads 1 for 10 minutes, then the samples just stop (no stale marker)
TargetDown never
TargetMissing from minute 19 to 39
AbsentOverTime10m from minute 19 to 39
InstanceVanished from minute 17 to 28
Reading the timeline
Each group of four lines is one way the up series can end after ten minutes of healthy samples, and the numbers are the minutes at which each alert is firing.
upreads 0. This is a failed scrape.TargetDownfires from minute 15, which is the failure at minute 10 plus the five minutes offor.TargetMissingnever fires, because the series still exists.- A stale marker. A removed target or a dropped metric.
TargetMissingis pending from minute 10 and fires from minute 15.TargetDownnever fires. - Samples that just stop. There is no stale marker, so the series stays visible for the five-minute lookback.
TargetMissingfires only from minute 19, four minutes later than in the stale case. absent_over_timewith a ten-minute range fires from minute 19 in both of the last two cases. A range selector does not care how the series ended; it fires once the whole range is empty. That makes it a good tool to ignore short gaps, and a slow one: you pay for the tolerance in minutes.InstanceVanishedstarts at minute 17, not 12. The series only began at minute 0, so a 15-minute offset can first look at it at minute 15, andfor: 2madds two more minutes. It ends at minute 24 (stale case) because at minute 25 the offset points at the marker itself.
Step 10: Add a watchdog for the monitoring system itself
Every alert so far runs inside Prometheus. If Prometheus stops, or if it can no longer reach Alertmanager or the pager, none of them can fire, and you are back at the dog that did not bark. The standard answer is an alert that is always firing. Add the last rule:
# rules.yml (continued)
# 7. Always firing. If it ever stops reaching a human, the alert pipeline is broken.
- alert: Watchdog
expr: vector(1)
labels:
severity: none
annotations:
summary: The alerting pipeline is alive
The runbook for this alert in the kube-prometheus project describes its purpose: “This is an alert meant to ensure that the entire alerting pipeline is functional. This alert is always firing, therefore it should always be firing in Alertmanager and always fire against a receiver.” The other half is outside your system. The runbook continues: “If not firing then it should alert external systems that this alerting system is no longer working.” It also points to “integrations with various notification mechanisms that send a notification when this alert is not firing. For example the DeadMansSnitch integration in PagerDuty.” In other words you route the watchdog to a service that expects a message every few minutes and raises the alarm when the messages stop. The earlier Alertmanager post shows how to route an alert by its severity label, and this rule uses severity: none so that it can be given its own route.
The expression returns an element whatever its value is. Remember the documentation: the alert is active “whenever the alert expression results in one or more vector elements”. vector(0) would fire just as well as vector(1), and in Step 11 you will see a test run that cannot tell them apart, because for this alert there is nothing to tell apart.
Step 11: Lock it all in with tests and a gate that plants mistakes
Everything you have measured so far is in your head and in a terminal. Now put it into tests that run on every change to rules.yml. You already have test_silent.yml and test_labels.yml. Add seven more files, one for each story in this post. Most of them use two services, 10.0.0.1:9100 and 10.0.0.2:9100, and all of them use the shorthand {eval_time: 20m, alertname: X, exp_alerts: []} for “this alert must not be firing at that minute”.
Healthy services that fail half of their requests
This is the control. The error alert fires, the watchdog fires, and every “missing” alert is silent. It matters more than it looks: a selector with a typo makes absent() fire forever on a healthy system, and only a test like this notices.
# test_healthy.yml: two healthy replicas, half of the requests fail
rule_files:
- rules.yml
evaluation_interval: 1m
tests:
- interval: 1m
input_series:
- series: 'up{job="api", instance="10.0.0.1:9100"}'
values: '1x40'
- series: 'up{job="api", instance="10.0.0.2:9100"}'
values: '1x40'
- series: 'app_requests_total{job="api", instance="10.0.0.1:9100", path="/orders"}'
values: '0+600x40'
- series: 'app_errors_total{job="api", instance="10.0.0.1:9100", code="500"}'
values: '0+300x40'
alert_rule_test:
- eval_time: 20m
alertname: HighErrorRate
exp_alerts:
- exp_labels: {severity: page}
exp_annotations: {summary: More than 5 percent of api requests fail}
- {eval_time: 20m, alertname: TargetDown, exp_alerts: []}
- {eval_time: 20m, alertname: TargetMissing, exp_alerts: []}
- {eval_time: 25m, alertname: MetricMissing, exp_alerts: []}
- {eval_time: 20m, alertname: ReplicasLow, exp_alerts: []}
- {eval_time: 20m, alertname: InstanceVanished, exp_alerts: []}
- eval_time: 20m
alertname: Watchdog
exp_alerts:
- exp_labels: {severity: none}
exp_annotations: {summary: The alerting pipeline is alive}
Both services crash
This is the die scenario in minutes. The checks on HighErrorRate pin the lingering and the resolve (firing at minute 12, gone at minute 14). TargetDown fires for both instances, ReplicasLow fires, and the guarded MetricMissing stays silent even at minute 25, long after its for time.
# test_die.yml: both services crash at minute 10 (up drops to 0, the counters go stale)
rule_files:
- rules.yml
evaluation_interval: 1m
tests:
- interval: 1m
input_series:
- series: 'up{job="api", instance="10.0.0.1:9100"}'
values: '1x9 0x40'
- series: 'up{job="api", instance="10.0.0.2:9100"}'
values: '1x9 0x40'
- series: 'app_requests_total{job="api", instance="10.0.0.1:9100", path="/orders"}'
values: '0+600x9 stale'
- series: 'app_errors_total{job="api", instance="10.0.0.1:9100", code="500"}'
values: '0+300x9 stale'
alert_rule_test:
# The error alert lingers until the last samples leave its 5 minute window, then goes quiet.
- eval_time: 12m
alertname: HighErrorRate
exp_alerts:
- exp_labels: {severity: page}
exp_annotations: {summary: More than 5 percent of api requests fail}
- {eval_time: 14m, alertname: HighErrorRate, exp_alerts: []}
- eval_time: 20m
alertname: TargetDown
exp_alerts:
- exp_labels: {severity: page, job: api, instance: "10.0.0.1:9100"}
exp_annotations: {summary: "10.0.0.1:9100 cannot be scraped"}
- exp_labels: {severity: page, job: api, instance: "10.0.0.2:9100"}
exp_annotations: {summary: "10.0.0.2:9100 cannot be scraped"}
- {eval_time: 20m, alertname: TargetMissing, exp_alerts: []}
- {eval_time: 25m, alertname: MetricMissing, exp_alerts: []}
- eval_time: 20m
alertname: ReplicasLow
exp_alerts:
- exp_labels: {severity: page, job: api}
exp_annotations: {summary: Fewer than 2 healthy api replicas}
- {eval_time: 20m, alertname: InstanceVanished, exp_alerts: []}
Both targets leave service discovery
This is the gone scenario. TargetDown is silent and TargetMissing fires. InstanceVanished names both instances at minute 20 and is clear at minute 26, which pins the self-clearing behavior.
# test_gone.yml: both targets leave service discovery at minute 10 (every series gets a stale marker)
rule_files:
- rules.yml
evaluation_interval: 1m
tests:
- interval: 1m
input_series:
- series: 'up{job="api", instance="10.0.0.1:9100"}'
values: '1x9 stale'
- series: 'up{job="api", instance="10.0.0.2:9100"}'
values: '1x9 stale'
- series: 'app_requests_total{job="api", instance="10.0.0.1:9100", path="/orders"}'
values: '0+600x9 stale'
- series: 'app_errors_total{job="api", instance="10.0.0.1:9100", code="500"}'
values: '0+300x9 stale'
alert_rule_test:
- {eval_time: 20m, alertname: TargetDown, exp_alerts: []}
- eval_time: 15m
alertname: TargetMissing
exp_alerts:
- exp_labels: {severity: page, job: api}
exp_annotations: {summary: Prometheus has no up series for job api}
- {eval_time: 25m, alertname: MetricMissing, exp_alerts: []}
- eval_time: 20m
alertname: ReplicasLow
exp_alerts:
- exp_labels: {severity: page, job: api}
exp_annotations: {summary: Fewer than 2 healthy api replicas}
# InstanceVanished names both instances, then clears itself once the 15 minute offset passes minute 10.
- eval_time: 20m
alertname: InstanceVanished
exp_alerts:
- exp_labels: {severity: ticket, job: api, instance: "10.0.0.1:9100"}
exp_annotations: {summary: "10.0.0.1:9100 stopped reporting"}
- exp_labels: {severity: ticket, job: api, instance: "10.0.0.2:9100"}
exp_annotations: {summary: "10.0.0.2:9100 stopped reporting"}
- {eval_time: 26m, alertname: InstanceVanished, exp_alerts: []}
The counters are renamed
This is the renamed scenario: up stays 1, the old counters end, and only MetricMissing fires.
# test_renamed.yml: an upgrade at minute 10 renames the counters; both targets stay healthy
rule_files:
- rules.yml
evaluation_interval: 1m
tests:
- interval: 1m
input_series:
- series: 'up{job="api", instance="10.0.0.1:9100"}'
values: '1x40'
- series: 'up{job="api", instance="10.0.0.2:9100"}'
values: '1x40'
- series: 'app_requests_total{job="api", instance="10.0.0.1:9100", path="/orders"}'
values: '0+600x9 stale'
- series: 'app_errors_total{job="api", instance="10.0.0.1:9100", code="500"}'
values: '0+300x9 stale'
alert_rule_test:
- eval_time: 21m
alertname: MetricMissing
exp_alerts:
- exp_labels: {severity: ticket, job: api}
exp_annotations: {summary: api is up but app_requests_total is gone}
- {eval_time: 21m, alertname: HighErrorRate, exp_alerts: []}
- {eval_time: 21m, alertname: TargetDown, exp_alerts: []}
- {eval_time: 21m, alertname: TargetMissing, exp_alerts: []}
- {eval_time: 21m, alertname: ReplicasLow, exp_alerts: []}
- {eval_time: 21m, alertname: InstanceVanished, exp_alerts: []}
One of two targets leaves
This is the one_gone scenario. TargetMissing and TargetDown are silent, ReplicasLow fires, and InstanceVanished names the missing instance, while HighErrorRate keeps firing because the remaining service is still failing.
# test_one_gone.yml: the second target leaves service discovery at minute 10; the first keeps failing requests
rule_files:
- rules.yml
evaluation_interval: 1m
tests:
- interval: 1m
input_series:
- series: 'up{job="api", instance="10.0.0.1:9100"}'
values: '1x40'
- series: 'up{job="api", instance="10.0.0.2:9100"}'
values: '1x9 stale'
- series: 'app_requests_total{job="api", instance="10.0.0.1:9100", path="/orders"}'
values: '0+600x40'
- series: 'app_errors_total{job="api", instance="10.0.0.1:9100", code="500"}'
values: '0+300x40'
alert_rule_test:
- {eval_time: 20m, alertname: TargetMissing, exp_alerts: []}
- {eval_time: 20m, alertname: TargetDown, exp_alerts: []}
- {eval_time: 25m, alertname: MetricMissing, exp_alerts: []}
- eval_time: 20m
alertname: ReplicasLow
exp_alerts:
- exp_labels: {severity: page, job: api}
exp_annotations: {summary: Fewer than 2 healthy api replicas}
- eval_time: 20m
alertname: InstanceVanished
exp_alerts:
- exp_labels: {severity: ticket, job: api, instance: "10.0.0.2:9100"}
exp_annotations: {summary: "10.0.0.2:9100 stopped reporting"}
- eval_time: 20m
alertname: HighErrorRate
exp_alerts:
- exp_labels: {severity: page}
exp_annotations: {summary: More than 5 percent of api requests fail}
Stale marker or samples that just stop
This one pins the timing facts from Step 9: the same alert fires at minute 15 after a stale marker and not before minute 19 after a gap. It uses the name: field, which gives each group in the file a readable label.
# test_gap.yml: how fast absent() notices depends on HOW the series stopped
rule_files:
- rules.yml
evaluation_interval: 1m
tests:
- name: a stale marker at minute 10 (target removed, scrape failed, metric dropped)
interval: 1m
input_series:
- series: 'up{job="api", instance="10.0.0.1:9100"}'
values: '1x9 stale'
alert_rule_test:
- {eval_time: 14m, alertname: TargetMissing, exp_alerts: []}
- eval_time: 15m
alertname: TargetMissing
exp_alerts:
- exp_labels: {severity: page, job: api}
exp_annotations: {summary: Prometheus has no up series for job api}
- name: the samples just stop after minute 9 (no stale marker, so the 5 minute lookback applies)
interval: 1m
input_series:
- series: 'up{job="api", instance="10.0.0.1:9100"}'
values: '1x9 _x40'
alert_rule_test:
- {eval_time: 18m, alertname: TargetMissing, exp_alerts: []}
- eval_time: 19m
alertname: TargetMissing
exp_alerts:
- exp_labels: {severity: page, job: api}
exp_annotations: {summary: Prometheus has no up series for job api}
No data at all
This one covers a job that Prometheus has never seen, for example because the deployment never happened or the job label in the rule is wrong. input_series: [] means no samples at all.
# test_nothing.yml: Prometheus has never seen any api series (never deployed, or the job label is wrong)
rule_files:
- rules.yml
evaluation_interval: 1m
tests:
- interval: 1m
input_series: []
alert_rule_test:
- eval_time: 10m
alertname: TargetMissing
exp_alerts:
- exp_labels: {severity: page, job: api}
exp_annotations: {summary: Prometheus has no up series for job api}
- eval_time: 10m
alertname: ReplicasLow
exp_alerts:
- exp_labels: {severity: page, job: api}
exp_annotations: {summary: Fewer than 2 healthy api replicas}
- {eval_time: 20m, alertname: MetricMissing, exp_alerts: []}
- eval_time: 10m
alertname: Watchdog
exp_alerts:
- exp_labels: {severity: none}
exp_annotations: {summary: The alerting pipeline is alive}
One script for the whole gate
Create ci.sh, the script your CI system runs on every change. With set -e the script stops at the first command that fails, and the build fails with it.
#!/bin/bash
# ci.sh: fail the build when the alert rules are malformed or any test fails
set -e
promtool check rules rules.yml
promtool test rules test_silent.yml test_labels.yml test_healthy.yml test_die.yml test_gone.yml test_renamed.yml test_one_gone.yml test_gap.yml test_nothing.yml
bash ci.sh
Checking rules.yml
SUCCESS: 7 rules found
Processing test file: test_silent.yml
SUCCESS
Processing test file: test_labels.yml
SUCCESS
Processing test file: test_healthy.yml
SUCCESS
Processing test file: test_die.yml
SUCCESS
Processing test file: test_gone.yml
SUCCESS
Processing test file: test_renamed.yml
SUCCESS
Processing test file: test_one_gone.yml
SUCCESS
Processing test file: test_gap.yml
SUCCESS
Processing test file: test_nothing.yml
SUCCESS
Nine files, nine SUCCESS lines. The first line also shows how many rules promtool check rules found, which is 7. If you only run the checker, a rule with a wrong label or a typo in a selector still passes, as you are about to see.
Plant mistakes and see whether the tests notice
A test suite that passes is only useful if it would fail for a wrong rule. The script mutants.py makes one small mistake at a time in a copy of rules.yml, runs all the tests against it, and reports which test files failed. The mistakes are plausible ones: a regex where an equality was needed, a typo in the job name, a missing or vector(0), a deleted guard, a for that is too long, an offset that is too short.
# mutants.py
"""Plant one mistake at a time in rules.yml and check that the promtool tests notice.
python mutants.py prints one line per planted mistake and a final count
"""
import os
import shutil
import subprocess
import tempfile
from pathlib import Path
HERE = Path(__file__).resolve().parent
PROMTOOL = str(Path(os.environ["PROM_DIR"]) / ("promtool.exe" if os.name == "nt" else "promtool")) if "PROM_DIR" in os.environ else "promtool"
TESTS = sorted(p.name for p in HERE.glob("test_*.yml"))
MUTANTS = [ # name, text to find (exactly once), replacement
("regex-selector", 'absent(up{job="api"})', 'absent(up{job=~"api.*"})'),
("typo-in-job", 'absent(up{job="api"})', 'absent(up{job="apii"})'),
("absent-over-time", 'absent(up{job="api"})', 'absent_over_time(up{job="api"}[5m])'),
("no-vector-0", '(count(up{job="api"} == 1) or vector(0)) < 2', 'count(up{job="api"} == 1) < 2'),
("threshold-1", '(count(up{job="api"} == 1) or vector(0)) < 2', '(count(up{job="api"} == 1) or vector(0)) < 1'),
("no-guard", ' and on() (up{job="api"} == 1)', ""),
("guard-inverted", ' and on() (up{job="api"} == 1)', ' and on() (up{job="api"} == 0)'),
("for-too-long", 'expr: absent(up{job="api"})\n for: 5m', 'expr: absent(up{job="api"})\n for: 30m'),
("down-equals-1", 'expr: up{job="api"} == 0', 'expr: up{job="api"} == 1'),
("offset-too-short", "offset 15m", "offset 1m"),
("wrong-severity", 'expr: up{job="api"} == 0\n for: 5m\n labels:\n severity: page',
'expr: up{job="api"} == 0\n for: 5m\n labels:\n severity: ticket'),
("error-threshold", "> 0.05", "> 0.9"),
("watchdog-never", "expr: vector(1)", "expr: vector(1) < 0"),
("watchdog-zero", "expr: vector(1)", "expr: vector(0)"),
]
def run_suite(rules_text):
with tempfile.TemporaryDirectory() as tmp:
Path(tmp, "rules.yml").write_text(rules_text, encoding="utf-8", newline="\n")
for name in TESTS:
shutil.copy(HERE / name, tmp)
done = subprocess.run([PROMTOOL, "test", "rules", *TESTS], cwd=tmp, capture_output=True, text=True, encoding="utf-8")
failed = []
for chunk in (done.stdout + done.stderr).split("Processing test file: ")[1:]:
name, rest = chunk.split("\n", 1)
if "SUCCESS" not in rest.split("FAILED", 1)[0]: # promtool prints the failure details after the file list
failed.append(name.strip())
return done.returncode, failed
def main():
rules = (HERE / "rules.yml").read_text(encoding="utf-8")
code, failed = run_suite(rules)
print(f"{'unchanged rules':<18} exit {code} failing test files: {len(failed)}")
caught = 0
survivors = []
for name, old, new in MUTANTS:
assert rules.count(old) == 1, (name, rules.count(old))
code, failed = run_suite(rules.replace(old, new))
if code == 0:
survivors.append(name)
print(f"{name:<18} exit {code} SURVIVED")
else:
caught += 1
print(f"{name:<18} exit {code} caught by {', '.join(failed)}")
print(f"\n{caught} of {len(MUTANTS)} planted mistakes made the suite fail; survivors: {', '.join(survivors) or 'none'}")
if __name__ == "__main__":
main()
python mutants.py
unchanged rules exit 0 failing test files: 0
regex-selector exit 1 caught by test_gap.yml, test_gone.yml, test_nothing.yml
typo-in-job exit 1 caught by test_die.yml, test_gap.yml, test_gone.yml, test_healthy.yml, test_nothing.yml, test_one_gone.yml, test_renamed.yml
absent-over-time exit 1 caught by test_gap.yml, test_gone.yml
no-vector-0 exit 1 caught by test_die.yml, test_gone.yml, test_nothing.yml
threshold-1 exit 1 caught by test_one_gone.yml
no-guard exit 1 caught by test_die.yml, test_gone.yml, test_nothing.yml
guard-inverted exit 1 caught by test_die.yml, test_renamed.yml
for-too-long exit 1 caught by test_gap.yml, test_gone.yml, test_nothing.yml
down-equals-1 exit 1 caught by test_die.yml, test_healthy.yml, test_one_gone.yml, test_renamed.yml
offset-too-short exit 1 caught by test_gone.yml, test_one_gone.yml
wrong-severity exit 1 caught by test_die.yml
error-threshold exit 1 caught by test_die.yml, test_healthy.yml, test_one_gone.yml, test_silent.yml
watchdog-never exit 1 caught by test_healthy.yml, test_nothing.yml
watchdog-zero exit 0 SURVIVED
13 of 14 planted mistakes made the suite fail; survivors: watchdog-zero
What the results say
Thirteen of fourteen mistakes make the suite fail. The right-hand column is worth reading: threshold-1, a replica threshold of 1 instead of 2, is caught only by test_one_gone.yml, and wrong-severity, the wrong routing label on TargetDown, only by test_die.yml. Delete either file and that mistake gets through. The one survivor is watchdog-zero, which changes vector(1) to vector(0). It is not a hole in the tests: as you saw in Step 10, the alert fires whatever the value, so the two rules behave identically.
See a failure with your own eyes
Edit rules.yml and delete and on() (up{job="api"} == 1) from the MetricMissing rule, then run the crash test:
promtool test rules test_die.yml
Processing test file: test_die.yml
FAILED:
alertname: MetricMissing, time: 25m,
exp:[],
got:[
0:
Labels:{alertname="MetricMissing", job="api", severity="ticket"}
Annotations:{summary="api is up but app_requests_total is gone"}
]
The failure names the alert, the minute and the labels of the alert that fired when none was expected. Put the guard back before you go on. Now try the typo. Change absent(up{job="api"}) in TargetMissing to absent(up{job="apii"}) and run the checker and the healthy test:
promtool check rules rules.yml
promtool test rules test_healthy.yml
Checking rules.yml
SUCCESS: 7 rules found
Processing test file: test_healthy.yml
FAILED:
alertname: TargetMissing, time: 20m,
exp:[],
got:[
0:
Labels:{alertname="TargetMissing", job="apii", severity="page"}
Annotations:{summary="Prometheus has no up series for job api"}
]
The checker is satisfied, because the file is valid YAML and the expression is valid PromQL. Only the test notices that the alert now fires on a healthy system, with the label job="apii" it copied from the typo. Change it back.
Step 12: Confirm the whole thing end to end
Run the complete lab with all seven rules in place and the gate once more. The first command takes about three and a half minutes, because it runs all five scenarios one after the other.
python live_lab.py
bash ci.sh
what each alert does in each scenario
errors die gone renamed one_gone
HighErrorRate FIRES RESOLVES RESOLVES RESOLVES stays
TargetDown - FIRES - - -
TargetMissing - - FIRES - -
MetricMissing - - - FIRES -
ReplicasLow - FIRES FIRES - FIRES
InstanceVanished - - fires, ends - fires, ends
Watchdog stays stays stays stays stays
Read the table by columns. errors is the only scenario where HighErrorRate is the right alert, and it fires there. In die the services crash, TargetDown and ReplicasLow fire, and the error alert resolves. In gone both targets leave discovery: TargetMissing, ReplicasLow and InstanceVanished fire, and TargetDown does not. In renamed only MetricMissing fires. In one_gone the job is partly gone: ReplicasLow and InstanceVanished fire and the three whole-job alerts do not. Every failure has an alert that names it, and nothing fires twice for the same cause. ci.sh should again print nine SUCCESS lines.
Common mistakes and how to avoid them
- Using
absent()on a metric that only appears after something happens. A counter with labels that has never been incremented does not exist, soabsent()fires on a perfectly healthy service. The instrumentation guidelines say: “Time series that are not present until something happens are difficult to deal with, as the usual simple operations are no longer sufficient to correctly handle them. To avoid this, export a default value such as 0 for any time series you know may exist in advance.” That is whyexporter.pyexports its error counter at 0 from the start. - Putting a regex in an
absent()selector. The labels disappear from the alert, and the routing that depends on them breaks. Use equality matchers, and add the labels you need in the rule itself. - Expecting one alert to cover every failure. Each of
TargetDown,TargetMissing,MetricMissingandReplicasLowcovers a different one, as the table in Step 12 shows. Keep all four. - Forgetting
or vector(0). Acount()alert that cannot fire at zero fails exactly when all replicas are gone. - Checking the rules only with
promtool check rules. It checks syntax and cannot see a wrong label, a typo in a selector or a missing guard. The unit tests can. - Trusting a pipeline you have never seen break. If nothing ever tests the route from Prometheus to a human, the watchdog is the only evidence that it works.
Where to go next
- Route the alerts. Send
severity: pageto the on-call receiver andseverity: ticketto a queue, and route the watchdog to an external heartbeat service. The Alertmanager post shows how to do that and how to test the routing tree. - Replace the hard-coded 2. In
ReplicasLowthe expected replica count is written into the rule. If your platform exports the number of replicas it intends to run, compare against that instead, so that scaling up does not need a rules change. - Add burn-rate alerts. The alerts here tell you that data is missing; the SLO post tells you how fast you are spending your error budget when data is present.
- Run the gate on every pull request.
ci.shneeds onlypromtool, so any CI system that can run a shell script can run it. - Try the real thing on your own exporter. Point the
job_nameinprometheus.ymlat a service you run, delete its target from the discovery file and see which of your alerts, if any, notices.
Sources and further reading
- Prometheus query functions:
absent()andabsent_over_time(), with the label examples thattest_labels.ymlchecks. - Querying basics: staleness, the lookback period and the
offsetmodifier. - Query operators:
and,orandunless. - Jobs and instances: the automatically generated
upseries. - Alerting rules:
for, the pending state and what makes an alert active. - Unit testing for rules: the sample notation with
_andstale,alert_rule_testandpromql_expr_test. - Instrumentation best practices: the “Avoid missing metrics” section.
- kube-prometheus runbook: Watchdog.
- scrape/scrape.go at v3.16.0, the failed-scrape and end-of-run staleness code, and discovery/manager.go at v3.16.0, the discovery update throttle.
- Prometheus v3.16.0 release.








No Comment! Be the first one.