Alerting That Actually Works
"Every time my pager goes off, I should be able to react with a sense of urgency. I can only do this a few times a day before I get fatigued." — Rob Ewaschuk, My Philosophy on Alerting (Google SRE, written for the chapter that became SRE Book ch. 6)
Summary: An alert is a request to interrupt a human, so it must be rare, urgent, actionable and about something users feel; everything else belongs on a dashboard, in a ticket or in a log. SLO burn-rate alerts page on how fast the error budget is being spent, the rest of the system (routing, grouping, heartbeats, on-call design, reviews) keeps that promise cheap to honour. Focus: Pages vs tickets vs logs, symptom-based vs cause-based alerts, static thresholds vs anomaly detection, precision, recall and time to detect, SLO-based alerting with multi-window multi-burn-rate rules (exact windows and thresholds), for duration, keep_firing_for and hysteresis, Alertmanager grouping, inhibition, silences and routing, severity and runbook annotations, on-call rotations, escalation policies and handoffs, pager fatigue metrics and alert review, dead man's switch and absent-data alerts, promtool test rules and blackbox probes, Grafana alerting, PagerDuty, Opsgenie, incident.io and Datadog monitors, queue-lag and job-SLA alerts, the postmortem feedback loop and the anti-patterns that make pagers useless. Learning goal: For any service, decide for each signal whether it is a page, a ticket or a dashboard line; write the multi-window multi-burn-rate rules for its SLO with real numbers; wire them through Alertmanager to an on-call schedule with a runbook; make silence itself alarming with a heartbeat; unit-test the rules; and run the weekly review that keeps the pager sustainable.
This chapter closes the Observability and Operations group's alerting half. It assumes the signals exist (Observability: Logs, Metrics, Traces and the Stack) and that you already have objectives to defend (SLAs, SLOs, SLIs & Error Budgets owns the definitions and the error budget policy; here we only use them). It links to Cascading Failures for why one failure creates a storm of alerts, Circuit Breaker and Load Shedding for the automation that should answer robotic problems, Chaos Engineering & Game Days for proving that the alerts fire, Secure SDLC, DevSecOps, Logging, Incident Response, Compliance & Breaches for the incident process that starts after a page, and Messaging Observability & Tracing and Dead Letter Queues for the broker metrics behind queue alerts.
Page map
| If you are looking for | Go to |
|---|---|
| The whole chapter in five tables | Everything in one minute |
| Why most alerting fails | Why it exists |
| Ewaschuk, SRE Book, SRE Workbook | Where it comes from |
| Page, ticket, log, report | Alert types |
| The questions every page must pass | The page test |
| Symptom or cause | Symptom-based vs cause-based |
| Static thresholds, anomaly detection | Thresholds |
| Precision, recall, time to detect | Alert quality |
| Burn rate, budget, windows | SLO-based alerting, Multi-window multi-burn-rate |
| Low traffic, 99.999% | Low traffic and extreme SLOs |
for, keep_firing_for, hysteresis, flapping | For duration and hysteresis |
| Grouping, inhibition, silences, routes | Alertmanager |
| Severity, annotations, runbook links | Severity and runbooks |
| Heartbeats, Watchdog | Dead man's switch |
| Missing metrics | Absent data |
| Rotations, escalation, handoffs | On-call design |
| Pager fatigue, alert review | Pager fatigue and review |
| Unit tests, probes | Testing alerts |
| PagerDuty, Opsgenie, Grafana, Datadog | Tooling |
| Queue lag, job misses | Queues and batch jobs |
| Feedback after incidents | Postmortem loop |
| What not to do | Anti-patterns |
| Exact knobs and arithmetic | Mechanics |
| Code | Go, Laravel |
| Classic failures and fixes | Solving the classic problems |
| Decision tables | Choosing |
| Monolith to many teams | In architecture |
| Replay of incidents with numbers | Lab |
| Beliefs, summary, quiz, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
What each kind of alert is for
| Output | Wakes a human? | Needs action within | Example | Where it goes |
|---|---|---|---|---|
| Page | Yes, any hour | Minutes | Checkout error budget burning 14.4x | PagerDuty, Opsgenie, phone |
| Ticket | No, business hours | Days | Disk fills in 4 days; 10% budget in 3 days | Jira, GitHub issue, queue |
| Report or digest | No | A week | Slow-query trend, certificate expiry in 30 days | Email digest, dashboard |
| Log or dashboard line | No | Never, only for diagnosis | CPU at 85%, one pod restarted | Grafana, Kibana |
| Auto-remediation | No | Seconds, by software | Restart a stuck consumer, scale out | Runbook automation, Kubernetes |
The five properties of a good page
| Property | Meaning | Source |
|---|---|---|
| Urgent | A human must react now, not after the weekend | Ewaschuk; SRE Book ch. 6 |
| Actionable | There is something to do; "it paged again" is not an action | Ewaschuk |
| Requires intelligence | A robotic response should be automated instead | SRE Book ch. 6 |
| Novel | About a problem not seen before; repeats become engineering work | SRE Book ch. 6 |
| User-visible, now or imminent | A symptom, or a definite cliff such as "N+0" or a full disk | Ewaschuk |
The multi-window multi-burn-rate table (99.9% SLO, 30 days; SRE Workbook table 5-8)
| Severity | Long window | Short window | Burn rate | Budget consumed | Time to exhaust if it continues |
|---|---|---|---|---|---|
| Page | 1 hour | 5 minutes | 14.4 | 2% | about 2.1 days |
| Page | 6 hours | 30 minutes | 6 | 5% | 5 days |
| Ticket | 3 days | 6 hours | 1 | 10% | 30 days |
Where alerts break, in order of how often
| Failure | What it looks like | Fix | Section |
|---|---|---|---|
| Too many | Pager fatigue, muted channels | Page on symptoms, review weekly | Pager fatigue |
| Too noisy | Flapping, storms | for, hysteresis, grouping, inhibition | For duration, Alertmanager |
| Too slow or blind | Outage found by customers | SLO burn rates, probes | Burn rate |
| Silent | No alert because nothing reported | Dead man's switch, absent() | Dead man's switch |
| Unowned | Alert with no runbook or owner | Routing by team, runbook_url | Severity |
The pipeline in one line
| Stage | Component | Knob to know |
|---|---|---|
| Measure | Exporter, instrumentation, blackbox probe | probe_success, SLI ratio |
| Decide | Prometheus rule, Grafana rule, Datadog monitor | expr, for, keep_firing_for |
| Reduce | Alertmanager | group_by, inhibit_rules, silences |
| Route | Alertmanager routing tree | matchers, continue, receiver |
| Notify | PagerDuty, Opsgenie, Slack, email, webhook | Escalation policy, schedule |
| Learn | Weekly review, postmortem | Alerts added, removed, demoted |
Why it exists
Monitoring produces data; alerting spends a human's attention. A system with a thousand metrics can notify nobody and still be well observed, while one noisy rule can wear down a whole team. The tension is between two costs.
| Under-alerting | Over-alerting |
|---|---|
| Customers find the outage before you do | The pager rings daily and every ring is ignored |
| Silent failures run for hours | The one real page is buried in noise |
| Error budget burns unseen | Engineers burn out and leave |
| Cheap to run, expensive on bad days | Costs every day, including the good ones |
Ewaschuk's own guidance leans one way: "Err on the side of removing noisy alerts – over-monitoring is a harder problem to solve than under-monitoring."
An everyday picture. A smoke detector. It is valuable because it is quiet 99.9% of the time and loud when there is fire. A detector that sounds every time you toast bread is unplugged within a week, and then it protects nobody. Alerting is the same economy: the credibility of the next page is spent by every false one.
Three common misunderstandings, up front
| Belief | Reality |
|---|---|
| "More alerts means safer" | Every extra alert lowers the response rate to all of them; precision matters more than coverage |
| "Alert on CPU, memory and disk so we see problems early" | Users do not feel CPU; alert on what they feel and keep resource graphs for diagnosis |
| "An alert is finished when it fires correctly" | It is finished when it has an owner, a runbook, a test and a review date; otherwise it becomes noise |
Where it comes from
The vocabulary comes from Google's SRE practice. Rob Ewaschuk, a Google SRE for seven years, wrote My Philosophy on Alerting as the foundation of what became chapter 6 of the Site Reliability Engineering book ("Monitoring Distributed Systems"). Its summary reads: "Pages should be urgent, important, actionable, and real." The book distilled it into four statements that this chapter keeps: urgency, actionability, intelligence and novelty. It also gave the taxonomy still used: the monitoring system's output is a page, a ticket or an email alert (SRE Book names them in that order), and the useful split of signals is white-box (internal metrics) vs black-box (probing from outside, "symptom-oriented and represents active—not predicted—problems").
The Site Reliability Workbook (2018), chapter 5 "Alerting on SLOs", turned philosophy into arithmetic. It walks six iterations: a fixed error-rate threshold on a 10-minute window; a longer window; a duration parameter; burn-rate alerts; multiple burn rates; and finally multiwindow, multi-burn-rate alerts, with the table of parameters used above. Its evaluation criteria are four: precision, recall, detection time and reset time.
The tooling grew in parallel. Prometheus (2012, SoundCloud; its alerting rules and Alertmanager came with it) made "alert = a PromQL expression plus a for duration" a standard shape. PagerDuty (founded 2009) and Opsgenie (Atlassian says it has been embedding Opsgenie in its platform since 2018, with end of sale on 4 June 2025 and a shutdown on 5 April 2027) popularised the on-call schedule and escalation policy as a product. The Prometheus and PagerDuty founding years are from general knowledge, not from a page fetched for this chapter (inference); the Opsgenie dates are from atlassian.com/software/opsgenie.
The concept catalogue
Alert types: page, ticket, report, log Must-know
In plain words: a page interrupts a person now, a ticket queues work for working hours, a report summarises slow-moving facts, and a log line only exists for whoever is investigating.
Common misunderstanding: "If it matters, it should page." Importance and urgency are different axes. A certificate expiring in 21 days is important and not urgent; it is a ticket. Ewaschuk calls these "sub-critical alerts" and says a quiet rotation depends on "a system for dealing with things that need timely response, but are not imminently critical".
Definition: Ewaschuk's vocabulary: a rule is any logic that detects a condition; an alert is the manifestation of a rule that intends to reach a human; a page is an alert that "tries to urgently and actively get the attention of a specific human". The SRE Book classifies the notification as ticket, email alert or page. Tickets work "as long as multiple firings of the same alert get correctly threaded into a single ticket", and fail without accountability for triage.
time Signal Class Who is told
1 10:02 checkout error budget burn 14.4x page on-call phone, 5 min to ack
2 10:02 disk /var/lib full in 3.5 days ticket payments queue, due Friday
3 10:03 p99 latency of /search at 900 ms for 3 min page? only if the latency SLO is burning
4 10:03 pod web-7f restarted once log none; kubectl events and dashboard
5 10:05 TLS certificate expires in 20 days ticket platform queueReal scenarios: (1) The payments team opens a ticket per slow-burn alert instead of paging at night; (2) a nightly backup that missed its window generates a ticket plus a morning Slack digest; (3) a disk that fills in 4 hours at the current rate pages, the same disk filling in 4 days is a ticket; (4) a rarely used internal tool has dashboards and no alerts at all.
| Channel | Interrupts | Accountability | Good for | Bad for |
|---|---|---|---|---|
| Phone/push page (PagerDuty, Opsgenie) | Yes | Ack and escalation | Active user pain | Anything that can wait |
| Chat message (Slack, Teams) | Soft | None unless a person replies | Context, low priority | The only channel for important alerts |
| No | None | Reports | Anything urgent; "email alerts nobody reads" is a named anti-pattern | |
| Ticket (Jira, GitHub) | No | Assignee and due date | Slow burns, capacity | Active outages |
| Dashboard | No | None | Diagnosis | Detection |
Fix / how to use it: give every rule a severity label with a fixed vocabulary (page, ticket, none), route on it (Alertmanager), and track tickets in a workflow system. Ewaschuk: "Every alert should be tracked through a workflow system. Don't only dump them into an email list or IRC channel."
The page test: urgent, actionable, intelligent, novel Must-know
In plain words: before a rule may wake someone, it must answer yes to a short list of questions.
Common misunderstanding: "A page is good if it correctly detected something." A correctly detected non-problem is still a bad page. The test is about the human, not the detector.
Definition: the SRE Book questions: Does this rule detect an otherwise undetected condition that is urgent, actionable, and actively or imminently user-visible? Will I ever be able to ignore this alert, knowing it is benign? Does it definitely indicate users are negatively affected (filtering out drained traffic and test deployments)? Can I act, and is that action urgent, or could it wait until morning, or be safely automated? Are other people getting paged for the same issue? Then the four statements: urgency "a few times a day before I become fatigued"; actionable; "Every page response should require intelligence"; "Pages should be about a novel problem or an event that hasn't been seen before."
Rule under review: "HighCPU > 85% for 5m" -> page
1 Urgent? No: users are not slow, CPU is a resource, not a symptom
2 Actionable? Unclear: scale out? find a hot loop? wait it out?
3 Intelligence? Often a scripted restart or scale-out -> automate
4 Novel? It fires every Monday at 09:00 -> expected load
5 Verdict Remove the page; keep CPU on the dashboard; alert on latency SLO burn insteadReal scenarios: (1) A batch job that fails and succeeds on retry pages every night; fix the retry, not the pager; (2) a "queue depth above 1000" page during the daily import is benign; (3) three teams are paged for one database failover and each starts debugging; (4) a cloud provider incident pages 40 people for a problem nobody can act on.
| Question | If the answer is no | Typical remedy |
|---|---|---|
| Is it user-visible now or imminent? | Not a page | Dashboard or ticket |
| Is it actionable? | Not a page | Fix the system or remove the rule |
| Does it need a human's judgment? | Not a page | Automate (restart, scale, failover) |
| Is it new? | Becomes engineering | Fix the root cause; a repeat is a bug |
| Is anyone else already paged? | Duplicate page | Inhibit, group, merge rules |
Fix / how to use it: keep the five questions in the pull-request template for alert rules and have the reviewer answer them. The diagram below shows the same flow.
Symptom-based vs cause-based alerts Must-know
In plain words: alert on what the user experiences (errors, slowness, stale data) and use the internal causes (full disk, dead replica, CPU) to explain it.
Common misunderstanding: "Cause alerts give early warning, so they are better." Ewaschuk: "Do your users care if your MySQL servers are down? No, they care if their queries are failing." Causes fire when nothing is wrong (a replica was retired on purpose) and stay silent when something is wrong in a way you did not foresee.
Definition: SRE Book: "The 'what's broken' indicates the symptom; the 'why' indicates a (possibly intermediate) cause." In a layered system "one person's symptom is another person's cause": slow database reads are a symptom for the database SRE and a cause for the frontend SRE. Users care about four things (Ewaschuk): availability and correctness, latency, completeness/freshness/durability, and features.
Symptom page (user-facing) Cause shown inside the page (not paged)
1 TooMany500StatusCodes: 10.7% 5xx for 3 min Also firing: UserDatabaseShardDown
2 Also firing: JanitorProcessNotKeepingUp
3 Also firing: FreshnessIndexBehind
-> the responder skims causes in one glance; the causes never paged anyone.Real scenarios: (1) "Users cannot check out" fires whether the cause is a database, a DNS change or a bad deploy; (2) "MySQL replica down" paged at night although traffic failed over cleanly; (3) quota exhaustion has no symptom until it is too late, so a predictive cause alert ("will run out in under 4 hours at the last hour's growth rate") is justified; (4) a 0.001% failure mode hides below the noise of a 99.99% service; the only handle is the cause.
| Situation | Alert on | Reason |
|---|---|---|
| Request failures, latency | Symptom, as high in the stack as the distinction still exists | One rule catches many causes |
| Quota, disk, memory cliff | Predictive cause, paged only when imminent | No symptom before it is too late |
| Known cause below symptom noise | Cause, with a clear owner | The only way to see it |
| Debugging aid | Show causes inside the page text or dashboard | Cheap, no extra pager |
| Redundant infrastructure | Capacity left (N+0 or N+1), not each node | Individual failures are expected |
Fix / how to use it: vantage point matters. Ewaschuk: "The best alerts in a layered client/server system come from the client's perspective", so alert on what the front-most load balancer or the calling service sees, including retries. Where the client is a real browser, treat the signal as noisy and avoid paging on it alone.
Thresholds: static, dynamic, anomaly detection Important
In plain words: a static threshold is a fixed line (error ratio > 1%); dynamic or anomaly detection learns a band from history and flags points outside it.
Common misunderstanding: "Machine-learned anomaly detection removes the need to choose thresholds." It moves the choice into the model's sensitivity, makes alerts harder to explain at 3 a.m. ("why is 4,310 req/s abnormal?") and produces false positives at deploys, holidays and growth. Ewaschuk's page rules are meant to be "simple to understand and represent a clear failure" (SRE Book wording).
Definition: static threshold: a constant bound on a value or ratio. Relative threshold: compare to a past period (rate(x[5m]) / rate(x[5m] offset 1w)). Dynamic baseline: moving average plus a multiple of standard deviation, or seasonal models. Anomaly detection: a statistical or ML model, offered as product features (Datadog "anomaly" and "forecast" monitors, Grafana plugins). Predictive threshold: extrapolate a trend (predict_linear in Prometheus).
Signal: requests per second, Tuesday 03:00 (normally 40 rps)
1 Static threshold rps < 200 fires every night (false positive)
2 Static threshold rps < 5 misses a 90% drop at noon (false negative)
3 Seasonal baseline rps < 0.5 * same hour last week fires on a real drop, and on Black Friday's aftermath
4 SLO burn rate error ratio vs budget ignores traffic shape entirelyReal scenarios: (1) A nightly traffic dip triggers a static "low traffic" alert; (2) a marketing campaign trains an anomaly detector to expect the new level for a week; (3) disk growth is a straight line, so predict_linear over a 6-hour window predicts a full disk reliably; (4) a business metric (orders per minute) uses a week-over-week ratio because it has strong seasonality and no SLO.
| Approach | Strength | Weakness | Use for |
|---|---|---|---|
| Static threshold | Predictable, explainable | Needs retuning as traffic changes | Ratios (error rate), saturation limits |
| Relative to last week | Handles seasonality simply | Wrong after holidays | Business volume |
predict_linear | Early, cause-level warnings | Assumes linear trend | Disk, quota, certificates |
| Anomaly detection (Datadog, Grafana plugins) | Finds unknown shapes | False positives, opaque | Tickets and exploration, rarely pages |
| SLO burn rate | Scale-free, ties to users | Needs an SLO and an SLI | The default for pages |
Fix / how to use it: ratios beat absolute counts because they are independent of traffic. Use anomaly detection to open tickets or annotate dashboards, and keep pages on rules a tired person can read.
Alert quality: precision, recall, time to detect, reset time Must-know
In plain words: how many of your alerts were real, how many real problems you caught, how fast you heard, and how fast the alert went away after recovery.
Common misunderstanding: "We can have a rule that is fast, never wrong and misses nothing." The Workbook shows each early iteration winning one property and losing another; tuning is a trade-off, not a search for the perfect threshold.
Definition: the Workbook's four attributes. Precision: "The proportion of events detected that were significant." Recall: the proportion of significant events detected. Detection time: how long before notification. Reset time: how long the alert stays up after the issue is resolved. In Ewaschuk's accountability rule: "Alerts that are less than 50% accurate are broken; even those that are false positives 10% of the time merit more consideration." A false positive is a page without a real problem; a false negative is a real problem without a page.
Rule: error ratio over the last 10 minutes > 0.1% (99.9% SLO)
1 Precision low: a 0.1% error rate for 10 minutes consumes only 0.02% of the monthly budget
2 Recall high: any error rate above the SLO is caught
3 Detection fast: 10 minutes at most for a total outage
4 Reset fast: 10 minutes after the problem ends
-> good recall and speed, terrible precision: the pager rings for things that do not matterReal scenarios: (1) The naive rule above pages for a brief blip and for a harmless 0.12% brownout; (2) a rule that needs a one-hour for has high precision and 100% outages wait the full hour (Workbook: a 100% outage consumes 140% of the 30-day budget in that hour); (3) a 35x burn that never alerts consumes the whole 30-day budget in 20.5 hours; (4) a rule that needs 15 minutes of data resets slowly and pages again after the fix.
| Property | Question | Raised by | Hurt by |
|---|---|---|---|
| Precision | Of the pages, how many mattered | Larger budget share, longer window, burn rates | Tiny thresholds, short windows |
| Recall | Of the incidents, how many paged | Multiple burn rates, lower thresholds | Single high-severity rule |
| Detection time | How soon | Short windows, high burn | Long for, long windows |
| Reset time | How soon it clears | A short second window | One long window |
| Cost | CPU and memory to evaluate | Recording rules | Long ranges evaluated raw |
Fix / how to use it: measure them. The review query in the SQL block gives precision as "pages that led to action"; recall comes from postmortems asking "which incidents did no alert catch?".
SLO-based alerting and burn rate Must-know
In plain words: instead of asking "is the error rate high?", ask "at this rate, how soon do we run out of the errors we are allowed?". The speed of spending is the burn rate.
Common misunderstanding: "Burn rate 1 is a problem." Burn rate 1 means the budget runs out exactly at the end of the SLO window, which is the plan. It matters only because sustained burn above 1 will exhaust the budget early.
Definition: with SLO objective O over period P, the error budget is 1 - O. The burn rate is the observed error ratio divided by the budget. The Workbook: "Burn rate is how fast, relative to the SLO, the service consumes the error budget." The budget consumed during an alert window W at burn B is B x W / P; the time to fire from a clean state is (1 - O) / error ratio x W x B. For the definitions of SLI, SLO and error budget see SLAs, SLOs, SLIs & Error Budgets.
99.9% SLO over 30 days: budget = 0.1% of requests = 43.2 minutes of total outage
1 burn 1 error ratio 0.1% budget lasts 30 days
2 burn 2 error ratio 0.2% 15 days
3 burn 6 error ratio 0.6% 5 days
4 burn 10 error ratio 1% 3 days
5 burn 14.4 error ratio 1.44% about 50 hours; 2% of budget goes in 1 hour
6 burn 1000 error ratio 100% about 43 minutesReal scenarios: (1) A checkout API at 99.9% fails 5% of requests after a bad deploy: burn 50, the budget is gone in 14.4 hours; (2) a slow memory leak yields 0.15% errors for days: burn 1.5, no page, a ticket before the month is over; (3) a quiet night with 0.05% errors never matters; (4) a dependency that fails 100% for 10 minutes spends 23% of the monthly budget (10 min of 43.2 min).
| Threshold style | Counts | Scale-free | Ties to user promise |
|---|---|---|---|
| Static error rate | Errors per window | No | Weakly |
| Burn rate | Budget spent per time | Yes | Yes |
| Predictive disk or quota | Time to exhaustion | Yes | Indirectly |
Fix / how to use it: record one error-ratio series per window with a Prometheus recording rule, then compare each to factor x budget (slo-rules.yml). The SLI must count good vs total events (requests, jobs, freshness checks); the SRE Book's example SLIs (availability, latency, freshness, durability) all work.
Multi-window, multi-burn-rate alerts Must-know
In plain words: page when the budget is being spent fast enough to matter (long window) and is still being spent right now (short window); use several speeds so that slow leaks become tickets instead of being missed.
Common misunderstanding: "A for: 1h clause gives the same result as a one-hour window." It does not. The Workbook: "Because the duration does not scale with the severity of the incident, a 100% outage alerts after one hour, the same detection time as a 0.2% outage." And a series of 5-minute 100% error spikes every 10 minutes "never triggers an alert, despite consuming 35% of the error budget".
Definition: the Workbook's sixth iteration. A policy fires when the error ratio exceeds burn x (1 - SLO) in both a long window and a short window; the short window is "a good guideline" at 1/12 of the long window. Starting parameters for a 99.9% SLO: page at burn 14.4 over 1h and 5m (2% of budget); page at burn 6 over 6h and 30m (5%); ticket at burn 1 over 3d and 6h (10%). The Workbook's text also lists a variant ticket pair (burn 3 over 24h and 2h) in the rule listing; table 5-8 uses the three-row form.
Event: 15% errors for 10 minutes, then a fix (SRE Workbook figure 5-6 scenario)
1 t=0 errors start; both averages begin to rise
2 t=6 min the 1h average passes 1.44% (15% x 6/60 = 1.5%); the 5m average is already above -> PAGE
3 t=10 min errors stop
4 t=15 min the 5m average drops below 1.44% -> alert resolves
5 t=70 min the 1h average finally drops below 1.44% (a long-only alert would stay up this long)Real scenarios: (1) A bad deploy returns 5xx on 5% of checkout calls: the 1h/5m pair pages after about 18 minutes (the lab measures it); (2) a 1% error leak pages at 3h37m through the 6h/30m pair; (3) a 0.3% burn opens a ticket after 24 hours; (4) a one-minute blip at 5% does not page at all.
| Policy | Long | Short | Burn | Threshold ratio (99.9%) | First fired in the replay |
|---|---|---|---|---|---|
| fast-burn (page) | 1h | 5m | 14.4 | 1.44% | 100% errors: 1 minute; 5% errors: 18 minutes; 1% errors: never |
| slow-burn (page) | 6h | 30m | 6 | 0.6% | 1% errors: 3h37m (5.02% of budget gone) |
| trickle (ticket) | 3d | 6h | 1 | 0.1% | 0.3% errors: 24h01m; 0.12% errors: 60h |
Fix / how to use it: PromQL for the pair, from the Workbook form (full file in Prometheus rules). Remember suppression: one outage satisfies several policies, and Alertmanager inhibition should keep the lower-severity ones quiet (Alertmanager).
Low traffic and extreme SLOs Important
In plain words: with ten requests an hour, one failure is a 10% error rate and looks like a catastrophe; at 99.999% the budget lasts seconds. The standard recipe breaks at both ends.
Common misunderstanding: "Burn-rate alerts work for every service unchanged." The Workbook warns that for a 99.9% SLO, one failure out of ten hourly requests is a 1,000x burn rate "and would page immediately, as it consumed 13.9% of the 30-day error budget", and that a 90% SLO can never fire the 2%-per-hour page because a 100% outage "consumes only 1.4% of the budget in that hour".
Definition: the Workbook's options for low traffic: generate artificial traffic (probers, integration tests; downside: successful synthetic requests can hide real user errors), combine small services into one group, change the product so more requests are needed to count as a failure (client retries with backoff and jitter, fallbacks), or lower the SLO or lengthen the window. For extreme goals: a 100% outage at 99.999% availability "would exhaust its budget in 26 seconds", which is shorter than a scrape interval; defend it by design (roll out to 1% of users first) rather than by paging.
Low-traffic example, 99.9% SLO, 10 requests per hour
1 10:00 1 request fails hourly ratio 10% = 100x the 0.1% budget (burn 100 on the 1h window)
2 10:00 page fires immediately 13.9% of the 30-day budget in one request
3 guard MinEvents=200 in the long window -> rule stays silent; a synthetic prober adds 60 requests/hourReal scenarios: (1) An internal admin API with 20 users: add a synthetic prober; (2) a back-office batch with 300 jobs a day: alert on job SLA misses instead of per-request errors; (3) a payment gateway with three nines promise over a year, not a month: lengthen the window; (4) several tiny microservices behind one product: aggregate by product.
| Technique | Cost | Risk |
|---|---|---|
| Synthetic traffic (blackbox_exporter, k6 cron) | Prober upkeep | Hides real user errors if probes always succeed |
| Aggregate small services | Coarser signal | A single service can be fully down without paging |
| Minimum events guard | Extra clause | A real outage at very low volume is missed |
| Lower SLO or longer window | Product decision | Changes the user promise and the error budget policy |
Fix / how to use it: the Go evaluator has a MinEvents field and returns "only N events" instead of firing; the Laravel evaluator mirrors it with min_events.
The for duration, keep_firing_for, hysteresis and flapping Must-know
In plain words: for says "only fire if it stays bad for this long"; hysteresis says "start at 80 but only stop below 70"; keep_firing_for says "after it clears, stay firing a bit longer so a blip in the data does not resolve it".
Common misunderstanding: "for: 5m makes an alert 5 minutes more accurate." It makes it five minutes slower, and for SLO rules it destroys the link between severity and speed. Use it for resource conditions and probes; use windows for ratios.
Definition: Prometheus alerting rule fields: for ("causes Prometheus to wait for a certain duration between first encountering a new expression output vector element and counting an alert as firing"; elements that are active but not firing are pending), and keep_firing_for ("to keep this alert firing for the specified duration after the firing condition was last met. This can be used to prevent situations such as flapping alerts, false resolutions due to lack of data loss"). Hysteresis is not a Prometheus keyword; it is the pattern of separate fire and resolve thresholds, available as the "recovery threshold" in several SaaS tools (Datadog metric monitors; verify in your product).
rule: fire above 80, resolve below 70, for 2m, keep_firing_for 1m
1 00:00 value 85 inactive -> pending
2 00:01 value 79 pending: active only if above 80 -> back to inactive (spike absorbed)
3 00:02 value 85 inactive -> pending
4 00:04 value 86 pending -> firing (held for 2 minutes)
5 00:05 value 75 firing: 75 is above the resolve line 70, stays firing
6 00:06 value 65 below 70: keep_firing_for starts
7 00:07 value 65 one minute later -> resolvedReal scenarios: (1) A probe flaps on a lossy link: for: 3m plus keep_firing_for: 5m; (2) CPU hovering near its limit alternates fire and resolve every minute without hysteresis; (3) a scrape gap resolves an alert falsely and re-fires it on the next scrape (keep_firing_for); (4) Alertmanager group_interval batches the flapping into one notification per 5 minutes.
| Mechanism | Where | Delays the page | Delays the resolve | Prevents |
|---|---|---|---|---|
for | Prometheus rule | Yes | No | Spikes |
keep_firing_for | Prometheus rule | No | Yes | Flapping, false resolves |
| Hysteresis (two thresholds) | Rule logic, SaaS recovery threshold | No | Yes | Flapping around a line |
group_wait | Alertmanager | Yes (30 s default) | No | First-notification storms |
group_interval | Alertmanager | No | Batches updates (5 min default) | Update spam |
| Multi-window | Rule expression | No | Faster reset | Long reset time |
Fix / how to use it: the Go rule package implements all three (for, keep-firing, hysteresis) plus a NoData policy and is unit-tested; see Go.
Alertmanager: grouping, inhibition, silences, routing Must-know
In plain words: Prometheus decides which alerts are firing; Alertmanager decides who hears about them, once, and in which order. It merges duplicates, bundles related alerts into one message, mutes the ones made pointless by a bigger failure, and sends the result to the right team.
Common misunderstanding: "Silences fix noisy alerts." A silence mutes a notification for a time; the rule still fires and the cause is still there. Silences are for maintenance windows and known issues under repair, not for tuning.
Definition: Alertmanager "takes care of deduplicating, grouping, and routing" and "silencing and inhibition of alerts". Grouping "categorizes alerts of similar nature into a single notification" (e.g. group by cluster and alertname so a network partition produces one page, not hundreds). Inhibition "is a concept of suppressing notifications for certain alerts if certain other alerts are already firing" (a target alert is muted while a source alert exists and both share the labels in equal). Silences mute alerts for a given time, matched with the same matchers as routes. The routing tree matches alert labels to receivers; with continue: true an alert keeps matching later siblings; mute_time_intervals and active_time_intervals restrict routes by time and are not inherited.
alerts: ServiceDown x120 (cluster=eu-1, one per instance) arrive within 40 s
1 t=0 s first alert arrives; group key = {alertname, cluster}; wait group_wait (30 s)
2 t=30 s ONE notification for the group, listing all 120 instances
3 t=40 s ClusterUnreachable(eu-1) fires; an inhibit rule (equal: cluster) mutes the other eu-1 alerts
4 t=5 m group_interval: new or resolved members are batched into one update
5 t=4 h repeat_interval: still firing -> reminderReal scenarios: (1) A network partition cuts half the pods from the database: one grouped page instead of hundreds; (2) a datacenter loses power: ClusterUnreachable inhibits everything else with equal: [cluster]; (3) planned database maintenance: a silence for instance=db-3 for two hours; (4) a ticket-level alert routes to a queue only in business hours via active_time_intervals (outside those hours the route does not match, so the alert falls through to the default Slack receiver).
| Setting | Default | Effect | Typical choice |
|---|---|---|---|
group_by | none (one group for all) | What goes into one notification | [alertname, cluster, service] |
group_wait | 30 s | Delay before the first notification | 30 s for pages, 0 for the heartbeat |
group_interval | 5 m | Batching of changes in a group | 5 m |
repeat_interval | 4 h | Reminder if nothing changed; rounded up to a multiple of group_interval | 4 h pages, 24 h tickets |
continue | false | Keep matching sibling routes | true for "also notify the audit channel" |
mute_time_intervals | none | Route muted during these times | Holidays for chat-only routes |
active_time_intervals | none | Route active only during these times | Business hours for tickets |
inhibit_rules | none | Source mutes target when equal labels match | Cluster-down mutes the rest |
resolve_timeout | 5 m | When an alert without an end time is considered resolved | default |
An alert that matches both the source and the target side of an inhibit rule cannot be inhibited by itself; the docs recommend choosing matchers so alerts never match both sides.
Fix / how to use it: the repository's alertmanager.yml routes the Watchdog to a heartbeat receiver, pages by team, sends tickets to a webhook in business hours, and has two inhibit rules (cluster-down and page-mutes-its-own-ticket).
Severity levels, annotations and runbook links Must-know
In plain words: every alert says how bad it is, who owns it, what it means and where to read what to do. The responder should not have to search.
Common misunderstanding: "A runbook is a long flow chart of every possible cause." Ewaschuk: "if your playbook has a long detailed flow chart, you're potentially spending too much time documenting what could be wrong and too little time fixing it". The best entries are short: what the alert means and what is currently interesting about it.
Definition: Prometheus rule labels identify and route (severity, team, service); annotations carry text for humans (summary, description, runbook_url, dashboard). Labels are part of alert identity; annotations are not. PagerDuty Events API v2 carries payload.severity as one of critical, error, warning, info and a dedup_key that correlates trigger, acknowledge and resolve events.
Event-API lifecycle for one incident (PagerDuty Events API v2)
1 POST /v2/enqueue event_action=trigger dedup_key=slo:checkout:fast-burn -> alert opens
2 POST /v2/enqueue event_action=trigger same dedup_key -> logged on the same alert
3 on-call acknowledges in the app -> no more notifications
4 POST /v2/enqueue event_action=resolve same dedup_key and routing_key -> alert resolved
5 POST /v2/enqueue event_action=trigger same dedup_key after resolve -> a NEW alertReal scenarios: (1) severity: page routes to the pager, severity: ticket to the queue, and severity: none (Watchdog) to the heartbeat service; (2) a rule without runbook_url fails the CI lint; (3) a team label lets the platform team page the database owners without a human router; (4) description includes $value so the responder sees the number.
| Severity | Meaning | Delivery | Response |
|---|---|---|---|
| page (critical) | Users hurt now or certain soon | Phone and push, escalation after 5 minutes | Acknowledge, mitigate |
| ticket (warning) | Will hurt within days | Queue, business hours | Triage by owner |
| info | For context | Chat or none | Nobody |
| none | Plumbing such as Watchdog | Heartbeat receiver | Silence is the alarm |
Fix / how to use it: lint rules in CI: every page rule must have team, summary and runbook_url; every ticket rule must have team. Keep severity names few and fixed.
Dead man's switch and heartbeat alerts Must-know
In plain words: most alerts fire when something bad happens; a dead man's switch fires when something stops happening. A job or the alerting pipeline itself must keep checking in; if it goes quiet, a separate system raises the alarm.
Common misunderstanding: "If the monitoring is broken we will see it." Nothing looks different when a broken Alertmanager sends no alerts: all quiet and no coverage are indistinguishable.
Definition: a heartbeat check expects a ping within period + grace. healthchecks.io describes it as a service that notifies when a periodic process does not report on time and supports /start, /fail and /<exitcode> suffixes on the ping URL. The Prometheus convention is an always-firing Watchdog alert (expr: vector(1)) routed to an external receiver which pages when the heartbeat stops. Laravel's scheduler can ping around a task with pingBefore, thenPing, pingOnSuccess and pingOnFailure.
t Event Heartbeat receiver
1 00:00 Watchdog fires; Alertmanager sends last seen 00:00
2 00:01 repeat (group_interval 1m) last seen 00:01
3 00:02 Alertmanager crashes -
4 00:03 (nothing arrives) waiting, within period + grace
5 00:06 grace elapsed PAGE: "alerting pipeline silent"Real scenarios: (1) The nightly backup stops running because cron was disabled; no error exists to alert on; (2) Prometheus loses its storage and rules stop evaluating; (3) the Laravel scheduler container is not running; every scheduled command is silently skipped; (4) the SLO evaluator throws before notifying.
| Pattern | Detects | Needs |
|---|---|---|
| Watchdog alert to external receiver | Prometheus, Alertmanager, notifier or network path broken | A receiver outside your cluster |
| Job pings healthchecks.io, Cronitor, Dead Man's Snitch | Cron, scheduler or worker not running | An account and a grace time |
absent() on the job's metric | Metric missing from scrape | Metric pushed by the job (Pushgateway) |
| Canary job | Queue workers not consuming | A scheduled dispatcher |
Fix / how to use it: the Go heartbeat package is a Registry with Expect, Beat, Check and an HTTP Handler, plus a Watchdog wrapper; the Laravel routes file pings the check around slo:evaluate.
Alerting on absent data Important
In plain words: a missing number is not a zero. A rule that says "errors above 1%" stays silent when the metric disappears, which is exactly when you have an outage in your monitoring.
Common misunderstanding: "No data means no errors." The error ratio of a target that stopped reporting is undefined, not 0%. Prometheus absent(v) "returns an empty vector if the vector passed to it has any elements" and a one-element vector with value 1 otherwise; absent_over_time does the same for a range.
Definition: three layers: (1) up/target health (up == 0); (2) explicit absence of a series (absent, absent_over_time); (3) the alert system's own treatment of missing data (Grafana-managed alert rules support "handling of error and no data states" per rule; Datadog monitors have a "notify on no data" option, from product knowledge, verify in your tenant).
Scrape of job=checkout fails from 02:10
1 02:10 no samples for http_requests_total{job="checkout"}
2 02:10 rate(...) over 5m still returns old data until the window empties
3 02:15 rate returns nothing; "error ratio > 1.44%" evaluates to nothing -> silent
4 02:15 absent(sum(rate(http_requests_total{job="checkout"}[5m]))) returns 1 -> pending
5 02:20 for: 5m elapsed -> CheckoutMetricsAbsent firesReal scenarios: (1) A deploy renames a metric and every SLO rule silently stops working; (2) a firewall change breaks scraping of one namespace; (3) a recording rule's input has a typo; (4) a Grafana alert on a query that returns no rows stays Normal while the service is down, unless "No Data" is handled.
| Tool | How absence is expressed | Default if you do nothing |
|---|---|---|
| Prometheus | absent(), absent_over_time(), up == 0 | Rule returns empty: not firing |
| Grafana-managed rules | Per-rule no-data and error handling | Configurable; read the state mapping |
| Datadog monitors | "Notify if data is missing" option | Verify per monitor |
| Heartbeat services | Missing ping after period + grace | Down |
Fix / how to use it: pair each SLO rule with an absent rule on its input and a test that proves it fires (Testing); make the Go evaluator return ok=false and never treat it as zero errors.
On-call design: rotations, escalation, handoffs Must-know
In plain words: an on-call schedule says who is reachable; an escalation policy says who is tried next if they are not; a handoff transfers the context at shift change.
Common misunderstanding: "On-call is a heroic duty some people are good at." It is a load that must stay under a limit. The SRE Book: no more than 25% of an SRE's time on-call, and measurable operational overload goals such as "paging events per shift < 2".
Definition: the SRE Book's rotation: primary and secondary, week-long shifts; "the minimum number of engineers needed for on-call duty from a single-site team is eight" (with two people on call and the 25% rule); dual-site teams a reasonable minimum of six each, and a multi-site "follow the sun" rotation avoids night shifts. The PagerDuty incident-response guide: "Always have a backup schedule", "A backup shift should generally come directly after a primary shift" so the previous primary can pass on context, the third escalation level is probably the entire team, "We recommend you set your escalation timeout to 5 minutes", new members shadow, "Don't acknowledge an incident out from under someone else", "Never hesitate to escalate".
Escalation policy: payments-pager
1 t=0 min notify primary (push) primary acknowledges -> stop
2 t=1 min notify primary (SMS, then phone call every minute)
3 t=5 min timeout: notify secondary (push, SMS, phone)
4 t=10 min timeout: notify the engineering manager and the whole team channel
5 handoff Monday 10:00: outgoing primary posts open issues, silences, flaky alerts in the handoff noteReal scenarios: (1) A two-person team cannot sustain 24/7; they use a business-hours rotation and a weaker SLO; (2) the secondary rotation is the previous primary, so context flows; (3) a swap is arranged for a conference week; (4) a night page is followed by the next-day compensation (time off) so fatigue does not accumulate.
| Design choice | Good default | Pitfall |
|---|---|---|
| Rotation length | One week, follow-the-sun if multi-site | Daily rotations lose context |
| Rotation size | At least 6 to 8 engineers | Burnout for small teams |
| Backup | Always, directly after the primary | "Whoever is free" |
| Escalation timeout | 5 minutes | Too long: users wait; too short: chaos |
| Handoff | Written note plus a short sync | Silent switch at midnight |
| Compensation | Time off or pay | Unpaid heroics |
| Training | Shadow rotation, game days | Learning in production |
Fix / how to use it: encode schedules and policies in PagerDuty, Opsgenie or incident.io, not in a wiki table; test the escalation path once a quarter with a fake page (Chaos Engineering covers game days).
Pager fatigue metrics and the alert review Must-know
In plain words: measure how often the pager rings, how often it was worth it and how often it rang at night; then review the worst offenders every week and fix or delete them.
Common misunderstanding: "We know the noisy alerts; we will fix them when we have time." Ewaschuk: "Track your pages, and all your other alerts. If a page is firing and people just say 'I looked, nothing was wrong', that's a pretty strong sign that you need to remove the paging rule, or demote it". A weekly review and quarterly statistics keep the picture "lost when the pager is handed from one human to the next".
Definition: metrics worth recording per alert and per shift: pages per shift (SRE Book target: under 2), night-time pages, percentage actionable, time to acknowledge, time to resolve, repeat pages of the same alert, tickets opened and closed, and the "alert-to-incident" ratio. A review meeting walks the top N alerts by count and the pages with no action taken.
-- alert_events is filled by an Alertmanager webhook (fired) and by PagerDuty (ack/resolve)
CREATE TABLE alert_events (
id bigserial PRIMARY KEY,
alertname text NOT NULL,
team text NOT NULL,
severity text NOT NULL, -- page | ticket
fired_at timestamptz NOT NULL,
acked_at timestamptz,
resolved_at timestamptz,
actionable boolean, -- set by the responder: did I do anything?
postmortem text -- link, if it led to one
);
-- Weekly review: noisiest and least useful pages of the last 7 days
SELECT alertname,
count(*) AS pages,
round(100.0 * avg((actionable IS TRUE)::int), 1) AS pct_actionable,
count(*) FILTER (WHERE extract(hour FROM fired_at) NOT BETWEEN 8 AND 20) AS night_pages,
percentile_cont(0.5) WITHIN GROUP (ORDER BY acked_at - fired_at) AS median_ack
FROM alert_events
WHERE severity = 'page' AND fired_at > now() - interval '7 days'
GROUP BY alertname
ORDER BY pages DESC, pct_actionable ASC
LIMIT 10; Weekly alert review (30 minutes, same agenda every week)
1 Open the SQL result: top 10 alerts by pages, pct_actionable under 50 are "broken" (Ewaschuk)
2 For each: delete, demote to ticket, fix the cause, or tune (window, for, grouping)
3 Check pages per shift against the target (under 2) and night pages
4 Review last week's tickets: any older than their due date?
5 Record decisions in the rule's git historyReal scenarios: (1) A rule at 12% actionable is demoted to a ticket; (2) a flapping probe is given keep_firing_for; (3) the team sees seven night pages in a week and pauses feature work (SRE Book: operational overload is corrected by the team and leadership); (4) a new rule is run in "info" for two weeks to vet its rate before it may page.
| Metric | Healthy | Warning | Action |
|---|---|---|---|
| Pages per on-call shift | under 2 | 2 to 5 | Review; fix top rules |
| Share of pages that were actionable | over 90% | under 50% = broken | Demote or delete |
| Night pages per week | 0 to 1 | 3 or more | Page only on SLO burn; automate |
| Median time to acknowledge | under 5 minutes | over 5 | Check escalation, device settings |
| Repeats of the same alert in 7 days | 0 | 3 or more | Root-cause work, not more acks |
| Open tickets older than due date | 0 | growing | Staffing problem, say so honestly |
Fix / how to use it: make "actionable?" a one-click field in the incident tool; without it precision is a guess.
Testing alerts: rule unit tests and synthetic probes Must-know
In plain words: an alert you have never seen fire might never fire. Feed fake data to the rule and check what it says, and send fake users through the real system.
Common misunderstanding: "Testing alerts means breaking production." Rule logic is testable offline with promtool test rules; production is only needed for the end-to-end path, which a probe or a game day covers.
Definition: promtool test rules test.yml loads rule_files, feeds input_series with a compact notation (0x10 1x20 = eleven zeros, then twenty-one ones; 0+10x30 an increasing series), evaluates at eval_time relative to start_timestamp, and compares against exp_alerts (labels and annotations). An empty exp_alerts asserts "not firing". blackbox_exporter probes targets over HTTP, HTTPS, DNS, TCP, ICMP and gRPC and exposes probe_success; Prometheus passes target and module as parameters (/probe?target=prometheus.io&module=http_2xx).
promtool test rules slo-rules-test.yml (expected, not run on this machine)
1 case 1 outage: both ratios 1 from minute 11; at 5m no alert, at 15m CheckoutErrorBudgetFastBurn fires
2 case 2 recovered: the 5m ratio drops to 0, the 1h ratio stays 0.05 -> must not fire
3 case 3 metric absent: with only job=other present, CheckoutMetricsAbsent fires after for: 5m
4 case 4 Watchdog always fires
SUCCESSReal scenarios: (1) A rule refactor changes a label name; the unit test fails in CI before deploy; (2) a blackbox probe of the login page detects the TLS certificate expiring; (3) a game day shuts a replica to verify that no page fires for redundant capacity; (4) a staging end-to-end test asserts that a synthetic error burst reaches PagerDuty's test service.
| Test level | Tool | Catches | Misses |
|---|---|---|---|
| Rule logic | promtool test rules | Wrong expression, thresholds, labels, annotations, for | Real data shape, delivery |
| Config syntax | promtool check rules, amtool check-config | YAML errors | Behaviour |
| Routing | amtool config routes test --config.file=alertmanager.yml severity=page team=payments | Wrong receiver | Receiver outage |
| End to end | Synthetic probe or fake incident | Whole path including paging | Rare combinations |
| Game day | Chaos experiment | Human response, runbooks | None of the above, done rarely |
Fix / how to use it: run all four in CI; give the Alertmanager config its own test of the routes that matter (page for each team, ticket, Watchdog).
Tooling landscape Good to know
In plain words: one piece decides (rule engine), one reduces (alert manager), one wakes people (on-call product). Some products do several.
Common misunderstanding: "The tool is the strategy." Moving from one pager product to another changes nothing about precision.
Definition: Prometheus plus Alertmanager (open source; rules in YAML, routing tree, silences and inhibition). Grafana alerting: Grafana-managed rules over many data sources with expressions, labels and annotations, no-data and error handling, notification policies and contact points, plus data source-managed rules. PagerDuty: on-call, escalation policies, Events API v2 (routing_key, event_action, dedup_key, payload.severity). Opsgenie: Atlassian ended sales on 4 June 2025 and shuts the product down on 5 April 2027, moving its capabilities into Jira Service Management (from Atlassian's page, which says Opsgenie "will be shut down" on that date). incident.io: on-call schedules and escalation paths plus incident response in Slack. Datadog monitors: threshold, anomaly, forecast, composite and SLO monitors (product knowledge; the monitors page was not detailed enough to quote).
One alert through a typical stack
1 app emits http_requests_total -> Prometheus scrapes every 15 s
2 rule CheckoutErrorBudgetFastBurn evaluates -> state pending, then firing
3 Alertmanager groups, applies inhibition -> receiver payments-pager
4 PagerDuty creates an incident, pages primary -> acknowledgement or escalation after 5 min
5 responder opens runbook_url and dashboard -> mitigates, resolves; resolve event with the same dedup_key| Product | Role | Config | Strength | Watch out for |
|---|---|---|---|---|
| Prometheus + Alertmanager | Rules and routing | YAML in git | Testable, label-based | You run it; HA needs two Alertmanagers |
| Grafana alerting | Rules, routing, UI | UI or provisioning | Many data sources | No-data defaults; folder permissions |
| PagerDuty | On-call and incidents | UI, Terraform | Mature schedules and escalation | Cost per seat |
| Opsgenie | On-call and incidents | UI | Was widely used | End of sale 4 June 2025, shutdown 5 April 2027 |
| incident.io | On-call and incident workflow | UI, API | Slack-native response | Newer ecosystem |
| Datadog monitors | Rules and notification | UI, Terraform | Anomaly and forecast monitors | Pricing by host and metric |
| Cloud-native (CloudWatch, Cloud Monitoring) | Rules and routing | Provider console | Integrated with the platform | Different semantics per cloud |
Fix / how to use it: keep rules in git whichever tool you use, with a naming and labelling convention and a CI check.
Alerting for queues and batch jobs Must-know
In plain words: for a queue, the user feels how long work waits, not how many items are in the queue; for a batch job, the user feels "was it done by 06:00".
Common misunderstanding: "Alert on queue depth above N." Depth depends on throughput; 10,000 items are fine at 50,000 per minute and a disaster at 10. The symptoms are age (oldest message age, consumer lag in time) and throughput (is anything being consumed).
Definition: queue lag alerts: Kafka consumer lag converted to time, RabbitMQ message age or queue growth with no consumers, Redis Streams pending entries and idle time, SQS ApproximateAgeOfOldestMessage. For job SLAs: expected completion time and a heartbeat on success. See Messaging Observability & Tracing for the per-broker metrics and Dead Letter Queues for poisoned messages. In Laravel, Horizon waits configures the seconds that count as a "long wait" per connection and queue (30, 60, 120 in the docs example) and 0 disables it; Pulse's Slow Jobs card uses a threshold per job class (1,000 ms default).
Queue "orders", consumers healthy until 14:00
1 14:00 workers crash; producers continue at 200 msg/s
2 14:01 depth 12000, oldest age 60 s -> queue-latency SLO (age over 30 s for 2 m) pending
3 14:03 oldest age 180 s -> page (canary silent for 180 s as well)
4 14:08 workers restarted; depth drains at 800 msg/s
5 14:19 oldest age under 30 s for 5 m -> resolvesReal scenarios: (1) Email jobs wait 40 minutes because one slow job blocks a worker; (2) a poison message loops forever (see DLQ); (3) the nightly reconciliation misses its 06:00 SLA; (4) a Kafka consumer group rebalances repeatedly and lag grows only in time, not depth.
| Signal | Symptom? | Page when |
|---|---|---|
| Oldest message age or time lag | Yes | Above the user-visible delay budget for several minutes |
| Consumer throughput = 0 with backlog | Yes | A few minutes |
| Queue depth | Cause | Rarely; only with growth and no consumers |
| DLQ arrivals | Cause or symptom | Rate above baseline, or any for critical queues |
| Job finished by deadline | Yes | Deadline missed (heartbeat or expected-by check) |
| Worker process count | Cause | No; use throughput |
Fix / how to use it: where the broker has no age metric, send a canary job and measure dispatch-to-run time (Laravel shows QueueCanary and queue:canary-check).
The postmortem feedback loop Important
In plain words: every incident asks the alerting system two questions: did it tell us fast enough, and did it also scream about things that did not matter.
Common misunderstanding: "After an incident, add an alert for exactly what failed." That is how rule counts grow forever. The postmortem should also remove or merge rules.
Definition: SRE Book chapter 15: a postmortem is "a written record of an incident, its impact, the actions taken to mitigate or resolve it, the root cause(s), and the follow-up actions". The alerting section of a postmortem answers: how was it detected (alert, customer, engineer); detection delay; which alerts fired and which were noise; what alerts to add, tune, demote or delete; whether the runbook helped. PagerDuty's guide adds the on-call habit "If information is difficult / impossible to find, write it down".
Postmortem alert review for incident 2026-11-03 "checkout 502 for 38 minutes"
1 Detected by customer support ticket at +21 min (alerts: none)
2 Why no page errors came from one region: global ratio 0.7%, below 1.44% fast-burn line
3 Add per-region burn-rate rule for checkout (new, page)
4 Remove CheckoutHighLatencyP95 (fired 3 times last month, 0 actionable)
5 Follow-up tests added to slo-rules-test.yml; owner: payments; due: next sprintReal scenarios: (1) A customer-reported outage yields a recall action item; (2) an alert paged at night and ended in "no action" and is deleted; (3) a runbook step was wrong and is fixed in the same PR as the rule; (4) a new rule is added together with its promtool test.
| Postmortem finding | Alerting action |
|---|---|
| Customers noticed first | Add or lower a symptom rule (recall) |
| Alert fired late | Shorten window, raise burn factor, add a probe |
| Alert fired but nobody acted | Fix routing, owner or runbook |
| Alerts fired for the same cause | Add inhibition or group |
| Alert was noise | Demote or delete |
| Heartbeat or tool failed | Add a Watchdog or backup channel |
Fix / how to use it: a postmortem is not done until the alert changes are merged; link the PR in the document.
Anti-patterns Important
In plain words: the ways alerting usually goes wrong.
Common misunderstanding: "More dashboards and more notifications will fix it." Usually they hide it.
Definition: the named anti-patterns:
Anti-pattern What it looks like Why it fails
1 Alert on every error page when error count above 0 normal systems have errors; retries hide them
2 CPU alert page at 85% CPU for 5 minutes a resource, not a symptom; benign by design in autoscaled systems
3 Email alert nobody reads channel "foo-alerts" with 4000 unread no accountability; ignored in a week (Ewaschuk)
4 Flapping alert opens and closes every minute no for, no hysteresis, no keep_firing_for
5 Alert storm 100 pages when a dependency fails no grouping, no inhibition, cause rules
6 Orphan alert no owner, no runbook responder starts from zero
7 Threshold copy-paste same numbers on every service not tied to each SLO
8 Silence as a fix permanent silence hides the problem; add an expiry and a ticket
9 Page for a robotic fix "restart the worker" every week automate it
10 Unmonitored monitor no Watchdog silence looks like healthReal scenarios: (1) "ErrorCountAboveZero" pages 40 times a night; (2) a CPU alert fires on every nightly batch; (3) a team's alert Slack channel has 6,000 unread messages; (4) the Alertmanager pod was evicted for a week.
| Anti-pattern | Replace with |
|---|---|
| Error count page | SLO burn-rate page |
| CPU page | Latency or saturation SLO plus a ticket for capacity |
| Email alert | Ticket with an owner or a digest with a reviewer |
| Flapping | for, keep_firing_for, hysteresis |
| Storm | Grouping, inhibition, symptom-only pages |
| Orphan | Required team and runbook_url labels, lint in CI |
Fix / how to use it: run the weekly review against this table.
Mechanics
The alert lifecycle in Prometheus
A rule group is evaluated every evaluation_interval. For each element returned by expr, Prometheus tracks a state. Without for, an alert "will become active on the first evaluation". With for: 10m, the element is pending until it has been returned on every evaluation for 10 minutes, then firing. For pending and firing alerts Prometheus stores the synthetic series ALERTS{alertname="<name>", alertstate="<pending or firing>", ...labels}. Firing alerts are pushed to Alertmanager on every evaluation and refreshed; if the alert stops being returned, Prometheus sends a resolved notice, unless keep_firing_for delays it.
| Concept | Where | Detail |
|---|---|---|
alert | rule | Alert name; label alertname |
expr | rule | PromQL; each returned element is one alert instance |
for | rule | Pending to firing delay |
keep_firing_for | rule | Firing to resolved delay |
labels | rule | Added to the alert; overwrite conflicting labels; used for routing |
annotations | rule | Templated text; not part of identity |
ALERTS series | Prometheus | Queryable history of pending and firing |
$value, $labels | templates | The sample value and labels in annotation templates |
Alertmanager timer arithmetic
Group {alertname="HighErrors", cluster="eu-1"}, group_wait 30 s, group_interval 5 m, repeat_interval 4 h
1 t=0:00 first alert for the group arrives
2 t=0:30 group_wait elapsed -> notification 1 (all alerts that arrived by now)
3 t=2:10 a new member arrives; it waits for the next group_interval tick
4 t=5:30 group_interval tick -> notification 2 contains the new member
5 t=9:00 all members resolve -> a resolved notification at the next tick (if send_resolved)
6 t=4:30h still firing, nothing changed -> repeat_interval reminder (rounded up to a multiple of group_interval)Rules of thumb from the configuration reference: if an alert resolves before group_wait ends, no notification is sent; a small group_interval with a slow receiver can cancel the notification (it sets the context timeout); repeat_interval should be a multiple of group_interval; inhibition depends on the inhibiting alert arriving before the target is notified, so a longer group_wait makes inhibition reliable.
Burn-rate arithmetic
| Quantity | Formula | Example (99.9%, 30 days) |
|---|---|---|
| Error budget | 1 - objective | 0.001 (43.2 minutes of full outage) |
| Burn rate | observed error ratio / budget | 1.44% / 0.1% = 14.4 |
| Threshold for a policy | burn x budget | 14.4 x 0.001 = 1.44% |
| Budget consumed in the long window | burn x long / period | 14.4 x 1h / 720h = 2% |
| Time to exhaustion | period / burn | 720 h / 14.4 = 50 h |
Fires after (clean start, ratio e) | long x threshold / e | 1h x 1.44% / 5% = 17.3 min |
| Alert resets after recovery | about the short window | 5 minutes (the 1h window alone: 60) |
PagerDuty Events API v2
| Field | Meaning |
|---|---|
routing_key | 32-character integration key of a service or ruleset |
event_action | trigger, acknowledge or resolve |
dedup_key | Up to 255 characters; correlates events to one open alert; omitted on a trigger means a new UUID and a new alert each time |
payload.summary, payload.source | Required for a trigger |
payload.severity | critical, error, warning or info |
| HTTP 202 | Accepted |
| HTTP 400 | Bad request: fix the JSON, do not retry |
| HTTP 429 | Too many calls: retry with backoff of a few minutes |
Acknowledge and resolve events sent with a different routing_key from the original do not apply to the open alert.
Error and message names you will see
| Where | Message or state | Meaning |
|---|---|---|
| Prometheus | pending, firing | Alert states |
| Prometheus | ALERTS series | Active alerts as metrics |
promtool test rules | FAILED with expected and got alerts | Mismatch in labels, annotations or timing |
| Alertmanager | level=error ... Notify for alerts failed | Receiver failed; check its API and retry |
| Alertmanager | silenced, inhibited states on the API | Alert is firing but muted |
| blackbox_exporter | probe_success 0 | Probe failed; probe_duration_seconds shows phases |
| PagerDuty Events API | 202, 400, 429 | See above |
| Grafana | State No Data or Error (rule-level handling) | Query returned nothing or failed |
(The Alertmanager log line and Grafana state names are from product knowledge and were not found in the fetched pages; treat them as indicative.)
Prometheus, Alertmanager and probe files
The recording rules, the three burn-rate alerts, the Watchdog, an absent() rule, a blackbox probe alert with keep_firing_for and a predictive disk ticket:
# Recording rules: one error-ratio series per window, per job.
groups:
- name: checkout-slo-ratios
interval: 30s
rules:
- record: job:slo_errors_per_request:ratio_rate5m
expr: sum by (job) (rate(http_requests_total{code=~"5.."}[5m])) / sum by (job) (rate(http_requests_total[5m]))
- record: job:slo_errors_per_request:ratio_rate30m
expr: sum by (job) (rate(http_requests_total{code=~"5.."}[30m])) / sum by (job) (rate(http_requests_total[30m]))
- record: job:slo_errors_per_request:ratio_rate1h
expr: sum by (job) (rate(http_requests_total{code=~"5.."}[1h])) / sum by (job) (rate(http_requests_total[1h]))
- record: job:slo_errors_per_request:ratio_rate6h
expr: sum by (job) (rate(http_requests_total{code=~"5.."}[6h])) / sum by (job) (rate(http_requests_total[6h]))
- record: job:slo_errors_per_request:ratio_rate3d
expr: sum by (job) (rate(http_requests_total{code=~"5.."}[3d])) / sum by (job) (rate(http_requests_total[3d]))
- name: checkout-slo-alerts
rules:
# 99.9% SLO: budget 0.001. Burn 14.4 over 1h and 5m = 2% of the budget.
- alert: CheckoutErrorBudgetFastBurn
expr: |
job:slo_errors_per_request:ratio_rate1h{job="checkout"} > (14.4 * 0.001)
and
job:slo_errors_per_request:ratio_rate5m{job="checkout"} > (14.4 * 0.001)
labels:
severity: page
team: payments
annotations:
summary: "Checkout is burning its 30-day error budget 14.4x too fast"
description: "{{ $value | humanizePercentage }} of requests failed over the last hour and the short window is still burning. At this rate 2% of the budget goes in 1h."
runbook_url: https://runbooks.example.com/checkout/error-budget-burn
dashboard: https://grafana.example.com/d/checkout-slo
# Burn 6 over 6h and 30m = 5% of the budget.
- alert: CheckoutErrorBudgetSlowBurn
expr: |
job:slo_errors_per_request:ratio_rate6h{job="checkout"} > (6 * 0.001)
and
job:slo_errors_per_request:ratio_rate30m{job="checkout"} > (6 * 0.001)
labels:
severity: page
team: payments
annotations:
summary: "Checkout is burning its 30-day error budget 6x too fast"
runbook_url: https://runbooks.example.com/checkout/error-budget-burn
# Burn 1 over 3d and 6h = 10% of the budget: a ticket, not a page.
- alert: CheckoutErrorBudgetTrickle
expr: |
job:slo_errors_per_request:ratio_rate3d{job="checkout"} > (1 * 0.001)
and
job:slo_errors_per_request:ratio_rate6h{job="checkout"} > (1 * 0.001)
labels:
severity: ticket
team: payments
annotations:
summary: "Checkout will exhaust its error budget in about 30 days at the current rate"
runbook_url: https://runbooks.example.com/checkout/error-budget-burn
- name: meta-alerts
rules:
# Dead man's switch: always firing. Alertmanager forwards it to an
# external receiver that pages when it STOPS arriving.
- alert: Watchdog
expr: vector(1)
labels:
severity: none
annotations:
summary: "Alerting pipeline heartbeat"
# Absence of data: the series that the SLO alerts depend on is gone.
- alert: CheckoutMetricsAbsent
expr: absent(sum(rate(http_requests_total{job="checkout"}[5m])))
for: 5m
labels:
severity: page
team: payments
annotations:
summary: "No http_requests_total from job=checkout for 5m (target down or scrape broken)"
runbook_url: https://runbooks.example.com/meta/metrics-absent
# Symptom from the outside: blackbox_exporter probe.
- alert: CheckoutProbeFailing
expr: probe_success{job="blackbox-checkout"} == 0
for: 3m
keep_firing_for: 5m
labels:
severity: page
team: payments
annotations:
summary: "Synthetic checkout probe has failed for 3m"
runbook_url: https://runbooks.example.com/checkout/probe
# Cause-based but predictive and ticket-level: disk fills in 4 days.
- alert: DiskWillFillIn4Days
expr: predict_linear(node_filesystem_avail_bytes{fstype!="tmpfs"}[6h], 4 * 24 * 3600) < 0
for: 1h
labels:
severity: ticket
team: platform
annotations:
summary: "{{ $labels.instance }}:{{ $labels.mountpoint }} will be full within 4 days"The unit tests for those rules (run with promtool test rules slo-rules-test.yml):
# promtool test rules slo-rules-test.yml
rule_files:
- slo-rules.yml
evaluation_interval: 1m
tests:
# Full outage: both the 1h and the 5m ratio are 100% -> the fast-burn page fires.
- interval: 1m
input_series:
- series: 'job:slo_errors_per_request:ratio_rate1h{job="checkout"}'
values: '0x10 1x20'
- series: 'job:slo_errors_per_request:ratio_rate5m{job="checkout"}'
values: '0x10 1x20'
alert_rule_test:
- eval_time: 5m
alertname: CheckoutErrorBudgetFastBurn
exp_alerts: []
- eval_time: 15m
alertname: CheckoutErrorBudgetFastBurn
exp_alerts:
- exp_labels:
severity: page
team: payments
job: checkout
exp_annotations:
summary: "Checkout is burning its 30-day error budget 14.4x too fast"
description: "100% of requests failed over the last hour and the short window is still burning. At this rate 2% of the budget goes in 1h."
runbook_url: https://runbooks.example.com/checkout/error-budget-burn
dashboard: https://grafana.example.com/d/checkout-slo
# Recovered: the 5m ratio drops, the 1h ratio is still high -> must NOT fire.
- interval: 1m
input_series:
- series: 'job:slo_errors_per_request:ratio_rate1h{job="checkout"}'
values: '0.05x30'
- series: 'job:slo_errors_per_request:ratio_rate5m{job="checkout"}'
values: '0.05x10 0x20'
alert_rule_test:
- eval_time: 20m
alertname: CheckoutErrorBudgetFastBurn
exp_alerts: []
# The metric disappears: absent() fires only after the 5m for duration.
- interval: 1m
input_series:
- series: 'http_requests_total{job="other", code="200"}'
values: '0+10x30'
alert_rule_test:
- eval_time: 3m
alertname: CheckoutMetricsAbsent
exp_alerts: []
- eval_time: 7m
alertname: CheckoutMetricsAbsent
exp_alerts:
- exp_labels:
severity: page
team: payments
exp_annotations:
summary: "No http_requests_total from job=checkout for 5m (target down or scrape broken)"
runbook_url: https://runbooks.example.com/meta/metrics-absent
# Watchdog is always firing.
- interval: 1m
alert_rule_test:
- eval_time: 2m
alertname: Watchdog
exp_alerts:
- exp_labels:
severity: none
exp_annotations:
summary: "Alerting pipeline heartbeat"The Alertmanager configuration with team routing, a heartbeat receiver, business-hours tickets, inhibition and a time interval:
global:
resolve_timeout: 5m
route:
receiver: team-slack-default
group_by: [alertname, cluster, service]
group_wait: 30s # wait for siblings before the first notification
group_interval: 5m # batch updates to an existing group
repeat_interval: 4h # re-notify if still firing
routes:
# The dead man's switch goes to an external service that pages on silence.
- receiver: deadmansswitch
matchers: [alertname = "Watchdog"]
group_wait: 0s
group_interval: 1m
repeat_interval: 1m
# Pages route by team, then fall through to the generic pager.
- receiver: payments-pager
matchers: [severity = "page", team = "payments"]
group_by: [alertname, service]
- receiver: platform-pager
matchers: [severity = "page", team = "platform"]
# Tickets never wake anyone.
- receiver: ticket-queue
matchers: [severity = "ticket"]
group_by: [alertname, team]
repeat_interval: 24h
active_time_intervals: [business-hours]
inhibit_rules:
# If the whole cluster is unreachable, mute everything else from that cluster.
- name: cluster-down-mutes-the-rest
source_matchers: [alertname = "ClusterUnreachable"]
target_matchers: [severity =~ "page|ticket"]
equal: [cluster]
# A page for a service mutes its own ticket-level alerts.
- name: page-mutes-ticket
source_matchers: [severity = "page"]
target_matchers: [severity = "ticket"]
equal: [alertname, service]
time_intervals:
- name: business-hours
time_intervals:
- weekdays: ['monday:friday']
times:
- start_time: '09:00'
end_time: '17:00'
location: 'UTC'
receivers:
- name: team-slack-default
slack_configs:
- channel: '#alerts-lowprio'
api_url_file: /etc/alertmanager/slack-url
send_resolved: true
title: '{{ .CommonLabels.alertname }}'
text: '{{ .CommonAnnotations.summary }} runbook: {{ .CommonAnnotations.runbook_url }}'
- name: payments-pager
pagerduty_configs:
- routing_key_file: /etc/alertmanager/pd-payments-key
severity: critical
description: '{{ .CommonAnnotations.summary }}'
details:
runbook: '{{ .CommonAnnotations.runbook_url }}'
- name: platform-pager
pagerduty_configs:
- routing_key_file: /etc/alertmanager/pd-platform-key
- name: ticket-queue
webhook_configs:
- url: https://tickets.example.com/hooks/alertmanager
- name: deadmansswitch
webhook_configs:
- url: https://hc-ping.example.com/00000000-0000-0000-0000-000000000000Go
Before
The first alert most teams write: a threshold on the raw error ratio of each minute. Run it on 12 minutes containing a one-minute blip, a 0.05% wobble and one real outage and it pages three times (minutes 1, 5, 7), two of them for nothing.
// Before: the alert most teams write first. It pages on a raw error-ratio
// threshold evaluated on every sample, so it flaps and wakes a human for blips.
package main
import "fmt"
func main() {
// Error ratio per minute for 12 minutes: a one-minute blip, then a real outage.
ratios := []float64{0, 0.002, 0, 0, 0.0005, 0.003, 0, 0.30, 0.31, 0.29, 0.30, 0.28}
const threshold = 0.001 // "alert if more than 0.1% of requests fail"
pages := 0
prev := false
for minute, r := range ratios {
firing := r > threshold
if firing && !prev {
pages++
fmt.Printf("minute %2d: PAGE (ratio %.4f)\n", minute, r)
}
if !firing && prev {
fmt.Printf("minute %2d: resolved\n", minute)
}
prev = firing
}
fmt.Printf("pages for 12 minutes with one real outage: %d\n", pages)
}After
Three small packages with no dependency outside the standard library. burnrate holds the SLO, the policies (default values are the Workbook table 5-8 parameters), a minute-bucket Counter, the multi-window evaluator with the low-traffic MinEvents guard and a function that picks the most severe firing policy. Missing data is reported as "no data in window", never as zero errors.
// Package burnrate implements multi-window, multi-burn-rate SLO alerting as
// described in the Google SRE Workbook, chapter "Alerting on SLOs".
package burnrate
import (
"fmt"
"sync"
"time"
)
// SLO is a success objective over a rolling period, e.g. 0.999 over 30 days.
type SLO struct {
Objective float64
Period time.Duration
}
// Budget is the allowed error ratio: 1 - Objective.
func (s SLO) Budget() float64 { return 1 - s.Objective }
// Policy is one alerting condition: fire when the error ratio exceeds
// Factor * budget over BOTH the long and the short window.
type Policy struct {
Name string
Severity string // "page" or "ticket"
Long time.Duration
Short time.Duration
Factor float64 // burn rate
}
// BudgetConsumed is the fraction of the whole error budget that a constant
// burn at Factor spends during the long window: Factor * Long / Period.
func (p Policy) BudgetConsumed(s SLO) float64 {
return p.Factor * float64(p.Long) / float64(s.Period)
}
// DefaultPolicies are the workbook's starting parameters for a 99.9% SLO
// (table 5-8): 2% of budget in 1h, 5% in 6h (pages), 10% in 3d (ticket).
func DefaultPolicies() []Policy {
return []Policy{
{Name: "fast-burn", Severity: "page", Long: time.Hour, Short: 5 * time.Minute, Factor: 14.4},
{Name: "slow-burn", Severity: "page", Long: 6 * time.Hour, Short: 30 * time.Minute, Factor: 6},
{Name: "trickle", Severity: "ticket", Long: 72 * time.Hour, Short: 6 * time.Hour, Factor: 1},
}
}
// Counter keeps good/bad event counts in one-minute buckets so that the error
// ratio over any window up to its retention can be read back.
type Counter struct {
mu sync.Mutex
retention time.Duration
buckets map[int64]*bucket
}
type bucket struct{ total, bad float64 }
// NewCounter keeps buckets for retention (it must cover the longest window).
func NewCounter(retention time.Duration) *Counter {
return &Counter{retention: retention, buckets: map[int64]*bucket{}}
}
func minute(t time.Time) int64 { return t.Unix() / 60 }
// Add records total and bad events observed at time t.
func (c *Counter) Add(t time.Time, total, bad float64) {
c.mu.Lock()
defer c.mu.Unlock()
k := minute(t)
b := c.buckets[k]
if b == nil {
b = &bucket{}
c.buckets[k] = b
}
b.total += total
b.bad += bad
oldest := minute(t.Add(-c.retention))
for key := range c.buckets {
if key < oldest {
delete(c.buckets, key)
}
}
}
// Window returns total and bad events in the half-open window (now-w, now].
func (c *Counter) Window(now time.Time, w time.Duration) (total, bad float64) {
c.mu.Lock()
defer c.mu.Unlock()
hi := minute(now)
lo := hi - int64(w/time.Minute)
for k, b := range c.buckets {
if k > lo && k <= hi {
total += b.total
bad += b.bad
}
}
return total, bad
}
// Ratio is bad/total over the window; ok is false when no events were seen
// (absent data must not be read as "zero errors").
func (c *Counter) Ratio(now time.Time, w time.Duration) (ratio float64, ok bool) {
total, bad := c.Window(now, w)
if total == 0 {
return 0, false
}
return bad / total, true
}
// Result is the evaluation of one policy at one instant.
type Result struct {
Policy Policy
LongRatio float64
ShortRatio float64
Threshold float64
Firing bool
Reason string
}
// Evaluator joins an SLO, its policies and a Counter.
type Evaluator struct {
SLO SLO
Policies []Policy
Counter *Counter
// MinEvents suppresses a policy when the long window holds fewer events.
// It is the low-traffic guard from the workbook (one failed request out of
// ten must not look like a 1,000x burn rate).
MinEvents float64
}
// Evaluate returns one Result per policy.
func (e *Evaluator) Evaluate(now time.Time) []Result {
out := make([]Result, 0, len(e.Policies))
for _, p := range e.Policies {
thr := p.Factor * e.SLO.Budget()
lr, lok := e.Counter.Ratio(now, p.Long)
sr, sok := e.Counter.Ratio(now, p.Short)
total, _ := e.Counter.Window(now, p.Long)
r := Result{Policy: p, LongRatio: lr, ShortRatio: sr, Threshold: thr}
switch {
case !lok || !sok:
r.Reason = "no data in window"
case total < e.MinEvents:
r.Reason = fmt.Sprintf("only %.0f events in long window (min %.0f)", total, e.MinEvents)
case lr > thr && sr > thr:
r.Firing = true
r.Reason = "both windows above threshold"
case lr > thr:
r.Reason = "long window above, short window recovered"
default:
r.Reason = "below threshold"
}
out = append(out, r)
}
return out
}
// Highest returns the most severe firing result, preferring "page" over "ticket".
func Highest(results []Result) (Result, bool) {
var best Result
found := false
for _, r := range results {
if !r.Firing {
continue
}
if !found || (r.Policy.Severity == "page" && best.Policy.Severity != "page") {
best, found = r, true
}
}
return best, found
}package burnrate
import (
"math"
"testing"
"time"
)
var t0 = time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)
func TestWorkbookTableBudgetConsumed(t *testing.T) {
slo := SLO{Objective: 0.999, Period: 30 * 24 * time.Hour}
want := []float64{0.02, 0.05, 0.10} // workbook table 5-8
for i, p := range DefaultPolicies() {
got := p.BudgetConsumed(slo)
if math.Abs(got-want[i]) > 1e-9 {
t.Errorf("%s: consumed %.4f, want %.4f", p.Name, got, want[i])
}
}
}
func feed(c *Counter, from time.Time, minutes int, perMin, errRatio float64) time.Time {
t := from
for i := 0; i < minutes; i++ {
c.Add(t, perMin, perMin*errRatio)
t = t.Add(time.Minute)
}
return t
}
func newEval() *Evaluator {
return &Evaluator{
SLO: SLO{Objective: 0.999, Period: 30 * 24 * time.Hour},
Policies: DefaultPolicies(),
Counter: NewCounter(73 * time.Hour),
}
}
func TestFullOutagePagesWithinMinutes(t *testing.T) {
e := newEval()
now := feed(e.Counter, t0, 120, 6000, 0)
for i := 1; i <= 10; i++ {
e.Counter.Add(now, 6000, 6000)
res, ok := Highest(e.Evaluate(now))
if ok && res.Policy.Severity == "page" {
if i > 2 {
t.Fatalf("paged after %d minutes, want <= 2", i)
}
return
}
now = now.Add(time.Minute)
}
t.Fatal("full outage never paged")
}
func TestBlipDoesNotPage(t *testing.T) {
e := newEval()
now := feed(e.Counter, t0, 120, 6000, 0)
e.Counter.Add(now, 6000, 300) // one minute at 5% errors
now = feed(e.Counter, now.Add(time.Minute), 30, 6000, 0)
for _, r := range e.Evaluate(now) {
if r.Firing {
t.Errorf("%s fired on a one-minute blip", r.Policy.Name)
}
}
}
func TestShortWindowResetsPageQuickly(t *testing.T) {
e := newEval()
now := feed(e.Counter, t0, 120, 6000, 0)
now = feed(e.Counter, now, 10, 6000, 1.0) // 10 minutes of total outage
if _, ok := Highest(e.Evaluate(now)); !ok {
t.Fatal("expected a page during the outage")
}
now = feed(e.Counter, now, 6, 6000, 0) // recovered; short window (5m) is clean
res := e.Evaluate(now)
if res[0].Firing {
t.Fatal("fast-burn should stop firing about 5 minutes after recovery")
}
if res[0].LongRatio <= res[0].Threshold {
t.Fatal("the long window should still be above threshold (that is the point of the short window)")
}
}
func TestSlowBurnTicketNotPage(t *testing.T) {
e := newEval()
now := feed(e.Counter, t0, 72*60, 6000, 0.002) // 0.2% = burn rate 2
got, ok := Highest(e.Evaluate(now))
if !ok || got.Policy.Severity != "ticket" {
t.Fatalf("want ticket, got %+v ok=%v", got.Policy, ok)
}
}
func TestLowTrafficGuard(t *testing.T) {
e := newEval()
e.MinEvents = 1000
e.Counter.Add(t0, 10, 1) // 10% errors on ten requests
for _, r := range e.Evaluate(t0) {
if r.Firing {
t.Errorf("%s fired on 10 events", r.Policy.Name)
}
}
}
func TestNoDataIsNotZeroErrors(t *testing.T) {
e := newEval()
for _, r := range e.Evaluate(t0) {
if r.Firing || r.Reason != "no data in window" {
t.Errorf("unexpected %+v", r)
}
}
}rule is the state machine for a single threshold alert: inactive, pending, firing, with For, KeepFiringFor, separate FireAbove and ResolveBelow for hysteresis and a NoData policy (keep state, treat as firing, treat as OK).
// Package rule evaluates a threshold alert with a for duration, hysteresis,
// keep-firing and an explicit policy for missing data.
package rule
import "time"
// State mirrors Prometheus alert states.
type State int
const (
Inactive State = iota
Pending
Firing
)
func (s State) String() string { return [...]string{"inactive", "pending", "firing"}[s] }
// NoData says what a missing sample means.
type NoData int
const (
KeepState NoData = iota // ignore the gap (default)
TreatAsFiring
TreatAsOK
)
// Rule describes one alert.
type Rule struct {
Name string
// FireAbove starts the alert; ResolveBelow ends it. Set ResolveBelow
// lower than FireAbove for hysteresis; equal means no hysteresis.
FireAbove float64
ResolveBelow float64
// For is how long the condition must hold before pending becomes firing.
For time.Duration
// KeepFiringFor keeps a firing alert up after the condition clears.
KeepFiringFor time.Duration
NoData NoData
}
// Transition reports a state change produced by Eval.
type Transition struct {
From, To State
}
// Evaluator holds the state of one rule for one series.
type Evaluator struct {
rule Rule
state State
pendingFrom time.Time
lastActive time.Time
}
// New returns an evaluator in the Inactive state.
func New(r Rule) *Evaluator {
if r.ResolveBelow == 0 && r.FireAbove != 0 {
r.ResolveBelow = r.FireAbove
}
return &Evaluator{rule: r}
}
// State returns the current state.
func (e *Evaluator) State() State { return e.state }
// Eval feeds one sample. ok=false means no sample arrived.
func (e *Evaluator) Eval(now time.Time, v float64, ok bool) (State, *Transition) {
from := e.state
active := e.active(v, ok)
switch e.state {
case Inactive:
if active {
e.pendingFrom = now
e.lastActive = now
e.state = Pending
if e.rule.For <= 0 {
e.state = Firing
}
}
case Pending:
switch {
case !active:
e.state = Inactive
case now.Sub(e.pendingFrom) >= e.rule.For:
e.lastActive = now
e.state = Firing
default:
e.lastActive = now
}
case Firing:
if active {
e.lastActive = now
} else if now.Sub(e.lastActive) >= e.rule.KeepFiringFor {
e.state = Inactive
}
}
if e.state == from {
return e.state, nil
}
return e.state, &Transition{From: from, To: e.state}
}
func (e *Evaluator) active(v float64, ok bool) bool {
if !ok {
switch e.rule.NoData {
case TreatAsFiring:
return true
case TreatAsOK:
return false
default:
return e.state != Inactive
}
}
if e.state == Firing {
return v > e.rule.ResolveBelow // hysteresis: stay active until below the lower line
}
return v > e.rule.FireAbove
}package rule
import (
"testing"
"time"
)
var t0 = time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)
// run feeds one sample per 15 s and returns the state history.
func run(e *Evaluator, samples []float64) []State {
var out []State
for i, v := range samples {
s, _ := e.Eval(t0.Add(time.Duration(i)*15*time.Second), v, true)
out = append(out, s)
}
return out
}
func TestForDurationSuppressesSpike(t *testing.T) {
e := New(Rule{Name: "x", FireAbove: 1, For: time.Minute})
hist := run(e, []float64{0, 5, 0, 0})
for _, s := range hist {
if s == Firing {
t.Fatal("a single spike must not fire with for: 1m")
}
}
}
func TestForDurationFiresWhenSustained(t *testing.T) {
e := New(Rule{Name: "x", FireAbove: 1, For: time.Minute})
hist := run(e, []float64{5, 5, 5, 5, 5, 5})
// t=0 pending, t=60s firing (index 4)
if hist[0] != Pending || hist[3] != Pending || hist[4] != Firing {
t.Fatalf("history %v", hist)
}
}
func TestHysteresisStopsFlapping(t *testing.T) {
noHys := New(Rule{Name: "a", FireAbove: 80})
hys := New(Rule{Name: "b", FireAbove: 80, ResolveBelow: 70})
samples := []float64{85, 79, 85, 79, 85, 79}
count := func(e *Evaluator) int {
n := 0
for i, v := range samples {
if _, tr := e.Eval(t0.Add(time.Duration(i)*time.Minute), v, true); tr != nil {
n++
}
}
return n
}
if a, b := count(noHys), count(hys); a != 6 || b != 1 {
t.Fatalf("transitions without=%d with=%d, want 6 and 1", a, b)
}
}
func TestKeepFiringFor(t *testing.T) {
e := New(Rule{Name: "x", FireAbove: 1, KeepFiringFor: time.Minute})
e.Eval(t0, 5, true)
if s, _ := e.Eval(t0.Add(30*time.Second), 0, true); s != Firing {
t.Fatal("should keep firing for 1m")
}
if s, _ := e.Eval(t0.Add(61*time.Second), 0, true); s != Inactive {
t.Fatal("should resolve after keep_firing_for")
}
}
func TestNoDataPolicies(t *testing.T) {
keep := New(Rule{FireAbove: 1, NoData: KeepState})
keep.Eval(t0, 5, true)
if s, _ := keep.Eval(t0.Add(time.Minute), 0, false); s != Firing {
t.Fatal("KeepState must not resolve on a gap")
}
fire := New(Rule{FireAbove: 1, NoData: TreatAsFiring})
if s, _ := fire.Eval(t0, 0, false); s != Firing {
t.Fatal("TreatAsFiring must fire on a gap")
}
ok := New(Rule{FireAbove: 1, NoData: TreatAsOK})
ok.Eval(t0, 5, true)
if s, _ := ok.Eval(t0.Add(time.Minute), 0, false); s != Inactive {
t.Fatal("TreatAsOK must resolve on a gap")
}
}heartbeat is the dead man's switch: jobs register an interval and grace, check in through Beat or the HTTP handler, and Check lists everything overdue. Watchdog models the always-firing alert whose arrival proves the pipeline works.
// Package heartbeat is a dead man's switch: a job must check in on time, and
// silence is what raises the alert. It also shows the Watchdog pattern.
package heartbeat
import (
"net/http"
"sort"
"strings"
"sync"
"time"
)
// Expectation says how often a named job must check in.
type Expectation struct {
Name string
Interval time.Duration
Grace time.Duration
}
// Missing is one overdue job.
type Missing struct {
Name string
LastSeen time.Time // zero if it never checked in
Overdue time.Duration
}
// Registry tracks expected heartbeats.
type Registry struct {
mu sync.Mutex
expect map[string]Expectation
seen map[string]time.Time
since map[string]time.Time
}
// New returns an empty registry.
func New() *Registry {
return &Registry{expect: map[string]Expectation{}, seen: map[string]time.Time{}, since: map[string]time.Time{}}
}
// Expect registers a job. A job that never checks in becomes overdue
// Interval+Grace after registration.
func (r *Registry) Expect(e Expectation, now time.Time) {
r.mu.Lock()
defer r.mu.Unlock()
r.expect[e.Name] = e
r.since[e.Name] = now
}
// Beat records a check-in. Unknown names are ignored and reported false.
func (r *Registry) Beat(name string, now time.Time) bool {
r.mu.Lock()
defer r.mu.Unlock()
if _, ok := r.expect[name]; !ok {
return false
}
r.seen[name] = now
return true
}
// Check returns every job that is overdue at now, oldest first.
func (r *Registry) Check(now time.Time) []Missing {
r.mu.Lock()
defer r.mu.Unlock()
var out []Missing
for name, e := range r.expect {
ref := r.since[name]
last := r.seen[name]
if last.After(ref) {
ref = last
}
deadline := ref.Add(e.Interval + e.Grace)
if now.After(deadline) {
out = append(out, Missing{Name: name, LastSeen: last, Overdue: now.Sub(deadline)})
}
}
sort.Slice(out, func(i, j int) bool { return out[i].Overdue > out[j].Overdue })
return out
}
// Handler serves GET or POST /ping/{name}, the shape used by healthchecks.io
// style services. The clock is injected for tests.
func (r *Registry) Handler(clock func() time.Time) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
name := strings.TrimPrefix(req.URL.Path, "/ping/")
if name == "" || !r.Beat(name, clock()) {
http.Error(w, "unknown check", http.StatusNotFound)
return
}
w.WriteHeader(http.StatusOK)
})
}
// Watchdog models Prometheus' always-firing Watchdog alert: the pipeline
// (rule evaluation, Alertmanager, notifier) is healthy only while the
// receiving side keeps seeing it. Silence from the pipeline is the alarm.
type Watchdog struct {
reg *Registry
name string
}
// NewWatchdog registers a pipeline heartbeat that must arrive every interval.
func NewWatchdog(reg *Registry, name string, interval, grace time.Duration, now time.Time) *Watchdog {
reg.Expect(Expectation{Name: name, Interval: interval, Grace: grace}, now)
return &Watchdog{reg: reg, name: name}
}
// Receive is called each time the always-firing alert is delivered.
func (w *Watchdog) Receive(now time.Time) { w.reg.Beat(w.name, now) }package heartbeat
import (
"net/http"
"net/http/httptest"
"testing"
"time"
)
var t0 = time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)
func TestOnTimeBeatIsQuiet(t *testing.T) {
r := New()
r.Expect(Expectation{Name: "backup", Interval: time.Hour, Grace: 5 * time.Minute}, t0)
r.Beat("backup", t0.Add(50*time.Minute))
if m := r.Check(t0.Add(100 * time.Minute)); len(m) != 0 {
t.Fatalf("unexpected %+v", m)
}
}
func TestSilenceRaisesAlert(t *testing.T) {
r := New()
r.Expect(Expectation{Name: "backup", Interval: time.Hour, Grace: 5 * time.Minute}, t0)
r.Beat("backup", t0.Add(55*time.Minute))
m := r.Check(t0.Add(2*time.Hour + 10*time.Minute))
if len(m) != 1 || m[0].Name != "backup" || m[0].Overdue != 10*time.Minute {
t.Fatalf("got %+v", m)
}
}
func TestNeverSeenBecomesOverdue(t *testing.T) {
r := New()
r.Expect(Expectation{Name: "nightly", Interval: 24 * time.Hour, Grace: time.Hour}, t0)
if m := r.Check(t0.Add(24 * time.Hour)); len(m) != 0 {
t.Fatal("within interval+grace")
}
m := r.Check(t0.Add(26 * time.Hour))
if len(m) != 1 || !m[0].LastSeen.IsZero() {
t.Fatalf("got %+v", m)
}
}
func TestHandler(t *testing.T) {
r := New()
r.Expect(Expectation{Name: "backup", Interval: time.Hour}, t0)
now := t0.Add(30 * time.Minute)
h := r.Handler(func() time.Time { return now })
for path, want := range map[string]int{"/ping/backup": 200, "/ping/nope": 404, "/ping/": 404} {
rec := httptest.NewRecorder()
h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, path, nil))
if rec.Code != want {
t.Errorf("%s: %d want %d", path, rec.Code, want)
}
}
}
func TestWatchdogSilence(t *testing.T) {
r := New()
w := NewWatchdog(r, "alertmanager-watchdog", time.Minute, 2*time.Minute, t0)
w.Receive(t0.Add(time.Minute))
w.Receive(t0.Add(2 * time.Minute))
if m := r.Check(t0.Add(4 * time.Minute)); len(m) != 0 {
t.Fatal("pipeline healthy")
}
if m := r.Check(t0.Add(6 * time.Minute)); len(m) != 1 {
t.Fatal("pipeline silent for 4m beyond the interval must alert")
}
}The replay command runs the same six incidents against the naive 10-minute rule and the three policies, in virtual time, with 72 hours of clean warm-up traffic:
// Command replay runs the same synthetic incidents through a naive
// "error ratio over 10 minutes > SLO" alert and through the workbook's
// multi-window, multi-burn-rate policies, in virtual time.
package main
import (
"fmt"
"time"
"academy/alerting-that-works/burnrate"
)
const (
perMinute = 6000.0 // 100 requests per second
horizon = 80 * time.Hour
)
type scenario struct {
name string
ratio func(minute int) float64 // error ratio during that minute of the incident
}
func main() {
slo := burnrate.SLO{Objective: 0.999, Period: 30 * 24 * time.Hour}
periodEvents := perMinute * slo.Period.Minutes()
budgetEvents := periodEvents * slo.Budget()
t0 := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)
scenarios := []scenario{
{"100% outage (burn 1000)", func(int) float64 { return 1 }},
{"5% errors (burn 50)", func(int) float64 { return 0.05 }},
{"1% errors (burn 10)", func(int) float64 { return 0.01 }},
{"0.3% errors (burn 3)", func(int) float64 { return 0.003 }},
{"0.12% errors (burn 1.2)", func(int) float64 { return 0.0012 }},
{"one minute at 5% then clean", func(m int) float64 {
if m == 0 {
return 0.05
}
return 0
}},
}
fmt.Printf("%-30s | %-26s | %-34s\n", "scenario", "naive (10m > 0.1%)", "multi-window multi-burn-rate")
for _, sc := range scenarios {
naive := run(sc, t0, slo, budgetEvents, true)
mw := run(sc, t0, slo, budgetEvents, false)
fmt.Printf("%-30s | %-26s | %-34s\n", sc.name, naive, mw)
}
}
// run returns "detect time, budget consumed" for the first alert, or "never".
func run(sc scenario, t0 time.Time, slo burnrate.SLO, budgetEvents float64, naive bool) string {
c := burnrate.NewCounter(73 * time.Hour)
ev := &burnrate.Evaluator{SLO: slo, Policies: burnrate.DefaultPolicies(), Counter: c}
var bad float64
// Warm-up: 72 hours of clean traffic before the incident starts at minute 0.
for m := -72 * 60; m < 0; m++ {
c.Add(t0.Add(time.Duration(m)*time.Minute), perMinute, 0)
}
for m := 0; time.Duration(m)*time.Minute < horizon; m++ {
now := t0.Add(time.Duration(m) * time.Minute)
r := sc.ratio(m)
c.Add(now, perMinute, perMinute*r)
bad += perMinute * r
if naive {
if ratio, ok := c.Ratio(now, 10*time.Minute); ok && ratio > slo.Budget() {
return describe(m+1, bad, budgetEvents, "page")
}
continue
}
if res, ok := burnrate.Highest(ev.Evaluate(now)); ok {
return describe(m+1, bad, budgetEvents, res.Policy.Severity)
}
}
return "never"
}
func describe(minutes int, bad, budget float64, sev string) string {
d := time.Duration(minutes) * time.Minute
return fmt.Sprintf("%s after %s, %.2f%% budget", sev, d, 100*bad/budget)
}The Go angle
Go has no alerting library in the standard library, but the pieces are small: a clock passed as a value (now time.Time) instead of read inside functions makes every test deterministic without a fake clock type; sync.Mutex guards the counters; net/http plus httptest gives a heartbeat endpoint and its test in a dozen lines. In production you rarely re-implement Prometheus' evaluator; this code is for in-process SLO checks (a worker that watches its own error ratio), for sidecars that evaluate custom signals, and for understanding the logic well enough to review rule files. The Prometheus Go client (prometheus/client_golang) exposes the counters that the Prometheus rules then evaluate; keep alert logic out of request handlers.
Laravel
Before
A cron-style Artisan command that emails when one-minute load average is high: cause-based, no deduplication, no resolve, no owner, no runbook, no heartbeat.
<?php
declare(strict_types=1);
namespace App\Before;
use Illuminate\Support\Facades\Mail;
// Before: the alert most Laravel teams write first. It pages on a cause
// (CPU), on every sample, by e-mail, with no runbook, no dedup, no resolve.
final class CpuAlert
{
public function __invoke(): void
{
$load = sys_getloadavg()[0];
if ($load > 2.0) {
Mail::raw("CPU load is {$load}", function ($m) {
$m->to('alerts@example.com')->subject('ALERT: high CPU');
});
}
}
}After
The SLO evaluation lives in a plain class (BurnRateEvaluator) that takes a reader for error counts, so the source can be Prometheus, a database or cache counters. EvaluateSlo reads Prometheus through the HTTP API with Laravel's HTTP client, opens and closes alerts with a cache key (one notification per transition, not per run), and sends a notification. Laravel ships a Slack channel (laravel/slack-notification-channel, SlackMessage with Block Kit) but no PagerDuty channel, so PagerDutyChannel follows the documented custom-channel contract (send($notifiable, Notification $notification)) and posts to the Events API v2 with a dedup_key, retrying only connection errors and HTTP 429.
<?php
declare(strict_types=1);
// config/alerting.php: policies mirror the SRE Workbook table 5-8 (99.9% SLO).
return [
'services' => [
'checkout' => [
'objective' => 0.999,
'min_events' => 200,
// Prometheus job that exposes http_requests_total
'job' => 'checkout',
],
],
'prometheus_url' => env('PROMETHEUS_URL', 'http://prometheus.internal:9090'),
'policies' => [
['name' => 'fast-burn', 'severity' => 'page', 'long' => '1h', 'short' => '5m', 'factor' => 14.4],
['name' => 'slow-burn', 'severity' => 'page', 'long' => '6h', 'short' => '30m', 'factor' => 6.0],
['name' => 'trickle', 'severity' => 'ticket', 'long' => '3d', 'short' => '6h', 'factor' => 1.0],
],
'queue_canary' => [
'queue' => 'default',
'max_latency_seconds' => 60,
'max_silence_seconds' => 180,
],
];<?php
declare(strict_types=1);
namespace App\Alerting;
/**
* Multi-window, multi-burn-rate evaluation over error ratios read from any
* source (a Prometheus HTTP query, a database aggregate, cache counters).
* Same policies as the Go package: SRE Workbook, table 5-8, 99.9% SLO.
*/
final class BurnRateEvaluator
{
/** @param list<array{name:string,severity:string,long:string,short:string,factor:float}> $policies */
public function __construct(
private readonly float $objective,
private readonly array $policies,
private readonly float $minEvents = 0.0,
) {
}
/**
* @param callable(string $window): ?array{total:float,bad:float} $read
* @return list<array{policy:array<string,mixed>,firing:bool,long:?float,short:?float,threshold:float,reason:string}>
*/
public function evaluate(callable $read): array
{
$budget = 1 - $this->objective;
$out = [];
foreach ($this->policies as $p) {
$threshold = $p['factor'] * $budget;
$long = $read($p['long']);
$short = $read($p['short']);
if ($long === null || $short === null || $long['total'] <= 0 || $short['total'] <= 0) {
$out[] = $this->row($p, false, null, null, $threshold, 'no data in window');
continue;
}
$lr = $long['bad'] / $long['total'];
$sr = $short['bad'] / $short['total'];
if ($long['total'] < $this->minEvents) {
$out[] = $this->row($p, false, $lr, $sr, $threshold, 'below minimum events');
continue;
}
$firing = $lr > $threshold && $sr > $threshold;
$out[] = $this->row($p, $firing, $lr, $sr, $threshold, $firing ? 'both windows above threshold' : 'below threshold');
}
return $out;
}
/** @param array<string,mixed> $p */
private function row(array $p, bool $firing, ?float $lr, ?float $sr, float $thr, string $reason): array
{
return ['policy' => $p, 'firing' => $firing, 'long' => $lr, 'short' => $sr, 'threshold' => $thr, 'reason' => $reason];
}
}<?php
declare(strict_types=1);
namespace App\Alerting;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\RequestException;
use Illuminate\Notifications\Notification;
use Illuminate\Support\Facades\Http;
/**
* Custom notification channel for the PagerDuty Events API v2. Laravel ships
* no first-party PagerDuty channel, so this follows the "Custom Channels"
* contract: a class with a send($notifiable, Notification $n) method.
*/
final class PagerDutyChannel
{
public function send(object $notifiable, Notification $notification): void
{
/** @var array{event_action:string,dedup_key:string,summary:string,severity:string,source:string,custom_details:array<string,mixed>,links:list<array{href:string,text:string}>} $event */
$event = $notification->toPagerDuty($notifiable);
$body = [
'routing_key' => config('services.pagerduty.routing_key'),
'event_action' => $event['event_action'],
'dedup_key' => $event['dedup_key'],
];
if ($event['event_action'] === 'trigger') {
$body['payload'] = [
'summary' => $event['summary'],
'source' => $event['source'],
'severity' => $event['severity'], // critical | error | warning | info
'custom_details' => $event['custom_details'],
];
$body['links'] = $event['links'];
}
Http::timeout(5)
// 202 = accepted, 400 = bad JSON (never retry), 429 = rate limited (retry with backoff)
->retry(3, 500, when: fn ($e) => $e instanceof ConnectionException
|| ($e instanceof RequestException && $e->response->status() === 429), throw: false)
->acceptJson()
->post('https://events.pagerduty.com/v2/enqueue', $body)
->throw();
}
}<?php
declare(strict_types=1);
namespace App\Notifications;
use App\Alerting\PagerDutyChannel;
use Illuminate\Notifications\Notification;
use Illuminate\Notifications\Slack\BlockKit\Blocks\ContextBlock;
use Illuminate\Notifications\Slack\BlockKit\Blocks\SectionBlock;
use Illuminate\Notifications\Slack\SlackMessage;
final class SloBurnAlert extends Notification
{
/** @param array{name:string,severity:string,long:string,short:string,factor:float} $policy */
public function __construct(
private readonly string $service,
private readonly array $policy,
private readonly float $longRatio,
private readonly float $shortRatio,
private readonly string $action = 'trigger',
) {
}
/** Pages go to PagerDuty and Slack; tickets go to Slack only. */
public function via(object $notifiable): array
{
return $this->policy['severity'] === 'page'
? [PagerDutyChannel::class, 'slack']
: ['slack'];
}
public function dedupKey(): string
{
// One open alert per service and policy; resolve uses the same key.
return "slo:{$this->service}:{$this->policy['name']}";
}
public function toPagerDuty(object $notifiable): array
{
return [
'event_action' => $this->action,
'dedup_key' => $this->dedupKey(),
'summary' => sprintf(
'%s burning error budget at %.1fx (%s window %.2f%% errors)',
$this->service,
$this->policy['factor'],
$this->policy['long'],
$this->longRatio * 100,
),
'severity' => 'critical',
'source' => $this->service,
'custom_details' => [
'long_window_ratio' => $this->longRatio,
'short_window_ratio' => $this->shortRatio,
'policy' => $this->policy,
],
'links' => [['href' => "https://runbooks.example.com/slo/{$this->service}", 'text' => 'Runbook']],
];
}
public function toSlack(object $notifiable): SlackMessage
{
return (new SlackMessage)
->text("{$this->service}: SLO burn ({$this->policy['severity']})")
->headerBlock("{$this->service}: {$this->policy['name']}")
->contextBlock(function (ContextBlock $block) {
$block->text("severity: {$this->policy['severity']}");
})
->sectionBlock(function (SectionBlock $block) {
$block->field(sprintf("*Long (%s):*\n%.2f%% errors", $this->policy['long'], $this->longRatio * 100))->markdown();
$block->field(sprintf("*Short (%s):*\n%.2f%% errors", $this->policy['short'], $this->shortRatio * 100))->markdown();
});
}
}<?php
declare(strict_types=1);
namespace App\Console\Commands;
use App\Alerting\BurnRateEvaluator;
use App\Notifications\SloBurnAlert;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Notification;
final class EvaluateSlo extends Command
{
protected $signature = 'slo:evaluate';
protected $description = 'Evaluate multi-window multi-burn-rate SLO alerts and notify';
public function handle(): int
{
foreach (config('alerting.services') as $service => $cfg) {
$evaluator = new BurnRateEvaluator($cfg['objective'], config('alerting.policies'), $cfg['min_events']);
$results = $evaluator->evaluate(fn (string $w) => $this->read($cfg['job'], $w));
foreach ($results as $r) {
$key = "slo-alert:{$service}:{$r['policy']['name']}";
$open = Cache::has($key);
if ($r['firing'] && ! $open) {
Cache::put($key, true, now()->addDay());
$this->notify(new SloBurnAlert($service, $r['policy'], $r['long'], $r['short'], 'trigger'));
} elseif (! $r['firing'] && $open && $r['reason'] !== 'no data in window') {
Cache::forget($key);
$this->notify(new SloBurnAlert($service, $r['policy'], (float) $r['long'], (float) $r['short'], 'resolve'));
}
}
}
return self::SUCCESS;
}
private function notify(SloBurnAlert $alert): void
{
Notification::route('slack', config('services.slack.notifications.channel'))->notifyNow($alert);
}
/** @return array{total:float,bad:float}|null */
private function read(string $job, string $window): ?array
{
$q = fn (string $expr) => (float) data_get(
Http::timeout(5)->get(config('alerting.prometheus_url').'/api/v1/query', ['query' => $expr])
->throw()->json(),
'data.result.0.value.1',
0,
);
$total = $q(sprintf('sum(increase(http_requests_total{job="%s"}[%s]))', $job, $window));
$bad = $q(sprintf('sum(increase(http_requests_total{job="%s",code=~"5.."}[%s]))', $job, $window));
return $total > 0 ? ['total' => $total, 'bad' => $bad] : null;
}
}The queue canary dispatches a tiny job each minute, records the dispatch-to-run latency and the time of the last finish, and raises a queue-slow or queue-silent alert; this works on any queue driver, even where the broker exposes no oldest-message age.
<?php
declare(strict_types=1);
namespace App\Jobs;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Facades\Cache;
/**
* A synthetic job: it measures the time between dispatch and execution, which
* is the user-visible "queue wait" even when the broker has no
* oldest-message-age metric.
*/
final class QueueCanary implements ShouldQueue
{
use Dispatchable;
use InteractsWithQueue;
use Queueable;
public function __construct(public readonly float $dispatchedAt)
{
}
public function handle(): void
{
Cache::put('queue-canary:last', [
'latency' => microtime(true) - $this->dispatchedAt,
'finished_at' => microtime(true),
], now()->addHour());
}
}<?php
declare(strict_types=1);
namespace App\Console\Commands;
use App\Jobs\QueueCanary;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Queue;
final class CheckQueueHealth extends Command
{
protected $signature = 'queue:canary-check';
protected $description = 'Dispatch a canary job and alert on queue wait time or silence';
public function handle(): int
{
$cfg = config('alerting.queue_canary');
$last = Cache::get('queue-canary:last');
// Always send the next canary first, so that a dead worker pool shows
// up as silence rather than as a stale reading.
QueueCanary::dispatch(microtime(true))->onQueue($cfg['queue']);
$silence = $last === null ? null : microtime(true) - $last['finished_at'];
$depth = Queue::size($cfg['queue']);
$this->line(sprintf('depth=%d latency=%s silence=%s', $depth, $last['latency'] ?? 'n/a', $silence ?? 'n/a'));
if ($silence !== null && $silence > $cfg['max_silence_seconds']) {
$this->page('queue-silent', "No canary finished for {$cfg['max_silence_seconds']}s (workers down or stuck)");
} elseif ($last !== null && $last['latency'] > $cfg['max_latency_seconds']) {
$this->page('queue-slow', sprintf('Queue wait %.0fs exceeds %ds (depth %d)', $last['latency'], $cfg['max_latency_seconds'], $depth));
} else {
$this->resolve('queue-silent');
$this->resolve('queue-slow');
}
return self::SUCCESS;
}
private function page(string $key, string $summary): void
{
$this->event('trigger', $key, $summary);
}
private function resolve(string $key): void
{
$this->event('resolve', $key, '');
}
private function event(string $action, string $key, string $summary): void
{
$body = ['routing_key' => config('services.pagerduty.routing_key'), 'event_action' => $action, 'dedup_key' => "queue:{$key}"];
if ($action === 'trigger') {
$body['payload'] = ['summary' => $summary, 'source' => gethostname() ?: 'app', 'severity' => 'error'];
}
Http::timeout(5)->post('https://events.pagerduty.com/v2/enqueue', $body);
}
}The scheduler wires both commands to an external dead man's switch with pingBefore, pingOnSuccess, pingOnFailure and thenPing; withoutOverlapping and onOneServer keep the check from running twice. Horizon's waits and Pulse's per-job slow thresholds are excerpted next.
<?php
declare(strict_types=1);
use Illuminate\Support\Facades\Schedule;
// Each scheduled task pings an external dead man's switch (a healthchecks.io
// style check, or any service with /start and /fail URLs). If the scheduler
// itself stops, nobody inside the app can report it: the silence is the alert.
$hb = config('services.heartbeat.slo_url');
Schedule::command('slo:evaluate')
->everyMinute()
->withoutOverlapping(5)
->onOneServer()
->pingBefore($hb.'/start')
->pingOnSuccess($hb)
->pingOnFailure($hb.'/fail');
Schedule::command('queue:canary-check')
->everyMinute()
->withoutOverlapping(5)
->onOneServer()
->thenPing(config('services.heartbeat.queue_url'));
// Horizon: snapshot for the wait-time metrics dashboard.
Schedule::command('horizon:snapshot')->everyFiveMinutes();<?php
declare(strict_types=1);
// Excerpts, not whole files.
// config/horizon.php: seconds a queue may wait before Horizon raises a
// "long wait" notification (0 disables it for that queue).
$horizon = [
'waits' => [
'redis:critical' => 30,
'redis:default' => 60,
'redis:batch' => 120,
],
];
// config/pulse.php: per-job slow thresholds (milliseconds) for the Slow Jobs card.
$pulse = [
'recorders' => [
\Laravel\Pulse\Recorders\SlowJobs::class => [
'threshold' => [
'#^App\\Jobs\\GenerateYearlyReports$#' => 5000,
'default' => env('PULSE_SLOW_JOBS_THRESHOLD', 1000),
],
],
],
];
// app/Providers/HorizonServiceProvider.php, boot():
// Horizon::routeSlackNotificationsTo(env('SLACK_WEBHOOK'), '#oncall-queues');<?php
declare(strict_types=1);
namespace Tests\Feature;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Notification;
use Tests\TestCase;
final class EvaluateSloTest extends TestCase
{
public function test_full_outage_triggers_one_page_and_dedups(): void
{
Cache::flush();
Notification::fake();
// 100% errors in every window: total == bad.
Http::fake(['prometheus.internal:9090/*' => Http::response([
'data' => ['result' => [['value' => [0, '100000']]]],
])]);
$this->artisan('slo:evaluate')->assertSuccessful();
$this->artisan('slo:evaluate')->assertSuccessful(); // second run must not re-notify
Notification::assertSentOnDemandTimes(\App\Notifications\SloBurnAlert::class, 3);
}
public function test_pagerduty_payload_has_dedup_key_and_severity(): void
{
Http::fake(['events.pagerduty.com/*' => Http::response(['status' => 'success'], 202)]);
config(['services.pagerduty.routing_key' => 'R0UT1NGK3Y']);
$alert = new \App\Notifications\SloBurnAlert(
'checkout',
['name' => 'fast-burn', 'severity' => 'page', 'long' => '1h', 'short' => '5m', 'factor' => 14.4],
0.05,
0.06,
);
(new \App\Alerting\PagerDutyChannel)->send(new \Illuminate\Notifications\AnonymousNotifiable, $alert);
Http::assertSent(fn ($req) => $req['dedup_key'] === 'slo:checkout:fast-burn'
&& $req['event_action'] === 'trigger'
&& $req['payload']['severity'] === 'critical');
}
}The Laravel angle
Laravel's role is the application end of the pipeline. The scheduler (Schedule::command(...)->everyMinute()) is also a failure point, so give it its own heartbeat: pingBefore($url) and thenPing($url) ping before and after a task, and pingOnSuccess/pingOnFailure ping only on a zero or non-zero exit code (the ...If variants take a condition). Notifications deliver to mail, slack, SMS (Vonage) and custom channels, and Notification::route('slack', ...) sends on-demand without a notifiable model. Horizon notifies about long queue waits through Horizon::routeSlackNotificationsTo (and mail and SMS) with per-queue thresholds in waits; Pulse records slow jobs, queries and requests as dashboards, not as pages, so treat its cards as diagnosis and feed paging from Prometheus or the canary. Laravel Octane, queues and Reverb do not change the rules: alert on user-visible latency and errors at the load balancer, and use application-side checks for what the edge cannot see (job age, scheduler liveness).
Limits of the sample: Queue::size() exists on the queue contract but is not described on the pages fetched for this chapter; the slo:evaluate Prometheus queries use increase(...) over long windows, which is simpler than recording rules but heavy for 3-day ranges; the tests were not executed here.
Solving the classic problems
Alert storm during an outage
| Solution | How | Advantage | Cost |
|---|---|---|---|
| Group | group_by: [alertname, cluster] | One message for 120 instances | Hides per-instance count unless templated |
| Inhibit | ClusterUnreachable mutes same-cluster alerts | The cause page wins | Needs a good cause alert; arrival order matters |
| Symptom-only pages | Remove cause paging rules | Fewer rules | Causes only on dashboards |
| Dependency-aware routing | Route by team with parent/child labels | Owner gets the page | Label hygiene |
| Pager storm control | PagerDuty/Opsgenie grouping, rate limits | Protects humans | Tool-specific |
Flapping alert
| Solution | How | Advantage | Cost |
|---|---|---|---|
for | for: 3m | Absorbs spikes | Slower detection |
keep_firing_for | keep_firing_for: 5m | No false resolves | Slower reset |
| Hysteresis | Fire at 80, resolve at 70 | Stable near the line | Two thresholds to maintain |
| Longer window | 10m average instead of 1m | Smoother | Slower |
| Remove it | Is it actionable? | Zero noise | Coverage trade-off |
A slow leak that nobody sees
A 0.3% error rate for two days consumes 14% of the 30-day budget and never trips a page. The 3-day ticket policy (burn 1, with the 6-hour short window) opens a ticket after about a day (the lab measured 24h01m at 0.3%). Without it the team learns at the end of the month, when the budget is already gone.
Silent failure of monitoring itself
Watchdog to an external receiver, up and absent alerts, heartbeat on the scheduler, and a monthly test that kills Alertmanager in staging. The rule: every component that can be silent needs a partner that notices the silence.
The alert nobody understands at 3 a.m.
Add the summary (what is broken for whom), description with the value, runbook_url, a dashboard link and recent changes. Ewaschuk's trick: print the firing cause rules inside the symptom page so the responder sees "Also firing: UserDatabaseShardDown". Keep the runbook short: what it means and what is currently interesting.
Too many pages for a small team
Reduce scope (fewer services), raise SLO tolerance (a lower availability promise), move some alerts to business hours, add synthetic traffic or aggregate services for low-volume signals, and ask for more people before burnout, not after. The SRE guidance on a minimum rotation size (six to eight) is why very small teams need a business-hours model.
A cron job that never ran
Nothing logs an error because nothing ran. A dead man's switch (healthchecks.io style) with period + grace, pingBefore and pingOnFailure for start and failure, and a Prometheus absent() on the job's last-success timestamp, for example time() - job_last_success_timestamp_seconds > 86400 + 3600.
A paged alert that always ends with "restart it"
Automate it (Kubernetes liveness and readiness probes, a supervisor, an auto-remediation runbook) and keep a ticket-level alert if the automation fired more than N times a week. The page is the failure of the automation, not the original fault.
Choosing
Page, ticket or dashboard
| Signal | Decision | Reason |
|---|---|---|
| Checkout error budget burning 14.4x | Page | Active user harm, hours to exhaustion |
| Error budget at 10% in 3 days | Ticket | Real but not urgent |
| Disk full in 3 hours | Page (cause justified) | Imminent, no symptom before the cliff |
| Disk full in 4 days | Ticket | Fix at business hours |
| CPU at 90% | Dashboard | A resource, not a symptom |
| Pod restarted once | Log | Self-healing |
| Certificate expires in 20 days | Ticket | Deadline, not urgent |
| Certificate expires in 2 days | Page | Imminent outage |
| Queue oldest message age over the delay budget | Page | User-visible delay |
| Queue depth high, age low | Dashboard | Throughput is fine |
| Nightly job missed its deadline | Ticket during the day, page if business-critical | Depends on the consumer |
Which threshold style
| Situation | Choose | Why |
|---|---|---|
| Request success or latency with an SLO | Multi-window multi-burn-rate | Scale-free, ties to users |
| Resource cliff (disk, quota, cert) | predict_linear or days-to-expiry | Time to exhaustion |
| Business metric with seasonality | Week-over-week ratio, ticket | No SLO, strong cycle |
| Unknown shapes, exploration | Anomaly detection to tickets | Not for pages |
| Low traffic | Probes plus long window plus MinEvents | Avoid single-event pages |
Which tool for which team
| Team size and stack | Rule engine | Router | On-call |
|---|---|---|---|
| Small, Kubernetes, open source | Prometheus rules in git | Alertmanager | PagerDuty free tier or incident.io |
| Mixed data sources | Grafana-managed rules | Grafana notification policies | PagerDuty |
| Heavy SaaS use | Datadog monitors | Datadog | PagerDuty or incident.io |
| Atlassian shop | Prometheus or Datadog | Alertmanager | Jira Service Management (Opsgenie is being shut down) |
| Laravel app on one server | Scheduler checks plus healthchecks.io | The app | Phone call via PagerDuty Events API |
In architecture: from a single process to a distributed system
Monolith: one process, one database
One app on one server, one database. Keep it simple: an external uptime probe (blackbox_exporter or a SaaS probe) hitting login and checkout every minute, the scheduler heartbeat, a disk-full-in-24-hours ticket and a page on probe failure for 3 minutes with keep_firing_for. Example: a Laravel shop pages on "checkout probe fails for 3 minutes" and opens a ticket for "queue canary latency over 60 s". No SLO tooling is needed until there is traffic worth defending.
Modular monolith: boundaries without the network
One deployable, several modules and databases. Label metrics with module and route by team. Give each module its own SLI (orders, billing, search) so one noisy module cannot hide in a global error ratio. Per-module alerts page the owning team; a shared database alert pages the platform team and inhibits module alerts that depend on it (equal: [database]).
Microservices: every arrow is a decision
Flow: user -> gateway -> checkout -> payments -> bank
1 Symptom page owner gateway/edge SLO (what users see): page, team: platform-edge
2 Service SLOs checkout, payments: page their owners on burn rate
3 Dependency alerts payments sees bank errors: ticket or inhibited by the edge page
4 During a bank outage edge burns, checkout burns, payments burns -> three pages for one cause
5 Inhibition payments-bank-down (cause, owned by payments) inhibits checkout and edge pages with equal: [region]Each service owns its SLOs and runbooks; a central platform team owns the routing tree, the conventions (team, severity, runbook_url) and the Watchdog. Use client-side error ratios (what the caller sees) for dependencies, as Ewaschuk recommends. Cross-link: Cascading Failures explains why one failure produces many alerts; a Circuit Breaker state change is itself a good ticket-level signal.
Distributed data: replicas, caches, regions
Replica lag, cache hit ratio and cross-region error rates need per-region alerts: a global error ratio of 0.7% can hide a region at 20% (see the postmortem timeline above). Alert on staleness as a symptom ("data older than 5 minutes" for read replicas that serve users), not on every replication metric. Run Alertmanager in a high-availability pair across failure domains (the Alertmanager gossip replicates silences and notification state, and Prometheus sends alerts to all of them), keep the dead man's switch receiver outside the region it watches, and have a second notification path (SMS and a different vendor) for "the pager provider is down".
Scaling path: 1x, 10x, 100x
| Scale | What alerting looks like | What to add |
|---|---|---|
| 1x: one team, one service | A probe, three symptom pages, one heartbeat | severity and runbook_url conventions |
| 10x: several teams, dozens of services | SLOs per service, MWMBR rules from templates, Alertmanager routing by team | Rule linting in CI, promtool tests, weekly review, inhibition |
| 100x: platform with hundreds of services | Generated SLO rules (the Workbook warns that custom parameters for 100 microservices "accumulate toil"), shared Watchdog, region-aware routing, error budget policy | Alert catalog, ownership metadata, pager analytics, a game-day programme |
Lab: replay incidents through two alerting designs
Everything in this lab runs on one machine without containers. Steps 1 to 3 were run; steps 4 to 6 are labelled "expected, not run" because they need promtool, amtool or a Laravel application, which this environment does not have.
Experiment 1: the naive rule on a noisy minute series (run)
$ cd docs/snippets/system-design/alerting-that-works/go && go run ./before
minute 1: PAGE (ratio 0.0020)
minute 2: resolved
minute 5: PAGE (ratio 0.0030)
minute 6: resolved
minute 7: PAGE (ratio 0.3000)
pages for 12 minutes with one real outage: 3Two of three pages are for nothing.
Experiment 2: six incidents, naive vs multi-window multi-burn-rate (run)
$ go run ./cmd/replay
scenario | naive (10m > 0.1%) | multi-window multi-burn-rate
100% outage (burn 1000) | page after 1m0s, 2.31% budget | page after 1m0s, 2.31% budget
5% errors (burn 50) | page after 1m0s, 0.12% budget | page after 18m0s, 2.08% budget
1% errors (burn 10) | page after 2m0s, 0.05% budget | page after 3h37m0s, 5.02% budget
0.3% errors (burn 3) | page after 4m0s, 0.03% budget | ticket after 24h1m0s, 10.01% budget
0.12% errors (burn 1.2) | page after 9m0s, 0.02% budget | ticket after 60h0m0s, 10.00% budget
one minute at 5% then clean | page after 1m0s, 0.12% budget | neverReading it: the naive rule pages in minutes for everything, including a one-minute blip and a 0.12% brownout that needs 60 hours to matter. The policies page fast for real damage (100% outage: 1 minute; 5% errors: 18 minutes with 2% of the budget spent), page slowly for a 1% leak (after 3h37m, about 5% of the budget) and turn the slow leaks into tickets that arrive when about 10% of the budget is gone. The one-minute blip never pages. (Budget percentages are computed against 100 requests per second over 30 days; times have one-minute granularity.)
Experiment 3: tests with the race detector (run)
$ go vet ./... && go test -race ./...
ok academy/alerting-that-works/burnrate
ok academy/alerting-that-works/heartbeat
ok academy/alerting-that-works/ruleExperiment 4: promtool unit tests (expected, not run)
$ promtool check rules slo-rules.yml
Checking slo-rules.yml
SUCCESS: 12 rules found
$ promtool test rules slo-rules-test.yml
Unit Testing: slo-rules-test.yml
SUCCESSBreak the test on purpose (change 14.4 to 15 in the rule) and expect FAILED with the expected and the got alerts printed.
Experiment 5: routing test with amtool (expected, not run)
$ amtool config routes test --config.file=alertmanager.yml severity=page team=payments
payments-pager
$ amtool config routes test --config.file=alertmanager.yml alertname=Watchdog severity=none
deadmansswitchExperiment 6: kill the scheduler (expected, not run)
Create a healthchecks.io-style check with period 1 minute and grace 2 minutes, put its URL in services.heartbeat.slo_url, run php artisan schedule:work, then stop it. Expected: the check goes late at about 1 minute and "down" after about 3, and a notification is sent although no application code ran. Restart: the next ping recovers it.
Common misconceptions
| Belief | Reality |
|---|---|
| "If we alert on everything we are safe" | A noisy pager is ignored; precision protects recall in practice |
| "High CPU should always page" | CPU is a cause; autoscaled systems run hot by design; alert on latency and errors |
"for: 1h equals a one-hour window" | for ignores severity: a 100% outage waits as long as a 0.2% one |
| "A silence fixes a noisy alert" | It hides notifications; the rule keeps firing and the cause remains |
| "Anomaly detection removes thresholds" | It moves tuning into the model and adds false positives at deploys and holidays |
| "Burn rate 1 means trouble" | It is the plan: the budget lasts exactly the window |
| "No data means no errors" | Missing data is an unknown; use absent() and no-data handling |
| "Email is fine for alerts" | Email with no accountability is ignored; use tickets or digests with an owner |
| "More runbook detail is always better" | Short notes about what it means and what is interesting beat flow charts |
| "On-call is something good engineers just handle" | It has a sustainable limit (about 25% of time, under 2 pages per shift) |
| "The monitoring is up because we get no alerts" | Silence is ambiguous; a dead man's switch makes it measurable |
| "Add an alert after every incident" | Also remove, merge and demote; otherwise the rule count only grows |
Cheat sheet
| Topic | What to remember |
|---|---|
| Page test | Urgent, actionable, needs intelligence, novel, user-visible now or imminent |
| Symptom vs cause | Page on symptoms; show causes in the page text and on dashboards |
| Types | Page wakes, ticket queues, report summarises, log informs |
| Burn rate | Error ratio divided by budget; time to exhaustion is period divided by burn |
| MWMBR table (99.9%) | 14.4 over 1h and 5m (2%), 6 over 6h and 30m (5%) pages; 1 over 3d and 6h (10%) ticket |
| Short window | About 1/12 of the long window; resets the alert fast |
for | Delays firing; wrong tool for ratio SLOs |
keep_firing_for | Delays resolving; prevents flapping and false resolves |
| Hysteresis | Fire at one threshold, resolve at a lower one |
| Alertmanager | Dedup, group, inhibit, silence, route; defaults 30 s, 5 m, 4 h |
| Annotations | summary, description, runbook_url; labels route, annotations explain |
| Dead man's switch | Watchdog (vector(1)) or job ping; page when it stops |
| Absent data | absent(), up == 0, per-rule no-data handling |
| Testing | promtool test rules, amtool config routes test, probes, game days |
| On-call | Primary and backup, 5-minute escalation, written handoff, under 25% load |
| Pager fatigue | Under 2 pages per shift, over 90% actionable, review weekly |
| Queues | Alert on oldest message age and zero throughput, not depth |
| Postmortem | Add, tune, demote, delete alerts; merge the PR before closing |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — Name the four properties Google SRE says a page must have and why "novel" matters. Important
Answer
Answer: Urgent (react with a sense of urgency, only a few times a day), actionable, requiring intelligence (a robotic response should be automated) and novel (a problem not seen before). If it repeats it is a bug to fix, not a page to answer again.
2 — A service has a 99.9% SLO over 30 days. What error ratio triggers the fast-burn page and why? Important
Answer
Answer: 14.4 x 0.1% = 1.44% over both 1 hour and 5 minutes. At that burn 2% of the 30-day budget is spent in one hour (14.4 x 1h / 720h).
3 — Why does a for: 1h clause give worse results than a one-hour window with burn-rate threshold? Important
Answer
Answer: The duration does not scale with severity: a 100% outage and a 0.2% issue both alert after one hour. A 100% outage would have consumed 140% of the budget in that hour.
4 — What does the short window add and why is it about 1/12 of the long window? Good to know
Answer
Answer: It proves the budget is still being burned, so the alert resets about 5 minutes after recovery instead of 60 and false positives from past events drop. 1/12 is the Workbook's guideline.
5 — Describe three ways Alertmanager reduces an alert storm. Must-know
Answer
Answer: Grouping (one notification per group_by key), inhibition (a source alert such as ClusterUnreachable mutes targets with equal labels) and routing/silences (right receiver; temporary mute). Deduplication is automatic.
6 — What is a dead man's switch and how is Prometheus' Watchdog an example? Important
Answer
Answer: An alert on the absence of a signal. Watchdog (vector(1)) always fires; an external receiver pages when it stops arriving, which proves the rule engine, Alertmanager or the network is broken.
7 — Why is rate(errors) / rate(total) > x unsafe if a target stops reporting, and what do you add? Must-know
Answer
Answer: No data returns an empty result, which evaluates to "not firing". Add absent() or up == 0 rules and handle no-data states in the alert tool; never treat a gap as zero errors.
8 — Give two metrics for pager fatigue and a target for each. Good to know
Answer
Answer: Pages per on-call shift (SRE Book example target: under 2) and percentage of pages that were actionable (Ewaschuk: under 50% means broken). Night pages and time to acknowledge are also useful.
9 — How would you alert on a queue properly? Must-know
Answer
Answer: On the age of the oldest message (or time lag) and on zero throughput with a backlog, not on depth. Add a canary job where the broker has no age metric, and a DLQ rate for poisoned messages.
10 — What belongs in the alerting part of a postmortem? Important
Answer
Answer: How the incident was detected and how late, which alerts fired and which were noise, and the changes: alerts to add, tune, demote or delete, with owner and PR link.
11 — A team gets paged for a CPU alert every Monday morning. What is the sequence of actions? Must-know
Answer
Answer: Apply the page test (not user-visible, not novel), remove the page, keep CPU on the dashboard, and alert on latency or error-budget burn instead; if capacity is the real concern, open a ticket-level rule.
12 — Why must the dead man's switch receiver live outside the system it watches? Important
Answer
Answer: If it runs in the same cluster or region, the failure that silences the alerts also silences the watcher, so nobody is told.
Glossary
| Term | Meaning |
|---|---|
| Alerting | Turning a monitored condition into a notification to a human or a system |
| Page | An alert that urgently interrupts a specific person |
| Ticket | A queued task created by a lower-urgency alert |
| Actionable | There is something a human can do now |
| Symptom-based alert | Alert on what users experience (errors, latency, freshness) |
| Cause-based alert | Alert on an internal condition such as a full disk or dead replica |
| SLO-based alerting | Alerting on the rate at which an SLO's error budget is spent |
| Burn rate | Observed error ratio divided by the error budget ratio |
| Error budget | 1 - SLO: the allowed failures in the SLO window |
| Multi-window multi-burn-rate | Alert that needs a burn above a factor in a long and a short window, at several factors |
| Long window | The window that proves an event is significant |
| Short window | The window that proves it is still happening (about 1/12 of the long) |
| Threshold | The value that triggers an alert condition |
| Static threshold | A fixed constant bound |
| Anomaly detection | A statistical or ML detector of unusual values |
| False positive | An alert without a real problem |
| False negative | A real problem without an alert |
| Precision | Share of alerts that were significant |
| Recall | Share of significant events that alerted |
| Time to detect | Time between the problem starting and the notification |
for duration | How long a condition must hold before pending becomes firing |
keep_firing_for | How long a firing alert stays firing after the condition clears |
| Hysteresis | Separate fire and resolve thresholds to avoid flapping |
| Flapping | An alert repeatedly opening and closing |
| Alertmanager | The Prometheus component that deduplicates, groups, inhibits, silences and routes |
| Grouping | Merging related alerts into one notification |
| Inhibition | Muting target alerts while a source alert fires |
| Silence | A time-limited mute matched by label matchers |
| Routing | Choosing the receiver by label matchers |
| Severity | A label ranking urgency (page, ticket, none) |
| Runbook | A short document on what an alert means and what to do |
| Annotation | Free-text alert metadata such as summary and runbook_url |
| On-call | Duty to respond to pages during a shift |
| Rotation | The schedule of who is on call |
| Escalation policy | The ordered list of people tried when the first does not acknowledge |
| Handoff | Transfer of context at shift change |
| Pager fatigue | Reduced response caused by too many or too noisy pages |
| Alert review | A recurring meeting that prunes and tunes alerts |
| Dead man's switch | An alert that fires when an expected signal stops |
| Heartbeat alert | A periodic ping whose absence raises an alert |
| Watchdog | The always-firing Prometheus alert used as a pipeline heartbeat |
| Absent data | Missing samples, detected by absent() or no-data handling |
promtool test rules | Prometheus unit tests for rules with synthetic series |
| Blackbox exporter | Prometheus exporter that probes endpoints from outside |
| Synthetic probe | A fake request that exercises the user path |
| Grafana alerting | Grafana's rule, notification policy and contact point system |
| PagerDuty | On-call and incident product with an Events API |
| Opsgenie | Atlassian on-call product being shut down on 5 April 2027 |
| incident.io | On-call and incident response product centred on Slack |
| Datadog monitor | Datadog's alert definition (threshold, anomaly, forecast, composite) |
| Queue lag alert | An alert on message age or consumer lag |
| Oldest message age | How long the oldest unprocessed message has waited |
| Job SLA | The deadline by which a batch job must have completed |
| Postmortem | A written, blameless review of an incident and its follow-ups |
| Alert storm | Many alerts from one root cause |
| CPU alert anti-pattern | Paging on CPU use, a cause that is rarely a symptom |
| Notification channel | A delivery path for an alert: phone, SMS, chat, email, webhook |
pingBefore | Laravel scheduler hook that calls a URL before a task |
thenPing | Laravel scheduler hook that calls a URL after a task |
References
- Rob Ewaschuk, My Philosophy on Alerting: https://docs.google.com/document/d/199PqyG3UsyXlwieHaqbGiWVa8eMWi8zzAn0YfcApr8Q/preview
- Google SRE Book ch. 6, Monitoring Distributed Systems: https://sre.google/sre-book/monitoring-distributed-systems/
- Google SRE Book ch. 4, Service Level Objectives: https://sre.google/sre-book/service-level-objectives/
- Google SRE Book ch. 11, Being On-Call: https://sre.google/sre-book/being-on-call/
- Google SRE Book ch. 15, Postmortem Culture: https://sre.google/sre-book/postmortem-culture/
- Google SRE Workbook ch. 2, Implementing SLOs: https://sre.google/workbook/implementing-slos/
- Google SRE Workbook ch. 5, Alerting on SLOs: https://sre.google/workbook/alerting-on-slos/
- Prometheus alerting rules: https://prometheus.io/docs/prometheus/latest/configuration/alerting_rules/
- Prometheus unit testing for rules: https://prometheus.io/docs/prometheus/latest/configuration/unit_testing_rules/
- Prometheus query functions (
absent,absent_over_time): https://prometheus.io/docs/prometheus/latest/querying/functions/ - Prometheus Alertmanager overview: https://prometheus.io/docs/alerting/latest/alertmanager/
- Prometheus Alertmanager configuration: https://prometheus.io/docs/alerting/latest/configuration/
- blackbox_exporter README: https://raw.githubusercontent.com/prometheus/blackbox_exporter/master/README.md
- Grafana alerting: https://grafana.com/docs/grafana/latest/alerting/
- Grafana alert rules: https://grafana.com/docs/grafana/latest/alerting/fundamentals/alert-rules/
- PagerDuty incident response, being on call: https://response.pagerduty.com/oncall/being_oncall/
- PagerDuty Events API v2 overview: https://developer.pagerduty.com/docs/events-api-v2-overview
- PagerDuty, sending alert events: https://developer.pagerduty.com/docs/send-alert-event
- Atlassian, Opsgenie: https://www.atlassian.com/software/opsgenie
- incident.io documentation: https://docs.incident.io/
- Datadog monitors: https://docs.datadoghq.com/monitors/
- Healthchecks.io documentation: https://healthchecks.io/docs/
- Laravel 13 task scheduling: https://laravel.com/docs/13.x/scheduling
- Laravel 13 notifications: https://laravel.com/docs/13.x/notifications
- Laravel 13 queues: https://laravel.com/docs/13.x/queues
- Laravel 13 Horizon: https://laravel.com/docs/13.x/horizon
- Laravel 13 Pulse: https://laravel.com/docs/13.x/pulse