SLAs, SLOs, SLIs & Error Budgets
"An SLI is a service level indicator—a carefully defined quantitative measure of some aspect of the level of service that is provided." — Beyer, Jones, Petoff, Murphy (eds.), Site Reliability Engineering, chapter 4 "Service Level Objectives", Google / O'Reilly
Summary: A reliability target is a promise measured in numbers: the SLI is the measurement, the SLO is the internal target on it, the SLA is the external contract with consequences, and the error budget (100% minus the SLO) is the amount of failure you are allowed to spend on shipping change. Focus: Definitions and the differences between the three terms, choosing SLIs (availability, latency, correctness, freshness, throughput, durability; request-based versus window-based; where to measure), setting SLOs (percentiles, windows, the nines table), error budgets and burn rate, multiwindow multi-burn-rate alerting with concrete Prometheus rules, composite availability (serial versus parallel), SLOs across a monolith and microservices, SLA credits, reporting, common mistakes, and working code in Go and Laravel. Learning goal: Given any service, write one SLI as a ratio of good to valid events, pick an SLO and a window with the numbers behind them, compute the error budget and its burn rate, write the alert rules that page on fast burn and ticket on slow burn, and explain what happens to feature work when the budget is gone.
This chapter turns the vague word "reliable" into numbers an engineering team can negotiate, monitor and defend. It sits after Back-of-the-Envelope Capacity Estimation (how much load, how many machines) and before the architecture styles: the styles are judged by exactly the quality attributes written down here (What Software Architecture Is, Architecture Decisions and Trade-offs, From Requirements to Architecture). The code is Go with client_golang and Laravel 13 with a Prometheus client; the database angle (replication, observability) lives in Replication, Read Replicas & Failover and Database Observability.
Page map
| If you are looking for | Go to |
|---|---|
| The four terms and the nines table in a minute | Everything in one minute |
| Why we write targets down at all | Why it exists |
| Where the vocabulary comes from | Where it comes from |
| SLI, SLO, SLA, error budget, burn rate, one block each | The concept catalogue |
| Which SLI to choose for which kind of service | Choosing SLIs |
| Request-based versus window-based, and where to measure | Request vs window, Where to measure |
| 99.9 versus 99.99 in minutes per year | The nines |
| Serial and parallel availability math | Composite availability |
| Freeze features when the budget is gone | Error budget policy |
| Page on burn rate with Prometheus rules | Alerting on burn rate |
| Cloud SLA examples and credits | SLAs and credits |
| Go and Laravel instrumentation | Go, Laravel |
| Monolith, microservices, latency budgets | In architecture |
| A fault-injection lab with an alert | Lab |
| Wrong beliefs, cheat sheet, self-check, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The four terms. Every row is unpacked in the concept catalogue.
| Term | In plain words | Tiny example | What goes wrong without it |
|---|---|---|---|
| SLI (Service Level Indicator) | A measured number about user experience, usually good events divided by valid events | 99.93% of /orders requests returned non-5xx in the last 28 days | Everyone argues from feelings and dashboards that disagree |
| SLO (Service Level Objective) | The target you set on an SLI for a window | "99.9% of /orders requests succeed over 28 days" | No way to say when the service is good enough or when to stop shipping |
| SLA (Service Level Agreement) | A contract that says what the customer gets if the target is missed | "Below 99.99% monthly uptime, 10% service credit" | Customers assume guarantees you never made, or you owe money you did not plan for |
| Error budget | 100% minus the SLO: the failure you may spend | 0.1% of requests, about 43 minutes of full outage in 30 days | Reliability and feature speed fight with opinions instead of data |
| Burn rate | How fast the budget is spent relative to the SLO | 14.4 means the 30-day budget is gone in about 2 days | Alerts fire on blips or notice real incidents too late |
| Error budget policy | The agreed consequences of an empty budget | Freeze launches until back within SLO | The budget is a number nobody acts on |
SLI, SLO, SLA in one table.
| Question | SLI | SLO | SLA |
|---|---|---|---|
| What is it | A measurement | A target on the measurement | A contract about the target |
| Example | good / valid requests | at least 99.9% over 28 days | 99.9% monthly or a 10% credit |
| Who owns it | The team that runs the service | Product and engineering together | Business and legal |
| Consequence of missing | None by itself | Error budget policy (internal) | Money, credits, contract terms (external) |
| Strictness | Whatever is true | Tighter than the SLA | Looser than the SLO on purpose |
The nines (availability over a 30-day month and a year), computed by the code in Go:
| SLO | Error budget | Per day | Per 28 days | Per 30 days | Per year |
|---|---|---|---|---|---|
| 99% | 1% | 14.4 min | 6.7 h | 7.2 h | 3.6 days |
| 99.5% | 0.5% | 7.2 min | 3.4 h | 3.6 h | 43.8 h |
| 99.9% | 0.1% | 1.4 min | 40.3 min | 43.2 min | 8.8 h |
| 99.95% | 0.05% | 43.2 s | 20.2 min | 21.6 min | 4.4 h |
| 99.99% | 0.01% | 8.6 s | 4.0 min | 4.3 min | 52.6 min |
| 99.999% | 0.001% | 0.9 s | 24.2 s | 25.9 s | 5.3 min |
Burn rate for a 99.9% SLO and a 30-day window (the Workbook's Table 5-4 plus the rows used by alerts):
| Burn rate | Error ratio | Time to empty the budget |
|---|---|---|
| 1 | 0.10% | 30 days |
| 2 | 0.20% | 15 days |
| 6 | 0.60% | 5 days |
| 10 | 1.00% | 3 days |
| 14.4 | 1.44% | 2.1 days |
| 36 | 3.60% | 20 hours |
| 1000 | 100% | 43.2 minutes |
Why it exists
Every service is unreliable somewhere; the only question is how much, and who decided. Without numbers, "make it more reliable" and "ship faster" are opinions at war. The SRE book frames it as a cost curve: past a certain point, more reliability is worse for the service and its users because it limits how fast features ship and raises cost. An SLO is the line where both sides agree to stop.
| Without explicit targets | With SLI, SLO and an error budget |
|---|---|
| Operations says "too risky", product says "too slow", nobody has a number | A shared number says how much risk is left this month |
| Users form their own expectations, often wrong | Published SLOs set expectations, so users neither over-rely nor under-rely |
| Alerts fire on every error spike, on-call burns out | Alerts fire when the budget is threatened |
| Reliability work loses every prioritisation fight | An empty budget makes reliability work the agreed priority |
| Good for: a prototype with five users | Good for: any service another team or a customer depends on |
The picture shows the layering: the SLI at the base is a measurement, the SLO is a tighter internal target on it, and the SLA at the top is the looser external promise. Tighter inside, looser outside: the gap is your safety margin.
The analogy we reuse: a household budget. The bank statement is the SLI (what really happened). Your own savings goal is the SLO ("keep 10% of income"). The loan contract with the bank is the SLA (miss the payment and there is a fee). The error budget is the monthly allowance for things that can go wrong or be fun: spend it on risk (releases, experiments) and when it is gone, you stop spending until next month. A goal of "never spend anything" is the 100% target: impossible and not what anyone wants.
Three common misunderstandings, up front
- "SLA, SLO and SLI are three names for the same thing." No. The SRE book footnote says most people who say "SLA violation" mean a missed SLO; a real SLA violation might trigger a court case for breach of contract. The test is the consequence: no explicit consequence means SLO.
- "More nines is always better." No. Past a point users cannot tell, features slow down and cost explodes (the "99% reliable smartphone" argument below).
- "The SLO is whatever we currently achieve." No. Picking the target from current performance can lock you into heroic effort or into a number that no user asked for; start from what users care about.
Where it comes from
| Source | What it gave us |
|---|---|
| SRE book, chapter 3 "Embracing Risk" | Risk as a cost curve, availability as a request success rate, the error budget as a control loop between product and SRE |
| SRE book, chapter 4 "Service Level Objectives" | The definitions of SLI, SLO, SLA, percentiles instead of averages, rules for choosing targets, the Chubby planned outage |
| SRE Workbook, chapter 2 "Implementing SLOs" | SLI as a ratio of good to total events, SLI specification versus implementation, windows, stakeholder agreement, the error budget policy |
| SRE Workbook, chapter 5 "Alerting on SLOs" | Burn rate and the six alerting iterations ending in multiwindow, multi-burn-rate alerts |
| SRE Workbook, appendix B | An example error budget policy |
| Cloud provider SLAs (AWS, Google Cloud) | The contract side: uptime percentages, definitions of "unavailable", credits and exclusions |
| Prometheus and OpenTelemetry docs | The instruments (counters, histograms), recording rules, alerting rules |
"It’s both unrealistic and undesirable to insist that SLOs will be met 100% of the time: doing so can reduce the rate of innovation and deployment, require expensive, overly conservative solutions, or both." — SRE book, chapter 4
A detail worth remembering: Google's own SRE book calls SLA a contract with consequences, yet Google Cloud's published Cloud SQL SLA text introduces its uptime targets as "Service Level Objective" or "SLO" and attaches financial credits to them. The vocabulary in vendor documents is looser than the book; read the contract's definitions, not its title.
The concept catalogue
SLI: Service Level Indicator Must-know
In plain words: One number that says how good the service is for its users right now, measured the same way every time. The Workbook recommends writing it as good events divided by valid events, so it runs from 0% (nothing works) to 100% (nothing is broken).
Common misunderstanding: "Any metric in Grafana is an SLI." No. The SRE book warns against using every metric you can track; pick a handful that represent what users care about. CPU at 80% is a cause, not an experience.
Definition: SLI = good events / valid events over a window. "Valid" excludes events that are not your fault or not in scope (a 404 for a URL that never existed, a 400 from a client bug, health checks, load tests).
"we generally recommend treating the SLI as the ratio of two numbers: the number of good events divided by the total number of events." — SRE Workbook, chapter 2 "Implementing SLOs"
The Workbook splits the idea in two: the SLI specification (what you think matters to users, independent of how it is measured: "the proportion of requests that succeed") and the SLI implementation (the specification plus a way to measure it: "5xx responses at the load balancer, from the access log"). One specification can have several implementations with different quality (how accurately it captures the experience), coverage (how many customers it captures) and cost.
SLI specification : proportion of valid HTTP requests that succeed
SLI implementation : sum(rate(http_requests_total{code!~"5.."}[5m])) <- numerator (good)
/ sum(rate(http_requests_total[5m])) <- denominator (valid)
Excluded as invalid : /healthz, /metrics, load-test traffic, 4xx caused by the callerReal scenario: a checkout API where "good" means HTTP status below 500 and answered within 300 ms; a nightly report pipeline where "good" means the report finished before 06:00; an object store where "good" means the object written yesterday can be read today.
SLO: Service Level Objective Must-know
In plain words: The target you commit to for the SLI over a period: "99.9% of requests succeed, measured over 28 days". It is the line between "good enough" and "stop and fix".
Common misunderstanding: "An SLO is a promise to customers." No, that is the SLA. The SLO is an internal goal that drives engineering priorities; it is usually tighter than anything you promise outside.
Definition: a target value or range for an SLI over a window, written so it says how it is measured and when it applies. The SRE book's examples: "99% of Get RPC calls will complete in less than 100 ms", and, for the shape of the curve, three targets at once (90% under 1 ms, 99% under 10 ms, 99.9% under 100 ms).
A complete SLO statement has five parts: the SLI, the target, the window, the scope (which route, which customers), and the owner.
1 SLI good = non-5xx responses of GET/POST /orders; valid = all non-4xx requests, measured at the load balancer
2 Target 99.9%
3 Window rolling 28 days
4 Scope all customers, production, excluding synthetic load tests
5 Owner team-orders (escalation: head of platform)Real scenario: the team publishes orders: 99.9% over 28 days on a wiki page, dashboards show the remaining budget, and the product manager signs the error budget policy.
SLA: Service Level Agreement Must-know
In plain words: The legal version. It says what the customer gets (usually money back) when you miss the number.
Common misunderstanding: "An SLA is a stricter SLO." The reverse: an SLA is deliberately looser than the internal SLO, so you can notice and fix a problem before you owe anyone anything.
Definition: "an explicit or implicit contract with your users that includes consequences of meeting (or missing) the SLOs they contain" (SRE book). Business and legal pick the consequences; SRE helps estimate how likely and how hard it is to meet the numbers, and helps define SLIs so the contract can be checked.
"An easy way to tell the difference between an SLO and an SLA is to ask "what happens if the SLOs aren’t met?": if there is no explicit consequence, then you are almost certainly looking at an SLO." — SRE book, chapter 4
Real scenario: AWS and Google Cloud publish SLAs with tiers of service credit (see SLAs and credits). Google Search has no SLA to the public, but still has SLOs because an outage would still cost reputation and advertising revenue.
Error budget Must-know
In plain words: If the SLO is 99.9%, you are allowed to fail 0.1% of requests. That 0.1% is a budget you can spend on deployments, experiments, migrations and plain bad luck.
Common misunderstanding: "An error budget is a quota to fill." No. It is a limit, not a target. A service that never touches its budget is probably over-invested in reliability (or its SLO is too loose to matter); the book's Chubby example deliberately takes the service down in a quarter where it would otherwise over-deliver.
Definition: error budget = 1 − SLO. The Workbook's worked example: 1,000,000 requests in four weeks and a 99.9% availability SLO give a budget of 1,000 errors. The SRE book's version: an SLO of 99.999% per quarter means a failure rate of 0.001%; failing 0.0002% of queries spends 20% of the quarter's budget.
T0 SLO 99.9% over 28 days, 1,000,000 expected requests -> budget 1,000 bad requests
T1 day 6 bad deploy fails 300 requests -> 30% spent, 70% left
T2 day 11 dependency outage fails 450 requests -> 75% spent, 25% left
T3 day 13 one more incident fails 260 requests -> 101% spent -> error budget policy triggers
T4 day 13 feature launches paused, reliability backlog first, until back within SLOReal scenario: a shared-nothing release train: a team with 80% budget left ships two features and a risky migration; a team with 3% left ships only fixes. The number, not a meeting, decides.
"(An error budget is just an SLO for meeting other SLOs!)" — SRE book, chapter 4
Burn rate Must-know
In plain words: The speed at which you spend the budget. Burn rate 1 means you will use exactly all of it at the end of the window. Burn rate 10 means it is gone in a tenth of the window.
Common misunderstanding: "A 1% error rate is small, so it is fine." Whether 1% is fine depends on the SLO: against 99.9% that is burn rate 10 (budget gone in 3 days), against a 99% SLO it is burn rate 1.
"Burn rate is how fast, relative to the SLO, the service consumes the error budget." — SRE Workbook, chapter 5 "Alerting on SLOs"
Definition: burn rate = observed error ratio / (1 − SLO). Time to empty a fresh budget = window / burn rate. Budget spent while burning = burn rate × time held / window.
The chart shows a 30-day window at a 99.9% SLO: a constant burn of 1 drains the budget exactly at day 30, a burn of 2 at day 15, a burn of 10 at day 3. The thick line is a realistic month: one 40% incident on day 9, then a slow burn that ends the window with a little left. Below zero is where the error budget policy applies.
Choosing SLIs: the menu Must-know
In plain words: Different kinds of systems fail in different ways, so they get different indicators. Start with the few that users notice.
Common misunderstanding: "Availability and latency are enough for everything." For a pipeline, the user who sees yesterday's data does not care that the API answered quickly; freshness and correctness matter. The SRE book says all systems should care about correctness, even though it is often a data property and not an infrastructure one.
| Indicator | Good event | Typical for | Example SLO |
|---|---|---|---|
| Availability | The request succeeded (non-5xx, valid response) | Request-driven services, APIs | 99.9% of requests succeed |
| Latency | The request was faster than a threshold | Request-driven services, storage | 99% of requests under 300 ms |
| Quality | The answer was not degraded (full results, not a fallback) | Services that degrade gracefully | 99.5% of search results use the full index |
| Correctness | The right answer or record came out | Pipelines, billing, any data | 99.99% of invoices match the ledger |
| Freshness | The data is newer than a threshold | Pipelines, caches, read replicas | 99% of reads see data under 10 minutes old |
| Coverage | Enough of the input was processed | Batch and streaming jobs | 99% of nightly jobs process at least 99.9% of records |
| Throughput | The system processed enough per unit of time | Pipelines, queues, ingestion | 95% of 5-minute intervals ingest at least 1,000 events/s |
| Durability | A written record can still be read | Storage systems | 99.999999% of written objects readable after a year |
The Workbook groups the choice by component type: request-driven (availability, latency, quality), pipeline (freshness, correctness, coverage), storage (durability, plus availability and latency). It recommends five or fewer SLI types and, to capture both the typical experience and the long tail, several grades of SLO on the same SLI (for example 90% under 100 ms and 99% under 1 s).
Fix / how to use it: draw the architecture, mark the critical user journeys (search, add to cart, pay), and pick one availability and one latency SLI per journey first. Add freshness or correctness only where a wrong or stale answer costs more than a slow one.
Request-based versus window-based SLIs Important
In plain words: A request-based SLI counts events: 999 of 1000 requests were good. A window-based SLI chops time into slices (minutes) and counts how many slices were good: 43,000 of 43,200 minutes were good.
Common misunderstanding: "They give the same number." They do not. A five-minute total outage at 03:00 with no traffic costs almost nothing in request-based terms, but five bad minutes in window-based terms. A tiny error rate spread evenly can fail zero windows yet fail many requests.
| Request-based | Window-based (good minutes, uptime) | |
|---|---|---|
| Unit | Request or event | Minute (or other slice) |
| Numerator and denominator | Good requests, valid requests | Good minutes, minutes with traffic |
| Weights busy time more | Yes: busy hours dominate | No: each minute counts the same |
| Works with zero traffic | Undefined | Needs a rule (probe or skip) |
| Matches contracts | Rarely | Often: SLAs usually count unavailable minutes |
| Alerting | Easy with rate ratios | Harder, needs a per-minute good/bad series |
| Used in | Internal SLOs, Prometheus burn-rate alerts | Cloud SLAs, uptime pages |
AWS's EC2 SLA defines the monthly uptime percentage as 100% minus the percentage of minutes in the month the service was unavailable: a window-based number. The SQL below computes both kinds from one request log.
-- Window-based SLI: a minute is good when at least 99% of its requests succeeded.
WITH per_minute AS (
SELECT date_trunc('minute', ts) AS minute,
count(*) FILTER (WHERE status < 500)::float / count(*) AS success_ratio
FROM request_log
WHERE route = '/orders' AND ts >= now() - interval '28 days'
GROUP BY 1
)
SELECT count(*) FILTER (WHERE success_ratio >= 0.99) AS good_minutes,
count(*) AS minutes_with_traffic
FROM per_minute;The full report (request-based SLI, latency SLI, budget spent, burn rate and an SLA credit lookup) is in the SQL snippet in Solving the classic problems (sql/slo-report.sql).
Where to measure Important
In plain words: The nearer to the user you measure, the more of the real problems you see; the nearer to the code, the easier and cheaper it is.
Common misunderstanding: "The application's own metrics are the truth." A crashed process reports nothing, a full listen queue never reaches the handler, and a panicking Go handler is not reported by promhttp (see its documentation: "If the wrapped Handler panics, no values are reported."). The app cannot count requests it never saw.
user device ──> CDN / edge ──> load balancer ──> app server ──> database
(1) (2) (3) (4) (5)
client-side edge logs LB metrics app metrics dependency
instrumentation (promhttp) metrics| Where | Sees | Misses | Cost |
|---|---|---|---|
| 1. Client (browser, mobile app, RUM) | Real latency, JavaScript failures, DNS and network problems | Needs instrumentation, noisy, depends on user networks | Highest |
| 2. CDN or edge | Cache hits, geo problems | Origin internals | Low if you already pay for it |
| 3. Load balancer | Every request that reached the fleet, including ones the app dropped; status and latency | Client-side rendering, anything before the LB | Low: metrics already exist |
| 4. Application | Business-level success (a 200 with an error body), per-route detail | Crashes, queue time, requests that never arrived | Low, but blind to its own death |
| 5. Dependency | Cause of failures | User impact | Cheap, but it is a cause, not an SLI |
| Synthetic probe (black box) | Works at zero traffic, checks the whole path | Only the paths you probe, not real users | Medium |
The Workbook's example uses load-balancer metrics for availability and latency because they exist already and are closer to the user than the application logs, and a client-side measurement for pipeline freshness. It also notes that "it is better to count the slow requests than to approximate them with a histogram".
Fix: start at the load balancer or ingress, add synthetic probes for zero-traffic periods, and use application metrics for diagnosis and per-route detail, not as the only truth.
Percentiles, histograms and why averages lie Must-know
In plain words: The average hides slow requests. If 95 requests take 50 ms and 5 take 1 second, the average is 97 ms and looks fine, but one user in twenty waits a second.
Common misunderstanding: "Average latency under 100 ms means users are happy." The SRE book's Figure 4-1 shows a typical request at 50 ms while 5% were 20 times slower, and an average-only alert would show no change.
"Most metrics are better thought of as distributions rather than averages." — SRE book, chapter 4
Definition: a percentile pN is the value below which N% of observations fall. An SLO of "99% of requests under 300 ms" is a statement about the 99th percentile. In Prometheus you do not store percentiles (they cannot be averaged across instances); you store histogram buckets and count the share of requests below a threshold.
| Style | SLO sentence | How to compute | Notes |
|---|---|---|---|
| Threshold ratio (preferred) | 99% of requests under 300 ms | bucket{le="0.3"} divided by _count | Exact if a bucket boundary sits at 0.3 |
| Quantile estimate | p99 under 300 ms | histogram_quantile(0.99, sum by (le) (rate(..._bucket[5m]))) | Interpolated inside a bucket; error grows with wide buckets |
| Average | mean under 100 ms | rate(sum) divided by rate(count) | Hides the tail; do not use as an SLO |
| Summary quantile | p99 from the client library | {quantile="0.99"} | Cannot be aggregated across replicas: never avg() it |
The Prometheus histogram guide spells out the point for SLOs: with a classic histogram you get an accurate fraction only if a bucket boundary sits on the SLO threshold, which is why the Go code in this chapter puts a boundary at 0.3.
Real scenario: an API with three replicas must compute one p99; averaging three per-replica p99 values is wrong, summing buckets and then calling histogram_quantile is right.
Time windows: rolling versus calendar Important
In plain words: Over what period do you measure "99.9%"? A rolling window always looks back the same length; a calendar window resets on the first of the month.
Common misunderstanding: "Reset the budget every month, it is simpler." A calendar reset means a disaster on the 30th is forgotten on the 1st, while users remember it.
"Rolling windows are more closely aligned with user experience: if you have a large outage on the final day of a month, your user doesn’t suddenly forget about it on the first day of the following month." — SRE Workbook, chapter 2
| Rolling window | Calendar window | |
|---|---|---|
| Matches users | Yes | No: resets forget incidents |
| Matches business planning | Weakly | Yes: quarterly reviews and contracts |
| Mid-period forecast | Stable | Uncertain: unknown traffic for the rest of the period |
| Typical choice | Four weeks (28 days): "a good general-purpose interval" | Month or quarter for SLAs and reports |
The Workbook recommends an integer number of weeks so every window holds the same number of weekends, uses four weeks as a default, and complements it with weekly summaries for task prioritisation and quarterly reports for planning. Shorter windows give faster feedback; longer ones suit multi-quarter decisions.
The nines: what 99.9 versus 99.99 means Must-know
In plain words: Each extra nine divides the allowed downtime by ten, and roughly multiplies the cost and the engineering effort.
Common misunderstanding: "99.99% is just a bit better than 99.9%." It is ten times less downtime: 43 minutes per month becomes 4.3 minutes, below the time a human needs to be paged and open a laptop.
| SLO | 30-day budget | What it implies for the design | Typical fit |
|---|---|---|---|
| 99% | 7.2 h | A single server and manual recovery are acceptable | Internal tools, batch dashboards |
| 99.9% | 43.2 min | Redundant app tier, automated failover, on-call, safe deploys | Most B2B and consumer APIs |
| 99.95% | 21.6 min | Multi-AZ everything, zero-downtime migrations, fast rollback | Payments front doors, important SaaS |
| 99.99% | 4.3 min | No human in the loop: automated detection and recovery, multi-region or cell design | Core infrastructure, regional cloud services |
| 99.999% | 25.9 s | Active-active, dependency isolation, almost no change risk | Telecom, life-critical control |
The SRE book's cost argument: "a user on a 99% reliable smartphone cannot tell the difference between 99.99% and 99.999% service reliability". It also gives a worked cost estimate: for a service with $1M revenue where each request has equal value, going from 99.9% to 99.99% is worth $1M × 0.0009 = $900, so "if the cost of improving availability by one nine is less than $900, it is worth the investment". The lesson is to price the nine, not to count nines.
Fix: pick the lowest SLO users will not complain about, then keep an internal SLO a little tighter than the one you publish ("keep a safety margin").
Composite availability: serial versus parallel Must-know
In plain words: If a request needs three things to all work, multiply their availabilities (the result is lower than any single one). If any one of several copies is enough, multiply their failure rates (the result is higher).
Common misunderstanding: "Three components at 99.9% give a 99.9% system." They give 99.70%: 130 minutes of downtime per 30 days instead of 43. And the parallel formula needs independent failures: two replicas in the same zone, on the same database, behind the same bad deploy fail together.
| Pattern | Formula | Example | Result |
|---|---|---|---|
| Serial (all needed) | A × B × C | 3 services at 99.9% | 99.70% (about 130 min per 30 days) |
| Serial, longer chain | product of all | 5 services at 99.9% | 99.50% (about 215 min per 30 days) |
| Parallel (any one) | 1 − (1−A)(1−B) | 2 replicas at 99% | 99.99% |
| Mixed | serial of parallel groups | LB 99.99% → app 2 × 99.5% → DB 99.95% | 99.94% (about 27 min per 30 days) |
| With a fallback | serial, but the dependency failure is masked | Recommendations with cached default | Availability of the page, not of the dependency |
The reverse rule for dependencies: to promise 99.9% you need critical hard dependencies noticeably above 99.9%, or you must soften them (cache, default, queue, degrade). Remove a hard dependency and you also remove a multiplier.
SLOs for dependencies Important
In plain words: Your service is only as reliable as the things it needs. Agree an SLO with every team (and every vendor) you depend on, then check that the math closes.
Common misunderstanding: "If a dependency never fails, I do not need to plan for it." The SRE book's Chubby story: the global lock service was so reliable that service owners assumed it never went down and built hard dependencies on it, so Google deliberately takes it down in a quarter if it has not failed enough. "SRE makes sure that global Chubby meets, but does not significantly exceed, its service level objective."
1 Orders SLO target: 99.9% -> needs hard dependencies at about 99.95% or better
2 Payments provider SLA: 99.9% -> too weak as a hard dependency
3 Options: (a) async via queue + retry, (b) second provider in parallel, (c) soften SLO of the payment step
4 Result: Orders hard path = gateway 99.99% x orders 99.95% x DB 99.95% = 99.89% (still short; add replicas)| Dependency type | Tactic |
|---|---|
| Internal team service | Agree an SLO, a latency budget and an error budget policy for the dependency; alert on its SLI |
| Third-party SaaS | Read the SLA's definition of unavailable and its exclusions; assume the SLA is the best case |
| Cloud primitive (instance, database, queue) | Use the multi-AZ SLA tier (e.g. region-level) and design for it |
| Optional feature | Degrade gracefully and count the response as "quality" good or bad |
| Hard, critical, weak dependency | Isolate with a queue, cache, circuit breaker or a second provider (see Service Communication) |
Error budget policy Must-know
In plain words: A written agreement, signed by product, engineering and SRE, that says what happens when the budget is empty. Without it, the budget is just a number.
Common misunderstanding: "A freeze is a punishment." The Workbook's example policy says it is not: "Halting change is undesirable; this policy gives teams permission to focus exclusively on reliability when data indicates that reliability is more important than other product features."
"Common policies include stopping feature launches until the service is once again within SLO or devoting some or all engineering time to working on reliability-related bugs." — SRE Workbook, chapter 2
The Workbook's example policy (appendix B, dated 2018-02-19) is a good template:
| Trigger | Action |
|---|---|
| Service at or above SLO | Releases proceed according to the release policy |
| Error budget exceeded for the preceding four-week window | Halt all changes and releases except P0 issues and security fixes until back within SLO |
| A code bug or procedural error caused the miss | The team must work on reliability |
| A postmortem shows a hard dependency could be softened | The team must work on reliability |
| Outage caused by a company-wide network problem, or by another team that has itself frozen | The team may continue feature work |
| Budget eaten by out-of-scope users (load tests, penetration testers) | The team may continue feature work |
| One incident consumes more than 20% of the budget over four weeks | Postmortem required, with at least one P0 action item |
| One class of outage consumes more than 20% of the budget over a quarter | A P0 item in the next quarter's planning |
| Disagreement about the calculation or actions | Escalate to the CTO |
The SRE book adds the softer end: slowing releases or rolling them back when the budget is nearly used up, instead of a hard on/off freeze; and it notes the policy only works if SRE has the authority to actually stop launches.
T0 day 1 budget 100%, deploys proceed (several per day)
T1 day 8 budget 60% - normal
T2 day 14 budget 25% - warning: risky changes need review; canary traffic halved
T3 day 17 budget 0% - policy: freeze features, only fixes; reliability backlog first
T4 day 24 rolling window forgets the day-8 incident -> budget 12% -> freeze liftedSLAs and credits Important
In plain words: The provider promises a monthly uptime; if it misses, the customer gets a credit on future bills, usually only if they ask for it.
Common misunderstanding: "An SLA means the provider is liable for my losses." The AWS text is explicit that a service credit is not a refund and is the sole and exclusive remedy; a lost business day costs you far more than the credit.
| AWS: Amazon Compute SLA (EC2), last updated May 25, 2022 | Google Cloud: Cloud SQL SLA | |
|---|---|---|
| Target | Region-level 99.99% (instances in two or more AZs); instance-level 99.5% | 99.99% (Enterprise Plus with HA or a read pool of two or more nodes); 99.95% (Enterprise with HA) |
| Credit tiers | 10% below 99.99% and at least 99.0%; 30% below 99.0% and at least 95.0%; 100% below 95.0% | Enterprise Plus: 10% below 99.99% to 99.0%, 25% below 99.0% to 95.0%, 100% below 95.0%. Enterprise: 10% below 99.95% to 99.0%, 25% to 95.0%, 50% below 95.0% |
| Unit counted | Minutes in which all running instances in two or more AZs have no external connectivity | Downtime Period: one consecutive minute in which all valid requests fail; shorter blips do not count |
| How to claim | Open a support case within two billing cycles, with request logs | Customer must request the credit |
| Remedy | Credit against future payments only, not a refund | Credit to future bills; sole and exclusive remedy |
| Notable exclusions | Force majeure, your own actions, your software or equipment | Scheduled maintenance for Enterprise edition; shared-core, single-zone and one-node read pools are not covered |
"AWS will use commercially reasonable efforts to make Amazon EC2 available for each AWS region with a Monthly Uptime Percentage of at least 99.99%" — Amazon Compute Service Level Agreement (EC2), https://aws.amazon.com/compute/sla/
The numbers show why an SLA is not an SLO: the instance-level promise of 99.5% allows about 3.6 hours a month for a single instance, and the region-level 99.99% requires you to run in two or more AZs to qualify at all. The design consequence ("deploy across AZs") is part of the contract.
A worked credit: a 30-day month is 43,200 minutes; 62 unavailable minutes give 99.856% uptime, which is below 99.99% and above 99.0%, so a 10% credit on that month's bill (the PHP SlaCreditCalculator and the SQL lookup in the snippets do exactly this).
What we sell versus what we run: if you offer an SLA to your own customers, set the internal SLO tighter (for example SLA 99.9%, SLO 99.95%) and make sure the credit exposure (credit × monthly revenue) is smaller than the cost of the reliability work that would avoid it.
Critical user journeys and graded SLOs Good to know
In plain words: Users do tasks (search, add to cart, pay), not requests. A journey is a chain of requests; measure the chain.
Common misunderstanding: "Per-endpoint SLOs cover the user." A journey can fail at step three even if every endpoint looks fine in isolation; the Workbook suggests critical user journeys to improve recall without hurting precision.
| Journey | Steps | SLI | Weight |
|---|---|---|---|
| Search | query, results page | availability and latency of results | Medium |
| Add to cart | add, view cart | availability | High |
| Pay | create order, authorise, confirm | availability and correctness | Highest: tightest SLO and alert |
Grade interaction importance: a failed payment and a failed avatar upload should not burn the same budget, so either split the SLOs or weight the events.
Low-traffic services Good to know
In plain words: With 10 requests an hour, one failure is a 10% error rate for that hour; ratios are noisy and burn-rate alerts misfire.
Common misunderstanding: "Use the same alert parameters everywhere." The Workbook's options for low traffic: generate artificial traffic, combine small services into a larger group for monitoring, change the product so that one failed request matters less (client retries with backoff and jitter, fallback paths), or lower the SLO or lengthen the window.
Mechanics
The formulas Must-know
| Quantity | Formula | Example (SLO 99.9%, window 30 d) |
|---|---|---|
| Error budget | 1 − SLO | 0.001 |
| Allowed downtime | window × (1 − SLO) | 43.2 min |
| Burn rate | error ratio / (1 − SLO) | 1.44% / 0.1% = 14.4 |
| Time to exhaustion | window / burn rate | 30 d / 14.4 = 2.08 d |
| Budget spent while burning | burn rate × held time / window | 14.4 × 1 h / 720 h = 2% |
| Burn rate for a chosen spend | spend × window / alert window | 0.02 × 720 h / 1 h = 14.4 |
| Serial availability | product of availabilities | 0.999³ = 0.997 |
| Parallel availability | 1 − product of failures | 1 − 0.01² = 0.9999 |
These are implemented, and tested, in budget/budget.go. The Workbook's warning about a single burn-rate threshold: "A 35x burn rate never alerts, but consumes all of the 30-day error budget in 20.5 hours", which is why one threshold is never enough.
From an SLI to an alert: the six iterations Must-know
The Workbook's chapter 5 walks through six alerting designs, scoring each on four parameters: precision (the share of alerts that were significant), recall (the share of significant events that alerted), detection time and reset time (how long an alert keeps firing after the problem is fixed).
| # | Design | Good | Bad |
|---|---|---|---|
| 1 | Error ratio over 10 minutes above the SLO's ratio | Detects a full outage in under a second | Low precision: a 0.1% error rate for 10 minutes alerts while spending 0.02% of the monthly budget |
| 2 | Longer window (36 hours, alert at 5% of the budget) | Better precision | Reset time very poor: a 100% outage keeps alerting for 36 hours |
| 3 | Add a duration (for) | Higher precision | Poor recall: the duration does not scale with severity; a 100% outage waits an hour like a 0.2% one. The Workbook does not recommend durations in SLO alerting |
| 4 | Alert on burn rate (1 h window, burn rate 36 for 5% spend) | Good precision and detection time, reset 58 minutes | Low recall: a 35x burn never alerts but empties the budget in 20.5 hours |
| 5 | Multiple burn rates and windows | Pages for fast burn, tickets for slow burn; good recall | Even longer reset time because of the three-day window |
| 6 | Multiwindow, multi-burn-rate | Adds a short window (about 1/12 of the long one) so the alert stops soon after the problem | More parameters to manage |
"A good guideline is to make the short window 1/12 the duration of the long window" — SRE Workbook, chapter 5, iteration 6
The Workbook's recommended starting parameters for a 99.9% SLO (Table 5-8):
| Severity | Long window | Short window | Burn rate | Budget consumed |
|---|---|---|---|---|
| Page | 1 hour | 5 minutes | 14.4 | 2% |
| Page | 6 hours | 30 minutes | 6 | 5% |
| Ticket | 3 days | 6 hours | 1 | 10% |
(The Workbook's rule example also shows a ticket rule at 3x over 24 hours and 2 hours; our rule file includes both ticket rules.) The alert fires only when both the long window and the short window exceed the threshold. The long window gives significance (a real chunk of budget is gone), the short window gives currency (it is still happening).
"We recommend 2% budget consumption in one hour and 5% budget consumption in six hours as reasonable starting numbers for paging, and 10% budget consumption in three days as a good baseline for ticket alerts." — SRE Workbook, chapter 5
Prometheus: recording rules, alert rules, and the knobs Must-know
| Knob | Where | Meaning |
|---|---|---|
record: | rule group | Precompute an expression and store it as a new series; the name convention is level:metric:operations |
expr: | recording and alerting rule | The PromQL expression evaluated each interval |
interval: | rule group | How often the group is evaluated (global evaluation_interval is the default) |
for: | alerting rule | The condition must hold this long before the alert goes from pending to firing; the Workbook advises against durations for SLO burn alerts |
keep_firing_for: | alerting rule | Keep an alert firing this long after the condition stops matching, to avoid flapping |
labels: and annotations: | alerting rule | Routing labels such as severity: page and human text such as a runbook URL |
rate(x[5m]) | PromQL | Per-second average increase of a counter over the window |
increase(x[28d]) | PromQL | Total increase over the window (expensive over long windows: use a recording rule) |
le="0.3" | histogram bucket label | Cumulative bucket: requests at most 0.3 s |
The recording rules (prometheus/slo-rules.yml) store the error ratio for each window, so the alert expressions stay readable and cheap; the alert rules (prometheus/slo-alerts.yml) compare them to burn rate × 0.001.
SLI error ratio, one window (recording rule, e.g. window 1h):
sum by (job) (rate(http_requests_total{route="/orders", code=~"5.."}[1h]))
/ sum by (job) (rate(http_requests_total{route="/orders"}[1h]))
Latency SLI, share slower than 300 ms (histogram):
1 - sum by (job) (rate(http_request_duration_seconds_bucket{le="0.3"}[5m]))
/ sum by (job) (rate(http_request_duration_seconds_count[5m]))Timeline: one incident through the alerts Must-know
From the lab (a ten percent error fault from minute 60 to 75, 600 requests per minute, 99.9% SLO), computed by the Go program in lab/main.go on a virtual clock:
T event 5m ratio 1h ratio multiwindow 1h-only
60 fault starts (10% of requests fail) 0.00% 0.00% quiet quiet
69 1h ratio crosses 1.44% (burn 14.4) 10% 1.5% FIRES FIRES
75 fault ends 10% 2.6% FIRES FIRES
80 5m window clears 0.00% 2.6% RESOLVES FIRES
127 1h window finally below 1.44% 0.00% 1.4% quiet RESOLVESBoth designs notice the problem at the same minute; the multiwindow rule stops paging 47 minutes sooner. This matches the Workbook's 58-minute reset-time complaint for the single-window design.
Go
Example: SLI middleware with promhttp
The service instruments one route with a counter and a histogram. promhttp.InstrumentHandlerDuration and InstrumentHandlerCounter accept only the labels code and method, so the route is attached with MustCurryWith, using the route pattern (never the raw path). Recover sits inside the instrumentation, because a panicking handler would otherwise leave no trace in the SLI.
// Package service wires an HTTP handler to the SLI metrics that an
// availability SLO and a latency SLO need: a request counter and a latency
// histogram, both labelled by status code, method and route.
package service
import (
"fmt"
"math/rand"
"net/http"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
// LatencyBuckets contains a boundary at exactly 0.3 s because the latency SLO
// ("95% of requests under 300 ms") is computed from the le="0.3" bucket.
// Prometheus docs: the fraction is exact only when a bucket boundary sits
// on the threshold.
var LatencyBuckets = []float64{0.01, 0.025, 0.05, 0.1, 0.2, 0.3, 0.5, 1, 2.5, 5}
// Metrics owns the two SLI instruments.
type Metrics struct {
Requests *prometheus.CounterVec
Duration *prometheus.HistogramVec
}
// NewMetrics registers the instruments on reg.
func NewMetrics(reg prometheus.Registerer) *Metrics {
m := &Metrics{
Requests: prometheus.NewCounterVec(prometheus.CounterOpts{
Name: "http_requests_total",
Help: "HTTP requests by status code, method and route.",
}, []string{"code", "method", "route"}),
Duration: prometheus.NewHistogramVec(prometheus.HistogramOpts{
Name: "http_request_duration_seconds",
Help: "HTTP request latency by status code, method and route.",
Buckets: LatencyBuckets,
}, []string{"code", "method", "route"}),
}
reg.MustRegister(m.Requests, m.Duration)
return m
}
// Instrument wraps next. promhttp allows only the labels "code" and "method"
// on the partitioned vector, so the route is fixed with MustCurryWith. The
// route must be the pattern ("/orders"), never the raw path ("/orders/42"),
// otherwise cardinality explodes.
func (m *Metrics) Instrument(route string, next http.Handler) http.Handler {
l := prometheus.Labels{"route": route}
h := promhttp.InstrumentHandlerDuration(m.Duration.MustCurryWith(l), next)
return promhttp.InstrumentHandlerCounter(m.Requests.MustCurryWith(l), h)
}
// Recover turns a panic into a 500 BEFORE the instrumentation sees it.
// promhttp reports nothing when the wrapped handler panics, so a panic would
// be invisible to the SLI: place Recover INSIDE Instrument.
func Recover(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if v := recover(); v != nil {
http.Error(w, fmt.Sprint("internal error: ", v), http.StatusInternalServerError)
}
}()
next.ServeHTTP(w, r)
})
}
// Faults is a fault-injection knob for the lab.
type Faults struct {
ErrorRate float64 // share of requests that fail with 503
SlowRate float64 // share of requests that get an extra delay
SlowBy time.Duration // the extra delay
}
// Orders is the business handler under measurement.
func Orders(f *Faults, rnd *rand.Rand) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if f.SlowRate > 0 && rnd.Float64() < f.SlowRate {
time.Sleep(f.SlowBy)
}
if f.ErrorRate > 0 && rnd.Float64() < f.ErrorRate {
http.Error(w, "injected failure", http.StatusServiceUnavailable)
return
}
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(`{"orders":[]}`))
})
}The command that serves it and exposes /metrics:
// Command api serves /orders with SLI instrumentation and exposes /metrics.
//
// go run ./cmd/api # :8080
// curl -s localhost:8080/orders
// curl -s localhost:8080/metrics | grep http_request
package main
import (
"log"
"math/rand"
"net/http"
"os"
"strconv"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"academy/sla-slo-sli-error-budgets/service"
)
func main() {
reg := prometheus.NewRegistry()
reg.MustRegister(prometheus.NewGoCollector(), prometheus.NewProcessCollector(prometheus.ProcessCollectorOpts{}))
m := service.NewMetrics(reg)
faults := &service.Faults{}
if v, err := strconv.ParseFloat(os.Getenv("ERROR_RATE"), 64); err == nil {
faults.ErrorRate = v
}
rnd := rand.New(rand.NewSource(time.Now().UnixNano()))
mux := http.NewServeMux()
mux.Handle("GET /orders", m.Instrument("/orders", service.Recover(service.Orders(faults, rnd))))
// Health endpoint: used by the load balancer, deliberately NOT counted in the SLI.
mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) })
mux.Handle("GET /metrics", promhttp.HandlerFor(reg, promhttp.HandlerOpts{}))
srv := &http.Server{Addr: ":8080", Handler: mux, ReadHeaderTimeout: 5 * time.Second}
log.Fatal(srv.ListenAndServe())
}The arithmetic as a tested package (nines, burn rate, serial and parallel):
// Package budget holds the arithmetic behind SLOs: allowed downtime,
// error budget, burn rate, time to exhaustion and composite availability.
package budget
import (
"fmt"
"time"
)
// Window is the SLO compliance window.
type Window time.Duration
const (
Day Window = Window(24 * time.Hour)
Week Window = 7 * Day
Days4 Window = 28 * Day // the Workbook's "four-week rolling window"
Days30 Window = 30 * Day
Year Window = 365 * Day
)
// AllowedDowntime is how long the service may be completely down inside the
// window and still meet an availability SLO (0.999 means 99.9%).
func AllowedDowntime(slo float64, w Window) time.Duration {
return time.Duration(float64(w) * (1 - slo))
}
// ErrorBudget is the allowed fraction of bad events: 100% minus the SLO.
func ErrorBudget(slo float64) float64 { return 1 - slo }
// BurnRate is how fast the budget is consumed relative to the SLO.
// A burn rate of 1 uses exactly the whole budget at the end of the window.
func BurnRate(errorRatio, slo float64) float64 {
b := ErrorBudget(slo)
if b <= 0 {
return 0
}
return errorRatio / b
}
// TimeToExhaustion is how long a constant burn rate needs to spend the whole
// budget of a window that is still untouched.
func TimeToExhaustion(burnRate float64, w Window) time.Duration {
if burnRate <= 0 {
return 0
}
return time.Duration(float64(w) / burnRate)
}
// BudgetSpent is the fraction of the window budget consumed when a burn rate
// is held for the given duration (alert window).
func BudgetSpent(burnRate float64, held time.Duration, w Window) float64 {
return burnRate * float64(held) / float64(w)
}
// BurnRateForSpend derives the burn rate that spends the given share of the
// budget inside the alert window. 2% in 1 h of a 30-day window gives 14.4.
func BurnRateForSpend(share float64, alert time.Duration, w Window) float64 {
return share * float64(w) / float64(alert)
}
// Serial is the availability of components that must ALL work.
func Serial(a ...float64) float64 {
p := 1.0
for _, x := range a {
p *= x
}
return p
}
// Parallel is the availability of redundant components where ANY one is
// enough, assuming independent failures.
func Parallel(a ...float64) float64 {
fail := 1.0
for _, x := range a {
fail *= 1 - x
}
return 1 - fail
}
// Pretty renders a duration the way a runbook would.
func Pretty(d time.Duration) string {
switch {
case d >= 48*time.Hour:
return fmt.Sprintf("%.1f days", d.Hours()/24)
case d >= time.Hour:
return fmt.Sprintf("%.1f h", d.Hours())
case d >= time.Minute:
return fmt.Sprintf("%.1f min", d.Minutes())
default:
return fmt.Sprintf("%.1f s", d.Seconds())
}
}The Go angle
| Option | What it gives | Limit |
|---|---|---|
promhttp handler wrappers | Counter, histogram and in-flight gauge middleware, /metrics handler | Only code and method partition labels; a panicking handler reports nothing; wide histograms are costly |
prometheus.NewHistogramVec with chosen buckets | A bucket boundary exactly at the SLO threshold | Changing buckets later means changing code and handling mixed layouts |
| Native histograms (Prometheus) | Dynamic exponential buckets, change the threshold without redeploying | Interpolated, newer feature; check your Prometheus version and client support |
| OpenTelemetry metrics SDK | Counter, UpDownCounter, Gauge, Histogram instruments, Views to change aggregation, vendor-neutral export | More moving parts; same SLI maths |
expvar (standard library) | Counters as JSON on /debug/vars with no dependency | No histogram type, no labels, no Prometheus text format: demo or internal use |
For the expvar option see expvarsli/main.go (below). OpenTelemetry's metrics concepts: a Meter creates instruments; the instrument kinds are Counter, Asynchronous Counter, UpDownCounter, Asynchronous UpDownCounter, Gauge, Asynchronous Gauge and Histogram (OpenTelemetry's description: "A client-side aggregation of values, such as request latencies"); Views customise the output (for example which attributes to keep). Avoid high-cardinality attributes such as the full URL path.
// Command expvarsli is the standard-library-only option: expvar counters
// served as JSON on /debug/vars. Enough for a demo or an internal tool;
// production SLOs normally use Prometheus histograms (see ../cmd/api).
package main
import (
"expvar"
"log"
"net/http"
"time"
)
var (
requests = expvar.NewMap("requests") // keys: "total", "5xx"
slowMs = expvar.NewInt("slow_over_300ms")
)
type statusWriter struct {
http.ResponseWriter
code int
}
func (w *statusWriter) WriteHeader(c int) { w.code = c; w.ResponseWriter.WriteHeader(c) }
func measure(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
sw := &statusWriter{ResponseWriter: w, code: http.StatusOK}
start := time.Now()
next.ServeHTTP(sw, r)
requests.Add("total", 1)
if sw.code >= 500 {
requests.Add("5xx", 1)
}
if time.Since(start) > 300*time.Millisecond {
slowMs.Add(1)
}
})
}
func main() {
mux := http.NewServeMux()
mux.Handle("GET /orders", measure(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write([]byte("ok"))
})))
mux.Handle("GET /debug/vars", expvar.Handler())
log.Fatal(http.ListenAndServe(":8081", mux))
}Laravel
Example: terminable middleware, /metrics and the health route
Laravel 13 does not ship Prometheus metrics. The pieces below use promphp/prometheus_client_php (its README: client-side aggregation in Redis or APCu, five adapters: Redis, Predis, APC, APCng, in-memory; PushGateway support was removed in 2.0.0) and a terminable middleware, which Laravel calls after the response is sent when the server is FastCGI.
<?php
declare(strict_types=1);
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Laravel\Pulse\Facades\Pulse;
use Prometheus\CollectorRegistry;
use Prometheus\Histogram;
use Symfony\Component\HttpFoundation\Response;
/**
* Terminable middleware that records the two SLI instruments of the chapter:
* a request counter and a latency histogram, labelled code / method / route.
*
* Registered as a singleton (see AppServiceProvider) so handle() and
* terminate() share one instance, as the Laravel middleware docs describe.
*/
final class RecordSli
{
/** Same boundaries as the Go service; 0.3 is the SLO threshold. */
public const BUCKETS = [0.01, 0.025, 0.05, 0.1, 0.2, 0.3, 0.5, 1, 2.5, 5];
private float $startedAt;
public function __construct(private readonly CollectorRegistry $registry)
{
}
public function handle(Request $request, Closure $next): Response
{
$this->startedAt = hrtime(true) / 1e9;
return $next($request);
}
public function terminate(Request $request, Response $response): void
{
$route = $request->route();
// Route PATTERN ("orders/{order}"), never the raw path: cardinality.
$pattern = $route?->uri() ?? 'unmatched';
if (in_array($pattern, ['metrics', 'up'], true)) {
return; // probes and the scrape itself are not user traffic
}
$labels = [(string) $response->getStatusCode(), $request->getMethod(), '/'.$pattern];
$seconds = (hrtime(true) / 1e9) - $this->startedAt;
$this->registry
->getOrRegisterCounter('app', 'http_requests_total', 'HTTP requests', ['code', 'method', 'route'])
->inc($labels);
/** @var Histogram $h */
$h = $this->registry->getOrRegisterHistogram(
'app', 'http_request_duration_seconds', 'HTTP request latency',
['code', 'method', 'route'], self::BUCKETS,
);
$h->observe($seconds, $labels);
// Optional: a per-route latency card for humans. Pulse stores aggregates
// in the database; it is a dashboard, not an SLI source.
Pulse::record('sli_request', '/'.$pattern, (int) round($seconds * 1000))->avg()->max()->count();
}
}<?php
declare(strict_types=1);
namespace App\Http\Controllers;
use Illuminate\Http\Response;
use Prometheus\CollectorRegistry;
use Prometheus\RenderTextFormat;
/** GET /metrics: Prometheus text exposition. Protect it (network policy or auth) in production. */
final class MetricsController
{
public function __invoke(CollectorRegistry $registry): Response
{
$text = (new RenderTextFormat())->render($registry->getMetricFamilySamples());
return new Response($text, 200, ['Content-Type' => RenderTextFormat::MIME_TYPE]);
}
}<?php
declare(strict_types=1);
use App\Http\Controllers\MetricsController;
use App\Http\Middleware\RecordSli;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Support\Facades\Route;
// bootstrap/app.php
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.php',
api: __DIR__.'/../routes/api.php',
commands: __DIR__.'/../routes/console.php',
health: '/up', // 200 if the app booted, 500 otherwise
then: function (): void {
Route::get('/metrics', MetricsController::class);
},
)
->withMiddleware(function (Middleware $middleware): void {
// Global: counts web AND api requests, including 404s that never reach a controller.
$middleware->append(RecordSli::class);
})
->create();<?php
declare(strict_types=1);
namespace App\Providers;
use App\Http\Middleware\RecordSli;
use Illuminate\Foundation\Events\DiagnosingHealth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\ServiceProvider;
use Prometheus\CollectorRegistry;
use Prometheus\Storage\APCng;
final class AppServiceProvider extends ServiceProvider
{
public function register(): void
{
// Client-side aggregation must outlive one request, so use APCu (or the
// Redis adapter). The InMemory adapter would reset on every PHP-FPM request.
$this->app->singleton(CollectorRegistry::class, fn () => new CollectorRegistry(new APCng()));
// One instance for handle() and terminate().
$this->app->singleton(RecordSli::class);
}
public function boot(): void
{
// The built-in health route (/up) dispatches DiagnosingHealth.
// Throwing here turns the 200 into a 500: the load balancer then drains this node.
Event::listen(DiagnosingHealth::class, function (): void {
DB::select('select 1');
});
}
}The Laravel angle
| Piece | What the docs say | Use for SLOs |
|---|---|---|
Health route /up | Served at /up, returns 200 if the application booted without exceptions, otherwise 500. Configure with withRouting(health: ...). The DiagnosingHealth event fires on each hit, and a listener may throw to fail the check | Load balancer and Kubernetes probes; exclude it from the SLI |
| Laravel Pulse | A dashboard with recorders for requests, slow requests, queues, exceptions, slow queries; default slow threshold is 1,000 ms; entries stored in the database or ingested via Redis (PULSE_INGEST_DRIVER=redis, then pulse:work); pulse:check for the servers recorder; Pulse::record('type', 'key', value)->avg()->max()->count() for custom entries | Human triage ("which route is slow"). It records slow requests above a threshold, not good and total counts, so it is not an SLI source |
| Terminable middleware | terminate($request, $response) runs after the response is sent under FastCGI; a fresh instance is resolved unless registered as a singleton | Timing without delaying the response |
| Logging | Channels and context (Log::withContext) | Structured request logs for log-based SLIs and exemplars |
| Prometheus client | promphp/prometheus_client_php with APCu or Redis storage; in-memory resets every request under PHP-FPM | The real SLI instruments |
| StatsD | A UDP line protocol: a counter line is the name, a colon, the value and the type c; a timing line ends in the type ms (the separator between value and type is a pipe character) | When an agent already exists (Telegraf, Datadog agent, statsd) |
A minimal UDP StatsD sender and the SLA credit calculator:
<?php
declare(strict_types=1);
namespace App\Support;
/**
* Minimal StatsD client over UDP (fire and forget). Wire format from the StatsD
* docs: "name:value|c" for counters and "name:value|ms" for timings.
* Use it when the platform already runs a StatsD/Telegraf/Datadog agent.
*/
final class StatsdTimer
{
/** @var resource|null */
private $socket = null;
public function __construct(private readonly string $host = '127.0.0.1', private readonly int $port = 8125)
{
}
public function timing(string $name, float $milliseconds): void
{
$this->send(sprintf('%s:%.1f|ms', $name, $milliseconds));
}
public function increment(string $name): void
{
$this->send($name.':1|c');
}
private function send(string $line): void
{
$this->socket ??= @stream_socket_client("udp://{$this->host}:{$this->port}", $errno, $errstr, 0.1) ?: null;
if ($this->socket !== null) {
@fwrite($this->socket, $line); // metrics must never break the request
}
}
}<?php
declare(strict_types=1);
namespace App\Billing;
/** Maps a monthly uptime percentage to a service-credit percentage (tiers as in a typical cloud SLA). */
final class SlaCreditCalculator
{
/** @param list<array{from: float, credit: int}> $tiers sorted by "from" descending */
public function __construct(private readonly array $tiers = [
['from' => 99.99, 'credit' => 0], // target met: no credit
['from' => 99.0, 'credit' => 10],
['from' => 95.0, 'credit' => 30],
['from' => 0.0, 'credit' => 100],
]) {
}
public function uptimePercent(int $unavailableMinutes, int $minutesInMonth): float
{
return 100 - 100 * $unavailableMinutes / $minutesInMonth;
}
public function creditPercent(float $uptimePercent): int
{
foreach ($this->tiers as $tier) {
if ($uptimePercent >= $tier['from']) {
return $tier['credit'];
}
}
return 100;
}
}Two honesty notes. First, the middleware measures time inside PHP: queueing in nginx or the FPM pool, and requests rejected before PHP starts, are invisible, so the load balancer remains the better place for the availability SLI. Second, an uncaught exception still produces a 500 response through the exception handler and reaches terminate, but a PHP fatal or an OOM kill does not; those are exactly the failures a load-balancer SLI catches.
Solving the classic problems
"We have metrics but no SLO"
| Step | Action | Output |
|---|---|---|
| 1 | List the critical user journeys | Three to five journeys |
| 2 | Pick one availability and one latency SLI per journey, as good/valid ratios | SLI specifications |
| 3 | Measure at the load balancer first | SLI implementations |
| 4 | Compute the last 28 days, set the target slightly below what users already tolerate, never at 100% | A first SLO |
| 5 | Agree the error budget policy with product | A signed document |
| 6 | Add burn-rate alerts, remove cause-based alerts that nobody acts on | Quieter on-call |
The SQL for steps 3 to 4 (and the credit lookup) lives in the snippet:
-- PostgreSQL. Reviewed, not executed against a live database.
-- Input: one row per request (or per load-balancer log line).
CREATE TABLE IF NOT EXISTS request_log (
ts timestamptz NOT NULL,
route text NOT NULL, -- route PATTERN, e.g. '/orders'
status int NOT NULL,
duration_ms int NOT NULL
);
CREATE INDEX IF NOT EXISTS request_log_route_ts ON request_log (route, ts);
-- 1. Request-based availability SLI and latency SLI for the last 28 days.
-- "Valid" events exclude client errors (4xx): the caller's mistake is not our outage.
-- Latency SLI counts only successful requests, so slow errors are not double counted.
SELECT
count(*) FILTER (WHERE status < 500) AS good_availability,
count(*) AS valid_requests,
round(100.0 * count(*) FILTER (WHERE status < 500) / count(*), 4) AS availability_sli_pct,
round(100.0 * count(*) FILTER (WHERE status < 500 AND duration_ms <= 300)
/ NULLIF(count(*) FILTER (WHERE status < 500), 0), 4) AS latency_sli_pct
FROM request_log
WHERE route = '/orders'
AND status NOT BETWEEN 400 AND 499
AND ts >= now() - interval '28 days';
-- 2. Window-based SLI: a minute is "good" when at least 99% of its requests succeeded.
-- SLI = good minutes / minutes that had traffic.
WITH per_minute AS (
SELECT date_trunc('minute', ts) AS minute,
count(*) FILTER (WHERE status < 500)::float / count(*) AS success_ratio
FROM request_log
WHERE route = '/orders' AND ts >= now() - interval '28 days'
GROUP BY 1
)
SELECT count(*) FILTER (WHERE success_ratio >= 0.99) AS good_minutes,
count(*) AS minutes_with_traffic,
round(100.0 * count(*) FILTER (WHERE success_ratio >= 0.99) / count(*), 4) AS window_sli_pct
FROM per_minute;
-- 3. Error budget report for a 99.9% SLO: spent, remaining, and burn rate over the last hour.
WITH w AS (
SELECT count(*) FILTER (WHERE status >= 500) AS bad,
count(*) AS total
FROM request_log
WHERE route = '/orders' AND ts >= now() - interval '28 days'
), h AS (
SELECT count(*) FILTER (WHERE status >= 500)::float / NULLIF(count(*), 0) AS err_1h
FROM request_log
WHERE route = '/orders' AND ts >= now() - interval '1 hour'
)
SELECT w.bad,
round((0.001 * w.total)::numeric, 1) AS budget_in_requests,
round((100.0 * w.bad / NULLIF(0.001 * w.total, 0))::numeric, 1) AS budget_spent_pct,
round((h.err_1h / 0.001)::numeric, 2) AS burn_rate_1h
FROM w, h;
-- 4. SLA credit: map a monthly uptime percentage to a credit tier (AWS EC2 Region-Level tiers).
CREATE TABLE IF NOT EXISTS sla_credit_tier (
uptime_from numeric NOT NULL, -- inclusive lower bound
uptime_to numeric NOT NULL, -- exclusive upper bound
credit_pct int NOT NULL
);
INSERT INTO sla_credit_tier VALUES (99.0, 99.99, 10), (95.0, 99.0, 30), (0, 95.0, 100);
-- Monthly uptime: 100% minus the share of minutes in Unavailability (probe-based).
WITH month AS (
SELECT 43200::numeric AS minutes_in_month, -- 30 days
62::numeric AS unavailable_minutes
)
SELECT round(100 - 100 * unavailable_minutes / minutes_in_month, 3) AS uptime_pct,
(SELECT credit_pct FROM sla_credit_tier t
WHERE 100 - 100 * unavailable_minutes / minutes_in_month >= t.uptime_from
AND 100 - 100 * unavailable_minutes / minutes_in_month < t.uptime_to) AS credit_pct
FROM month;"Our alerts page for blips"
Replace threshold alerts on error rate with the multiwindow, multi-burn-rate rules. First the recording rules and then the alert rules:
# SLI recording rules for a request-based availability SLI and a
# latency SLI (share of requests under 300 ms).
# Naming follows level:metric:operations. Windows match the alert rules.
groups:
- name: slo-availability
interval: 5s # lab value; use 30s-1m in production
rules:
- record: job:slo_errors_per_request:ratio_rate5m
expr: |
sum by (job) (rate(http_requests_total{route="/orders", code=~"5.."}[5m]))
/
sum by (job) (rate(http_requests_total{route="/orders"}[5m]))
- record: job:slo_errors_per_request:ratio_rate30m
expr: |
sum by (job) (rate(http_requests_total{route="/orders", code=~"5.."}[30m]))
/
sum by (job) (rate(http_requests_total{route="/orders"}[30m]))
- record: job:slo_errors_per_request:ratio_rate1h
expr: |
sum by (job) (rate(http_requests_total{route="/orders", code=~"5.."}[1h]))
/
sum by (job) (rate(http_requests_total{route="/orders"}[1h]))
- record: job:slo_errors_per_request:ratio_rate2h
expr: |
sum by (job) (rate(http_requests_total{route="/orders", code=~"5.."}[2h]))
/
sum by (job) (rate(http_requests_total{route="/orders"}[2h]))
- record: job:slo_errors_per_request:ratio_rate6h
expr: |
sum by (job) (rate(http_requests_total{route="/orders", code=~"5.."}[6h]))
/
sum by (job) (rate(http_requests_total{route="/orders"}[6h]))
- record: job:slo_errors_per_request:ratio_rate1d
expr: |
sum by (job) (rate(http_requests_total{route="/orders", code=~"5.."}[1d]))
/
sum by (job) (rate(http_requests_total{route="/orders"}[1d]))
- record: job:slo_errors_per_request:ratio_rate3d
expr: |
sum by (job) (rate(http_requests_total{route="/orders", code=~"5.."}[3d]))
/
sum by (job) (rate(http_requests_total{route="/orders"}[3d]))
- name: slo-latency
interval: 5s
rules:
# Share of requests slower than 300 ms: 1 - (le="0.3" bucket / count).
# Exact only because a bucket boundary sits at 0.3.
- record: job:slo_slow_per_request:ratio_rate5m
expr: |
1 - (
sum by (job) (rate(http_request_duration_seconds_bucket{route="/orders", le="0.3"}[5m]))
/
sum by (job) (rate(http_request_duration_seconds_count{route="/orders"}[5m]))
)
- record: job:slo_slow_per_request:ratio_rate1h
expr: |
1 - (
sum by (job) (rate(http_request_duration_seconds_bucket{route="/orders", le="0.3"}[1h]))
/
sum by (job) (rate(http_request_duration_seconds_count{route="/orders"}[1h]))
)
- name: slo-budget
interval: 1m
rules:
# Remaining error budget of a 99.9% SLO over 28 days, as a fraction (1 = untouched).
- record: job:slo_error_budget_remaining:ratio28d
expr: |
1 - (
(
sum by (job) (increase(http_requests_total{route="/orders", code=~"5.."}[28d]))
/
sum by (job) (increase(http_requests_total{route="/orders"}[28d]))
) / 0.001
)# Multiwindow, multi-burn-rate alerts for a 99.9% availability SLO over 30 days.
# Error budget = 1 - 0.999 = 0.001. Parameters: SRE Workbook, chapter 5, Table 5-8.
# page : 14.4x over 1h AND 5m (2% of budget) | 6x over 6h AND 30m (5%)
# ticket : 3x over 1d AND 2h (10%) | 1x over 3d AND 6h (10%)
groups:
- name: slo-burn-rate
rules:
- alert: OrdersErrorBudgetFastBurn
expr: |
(
job:slo_errors_per_request:ratio_rate1h{job="orders-api"} > (14.4 * 0.001)
and
job:slo_errors_per_request:ratio_rate5m{job="orders-api"} > (14.4 * 0.001)
)
or
(
job:slo_errors_per_request:ratio_rate6h{job="orders-api"} > (6 * 0.001)
and
job:slo_errors_per_request:ratio_rate30m{job="orders-api"} > (6 * 0.001)
)
labels:
severity: page
slo: orders-availability
annotations:
summary: "orders-api burns its 30-day error budget at 6x or faster"
runbook_url: "https://runbooks.example.com/orders/error-budget-fast-burn"
- alert: OrdersErrorBudgetSlowBurn
expr: |
(
job:slo_errors_per_request:ratio_rate1d{job="orders-api"} > (3 * 0.001)
and
job:slo_errors_per_request:ratio_rate2h{job="orders-api"} > (3 * 0.001)
)
or
(
job:slo_errors_per_request:ratio_rate3d{job="orders-api"} > (1 * 0.001)
and
job:slo_errors_per_request:ratio_rate6h{job="orders-api"} > (1 * 0.001)
)
labels:
severity: ticket
slo: orders-availability
annotations:
summary: "orders-api will exhaust its error budget in days if this continues"
runbook_url: "https://runbooks.example.com/orders/error-budget-slow-burn"
# Latency SLO: 99% of requests under 300 ms, budget 0.01. keep_firing_for holds the alert
# for 10 minutes after the condition stops matching, which avoids flapping pages.
- alert: OrdersLatencyBudgetFastBurn
expr: |
job:slo_slow_per_request:ratio_rate1h{job="orders-api"} > (14.4 * 0.01)
and
job:slo_slow_per_request:ratio_rate5m{job="orders-api"} > (14.4 * 0.01)
keep_firing_for: 10m
labels:
severity: page
slo: orders-latency-300ms-99
annotations:
summary: "orders latency SLO (99% under 300 ms) burns its budget at 14.4x or faster"
runbook_url: "https://runbooks.example.com/orders/latency"The rules were checked as YAML but not evaluated by Prometheus (see the lab note). The tooling around this pattern: Sloth ("generates understandable, uniform and reliable Prometheus SLOs", with multi window multi burn alerts, from a simple SLO spec) and Pyrra ("Making SLOs with Prometheus manageable") generate such rules for you; write them by hand once to understand them.
"The budget is always empty"
| Cause | Fix |
|---|---|
| SLO tighter than users need | Loosen it; the SRE book says it is better to start loose and tighten |
| One dependency eats the budget | Soften the hard dependency; give it its own SLO |
| Bad SLI (counts 4xx, load tests, health checks) | Fix "valid events"; the example policy lists miscategorised errors as a reason to work on reliability |
| Deploys cause most errors | Canary, progressive delivery, fast rollback (the example policy's background says changes represent roughly 70% of outages) |
| No capacity headroom | Revisit capacity estimation |
"Nobody acts when the budget is gone"
The policy lacks stakeholders. Run the Workbook's test: if the product manager, the developers and SRE will not all sign the policy, the SLO is not fit for purpose; iterate on the SLI and SLO until all three agree.
"The budget is never touched"
Either the SLO is too loose, or you are over-invested. Tighten the SLO or spend the budget: more frequent releases, chaos tests, risky migrations. For infrastructure that users over-depend on, the Chubby approach: meet but do not significantly exceed the SLO, with controlled outages.
Choosing: which SLI, SLO and window
| Situation | SLI | Target and window | Extra technique | Reason |
|---|---|---|---|---|
| Public REST API, B2B | Availability (non-5xx) and latency (under 300 ms) at the LB | 99.9% over 28 days, 99% under 300 ms | Burn-rate alerts, synthetic probe | Contracts follow, easy to measure |
| Checkout and payment | Availability and correctness (no double charge) | 99.95% over 28 days | Idempotency keys, reconciliation job | One failure costs more than many |
| Internal admin tool | Availability, coarse | 99% over a quarter | Ticket-only alerts | Cost of a nine is not justified |
| Search or listing page | Latency and quality (full results) | 99% under 500 ms; 99.5% undegraded | Graded SLOs | The tail drives bounces |
| Nightly batch or ETL | Freshness and coverage | 99% of runs finish before 06:00 | Window-based per run | Users care about "is it there when I need it" |
| Read replica fed dashboards | Freshness | 99% of reads under 10 s behind | Lag metric as SLI | See replication |
| Object or file storage | Durability and availability | A durability number is a design claim, not a measurement; measure read-after-write success | Scrubbing, checksums | Durability is hard to observe directly |
| Message pipeline | Throughput, end-to-end latency, correctness | 95% of messages processed under 30 s | Dead-letter queue as an SLI input | Backlog is the failure signal |
| Low-traffic service | Availability with synthetic traffic | 99% over 28 days | Larger windows, group services | Ratios are noisy |
| Selling an SLA | Same SLIs, window-based | SLA 99.9% monthly, internal SLO 99.95% | Credit exposure budget | Gap is your safety margin |
In architecture: from a single process to a distributed system
Monolith: one process, one database
Everyday example: a shop with one Laravel app and one PostgreSQL. There is one SLO per user journey, not per class. Availability SLI: load-balancer 5xx ratio on /checkout. Latency SLI: 99% of checkout requests under 800 ms. Dependency math is easy: LB × app × DB in series.
1 user -> LB -> Laravel (php-fpm) -> PostgreSQL
2 SLI: sum(rate(lb_requests_total{route="/checkout", code=~"5.."}[5m])) / sum(rate(lb_requests_total{route="/checkout"}[5m]))
3 SLO: 99.9% over 28 days -> budget 40 minutes of full outage
4 A deploy that restarts php-fpm for 90 s costs about 3.7% of the budget (90 s / 2,419 s)Production example: a single-process service on a single instance can at best promise AWS's instance-level 99.5% (about 3.6 hours a month), so a 99.9% SLO already forces a second instance and a load balancer. That is the first architectural consequence of an SLO.
Modular monolith and multiple databases
Inside one deployable, modules still have their own quality needs, so one SLO per journey (checkout, search) is better than one per module; modules inherit the journey's latency budget, divided between them. A shared database is a shared dependency for every module: its availability multiplies into every journey, and a runaway reporting module can burn the checkout budget (see Modular Monolith, Layered Monolith).
| Module | Budget slice | Technique |
|---|---|---|
| Catalogue (read-heavy) | 30% of the checkout latency budget | Cache, read replica |
| Pricing | 10% | In-process, no I/O |
| Payment | 50% | Timeout and idempotency |
| Orders (writes) | 10% | Single transaction |
Per-module metrics (a module label) diagnose; the SLO stays on the journey.
Microservices: SLOs across a network
Everyday example: the same shop split into gateway, catalogue, orders and payments. Each service gets its own availability and latency SLO, and the user-facing SLO is computed over the critical path.
1 Browser -> API gateway (99.99%) -> orders (99.95%) -> payments (99.9%) -> bank API (3rd party)
2 Serial availability of the hard path: 0.9999 x 0.9995 x 0.999 = 99.84% (about 69 min per 30 days)
3 A 99.9% journey SLO is NOT achievable unless payments is made async, retried, or doubled
4 Latency budget for p99 800 ms: gateway 50 + orders 150 + payments 450 + network 4 x 25 = 750 msRules for services:
| Rule | Why |
|---|---|
| One SLO per service, plus journey SLOs on the critical path | Service SLOs tell who owns a failure; journey SLOs tell what users feel |
| Each hop gets a share of the latency budget | Budgets across hops add up; the tail of a fan-out is worse than any single call |
| Timeouts and retries must fit the budget (a retry adds latency and load) | See Service Communication |
| Count only valid events at each boundary | A 4xx from a bad client must not burn the callee's budget |
| Dependencies need written SLOs and alerts on their SLIs | The Chubby lesson |
| Gateway and mesh are the cheapest place to measure edge SLIs | See API Gateway, BFF & Service Mesh |
| Many services, many SLOs: use templates or generators | Hand-written rules do not scale (Sloth, Pyrra, OpenSLO-style specs) |
Tail amplification: if a page fans out to 100 calls and each call is under its p99 target 99% of the time, then 1 − 0.99^100 ≈ 63% of page loads include at least one slow call. A per-service p99 target is therefore far from a page-level p99 target; compute the budget on the page.
Distributed data: replicas, caches and multi-region
| Component | SLI that matters | Trap |
|---|---|---|
| Read replica | Freshness (replica lag) | A replica can be 100% available and 20 minutes stale; measure lag, not ping |
| Cache | Hit ratio and freshness, plus the origin's SLI | Cache hides origin failures until it expires; the SLI of the page is still the page |
| Message queue | End-to-end age of the oldest message, throughput | Producers succeed while consumers fall behind |
| Multi-region active-passive | Recovery time and data loss | Failover time counts as downtime in the SLO |
| Multi-region active-active | Availability per region and globally | Correlated failures (shared control plane, bad deploy) break the parallel formula |
| Object storage | Durability, availability | Durability is a design number, rarely a measured one |
The parallel formula assumes independence. A cell or region design (isolate blast radius, deploy to one cell at a time) is how you earn independence. See Replication, Read Replicas & Failover and Delivery Guarantees for the freshness and processing SLIs.
Scaling path: 1×, 10×, 100×
| Scale | SLO practice | What changes |
|---|---|---|
| 1× (one team, one service) | One availability and one latency SLO per journey, LB metrics, a wiki page and a weekly look | Few alerts, manual reviews |
| 10× (several teams) | SLOs per service and journey, burn-rate alerts via recording rules, error budget policy signed per team | Standard SLI templates, a shared dashboard |
| 100× (a platform with many services) | SLOs as code (generated rules), dependency graph with budget propagation, exemplars linking metrics to traces, an SLO review in architecture sign-off | Governance: who may change a target; automatic checks that new services ship SLOs |
Capacity ties in directly: an SLO fixes the headroom you must plan for. Latency grows steeply near saturation (queuing), so a 99% latency SLO needs more spare capacity than a 99% availability SLO; use capacity estimation with a target utilisation well below 100%.
Runbooks and incident links. Every page-level alert must carry a runbook_url and an slo label. The runbook answers four questions: which SLI is burning, what changed recently, how to mitigate (roll back, shed load, fail over), and how to confirm recovery. After an incident, record how much budget it consumed; the Workbook suggests using the share of budget consumed to find the incidents that merit a closer look, and the example policy makes a postmortem mandatory above 20%.
Reporting and dashboards. One dashboard per service with: current SLI, SLO line, remaining budget (a stat panel), a 28-day burn chart, the fast-burn and slow-burn alert states, and the top contributors (route, status, dependency). Send a weekly summary for prioritisation and a quarterly one for planning.
Lab: instrument an endpoint, fault-inject, compute the SLI, fire an alert
What was actually run. Docker was not available when this chapter was written and a promtool binary could not be obtained, so the Prometheus rules were checked as YAML but not evaluated. What was run for real: the Go module (gofmt, go vet, go test) and the lab program, which reads the SLI back from the Prometheus registry and evaluates the same multiwindow condition on a virtual clock. The Laravel code was reviewed, not run (php is not installed here).
Part 1: the arithmetic.
cd docs/snippets/architecture/sla-slo-sli-error-budgets/go
go test ./... # budget package: expected ok
go run ./nines # prints the nines table, burn-rate table, composite examplesExpected: the tables of this page (for example 99.900% 1.4 min 40.3 min 43.2 min 8.8 h, and 3 services in series, each 99.9%: 99.7003%).
// Command nines prints the "nines" table, the burn-rate table and the
// composite availability examples used in the chapter.
package main
import (
"fmt"
"time"
"academy/sla-slo-sli-error-budgets/budget"
)
func main() {
fmt.Println("== Allowed downtime per window ==")
fmt.Printf("%-9s %-12s %-12s %-12s %-12s\n", "SLO", "day", "28 days", "30 days", "365 days")
for _, slo := range []float64{0.99, 0.995, 0.999, 0.9995, 0.9999, 0.99999} {
fmt.Printf("%-9s %-12s %-12s %-12s %-12s\n",
fmt.Sprintf("%.3f%%", slo*100),
budget.Pretty(budget.AllowedDowntime(slo, budget.Day)),
budget.Pretty(budget.AllowedDowntime(slo, budget.Days4)),
budget.Pretty(budget.AllowedDowntime(slo, budget.Days30)),
budget.Pretty(budget.AllowedDowntime(slo, budget.Year)))
}
fmt.Println("\n== Burn rate for a 99.9% SLO, 30-day window ==")
fmt.Printf("%-10s %-12s %-16s\n", "burn rate", "error ratio", "time to exhaust")
for _, br := range []float64{1, 2, 6, 10, 14.4, 36, 1000} {
ratio := br * budget.ErrorBudget(0.999)
fmt.Printf("%-10v %-12s %-16s\n", br, fmt.Sprintf("%.2f%%", ratio*100),
budget.Pretty(budget.TimeToExhaustion(br, budget.Days30)))
}
fmt.Println("\n== Alert parameters (Workbook Table 5-8 derivation) ==")
type row struct {
share float64
long, short time.Duration
}
for _, r := range []row{
{0.02, time.Hour, 5 * time.Minute},
{0.05, 6 * time.Hour, 30 * time.Minute},
{0.10, 72 * time.Hour, 6 * time.Hour},
} {
fmt.Printf("spend %2.0f%% in %-5v -> burn rate %-5.1f (short window %v)\n",
r.share*100, r.long, budget.BurnRateForSpend(r.share, r.long, budget.Days30), r.short)
}
fmt.Println("\n== Composite availability ==")
fmt.Printf("3 services in series, each 99.9%%: %.4f%%\n", budget.Serial(0.999, 0.999, 0.999)*100)
fmt.Printf("5 services in series, each 99.9%%: %.4f%%\n", budget.Serial(0.999, 0.999, 0.999, 0.999, 0.999)*100)
fmt.Printf("2 replicas in parallel, each 99%%: %.4f%%\n", budget.Parallel(0.99, 0.99)*100)
fmt.Printf("LB 99.99%% -> app (2 x 99.5%% parallel) -> db 99.95%%: %.4f%%\n",
budget.Serial(0.9999, budget.Parallel(0.995, 0.995), 0.9995)*100)
}Part 2: fault-inject, compute the SLI, see the alert condition.
go run ./labActual output of that run (600 requests per virtual minute, 10% failures from minute 60 to 75, SLO 99.9%):
min faults err 5m err 1h burn 1h page page (1h only)
10 false 0.00% 0.00% 0.0 false false
60 false 0.00% 0.00% 0.0 false false
-> minute 69: multiwindow page FIRES
-> minute 69: 1h-only page FIRES
70 true 10.83% 1.75% 17.5 true true
-> minute 80: multiwindow page RESOLVES
80 false 0.00% 2.59% 25.9 false true
120 false 0.00% 2.59% 25.9 false true
-> minute 127: 1h-only page RESOLVES
140 false 0.00% 0.00% 0.0 false false
Availability SLI over 140 min: 98.8917% (931 bad of 84000)
Share of this run's error budget spent: 1108% (budget = 84 bad requests)
Latency SLI (le=0.3 bucket / count): 100.0000%(Rows for minutes 20 to 50 and 90 to 110 are omitted here; they are all zero or constant.) Read it like this: an eleven-minute multiwindow page versus a fifty-eight-minute single-window page for the same incident; the whole 140-minute run spent far more than its own budget because it is only 140 minutes long; a 15-minute 10% incident is a major event for a 99.9% SLO.
// Command lab drives the instrumented handler through a fault-injected
// window on a virtual clock (1 loop iteration = 1 minute), reads the SLI
// back from the Prometheus registry and evaluates the multiwindow,
// multi-burn-rate page condition the same way the Prometheus rule does.
//
// This is an emulation of rate() over snapshots, NOT a Prometheus run.
package main
import (
"fmt"
"math/rand"
"net/http/httptest"
"strings"
"github.com/prometheus/client_golang/prometheus"
"academy/sla-slo-sli-error-budgets/budget"
"academy/sla-slo-sli-error-budgets/service"
)
const (
slo = 0.999
minutes = 140
requestsPerMin = 600
faultFrom = 60 // 0-based minute, after one healthy hour
faultTo = 74 // inclusive
faultRate = 0.10
pageBurn = 14.4
)
type snap struct{ total, bad float64 }
func main() {
reg := prometheus.NewRegistry()
m := service.NewMetrics(reg)
faults := &service.Faults{}
rnd := rand.New(rand.NewSource(42))
h := m.Instrument("/orders", service.Recover(service.Orders(faults, rnd)))
snaps := []snap{{}} // snaps[i] = cumulative counters after i minutes
longFiring, multiFiring := false, false
fmt.Printf("%-4s %-8s %-9s %-9s %-9s %-7s %s\n", "min", "faults", "err 5m", "err 1h", "burn 1h", "page", "page (1h only)")
for t := 1; t <= minutes; t++ {
faults.ErrorRate = 0
if t-1 >= faultFrom && t-1 <= faultTo {
faults.ErrorRate = faultRate
}
for i := 0; i < requestsPerMin; i++ {
h.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("GET", "/orders", nil))
}
snaps = append(snaps, read(reg))
e5, e60 := ratio(snaps, 5), ratio(snaps, 60)
long := budget.BurnRate(e60, slo) > pageBurn
short := budget.BurnRate(e5, slo) > pageBurn
multi := long && short
if multi != multiFiring {
fmt.Printf(" -> minute %d: multiwindow page %s\n", t, onOff(multi))
multiFiring = multi
}
if long != longFiring {
fmt.Printf(" -> minute %d: 1h-only page %s\n", t, onOff(long))
longFiring = long
}
if t%10 == 0 || t == minutes {
fmt.Printf("%-4d %-8v %-9s %-9s %-9.1f %-7v %v\n", t,
faults.ErrorRate > 0, pct(e5), pct(e60), budget.BurnRate(e60, slo), multi, long)
}
}
last := snaps[len(snaps)-1]
avail := 1 - last.bad/last.total
fmt.Printf("\nAvailability SLI over %d min: %.4f%% (%0.f bad of %0.f)\n", minutes, avail*100, last.bad, last.total)
fmt.Printf("Share of this run's error budget spent: %.0f%% (budget = %.0f bad requests)\n",
100*last.bad/(budget.ErrorBudget(slo)*last.total), budget.ErrorBudget(slo)*last.total)
fmt.Printf("Latency SLI (le=0.3 bucket / count): %.4f%%\n", latencySLI(reg)*100)
}
func onOff(b bool) string {
if b {
return "FIRES"
}
return "RESOLVES"
}
func pct(r float64) string { return fmt.Sprintf("%.2f%%", r*100) }
// ratio is increase(bad)/increase(total) over the last w snapshots.
func ratio(s []snap, w int) float64 {
last := s[len(s)-1]
first := s[0]
if len(s)-1 > w {
first = s[len(s)-1-w]
}
if last.total == first.total {
return 0
}
return (last.bad - first.bad) / (last.total - first.total)
}
// read sums http_requests_total, counting every 5xx as bad.
func read(g prometheus.Gatherer) snap {
var s snap
fams, _ := g.Gather()
for _, f := range fams {
if f.GetName() != "http_requests_total" {
continue
}
for _, mt := range f.GetMetric() {
v := mt.GetCounter().GetValue()
s.total += v
for _, l := range mt.GetLabel() {
if l.GetName() == "code" && strings.HasPrefix(l.GetValue(), "5") {
s.bad += v
}
}
}
}
return s
}
// latencySLI is the share of requests faster than 300 ms, read from the
// cumulative le="0.3" bucket (exact because a bucket boundary sits at 0.3).
func latencySLI(g prometheus.Gatherer) float64 {
var good, total float64
fams, _ := g.Gather()
for _, f := range fams {
if f.GetName() != "http_request_duration_seconds" {
continue
}
for _, mt := range f.GetMetric() {
h := mt.GetHistogram()
total += float64(h.GetSampleCount())
for _, b := range h.GetBucket() {
if b.GetUpperBound() == 0.3 {
good += float64(b.GetCumulativeCount())
}
}
}
}
if total == 0 {
return 1
}
return good / total
}Part 3: against a real Prometheus (not run here).
# terminal 1
ERROR_RATE=0.0 go run ./cmd/api
# terminal 2
cd ../prometheus && docker compose up # loads slo-rules.yml and slo-alerts.yml
# terminal 3: generate traffic, then fail 10% of requests by restarting the API with ERROR_RATE=0.1
for i in $(seq 1 100000); do curl -s localhost:8080/orders > /dev/null; done
# in the Prometheus UI (localhost:9090): Alerts -> OrdersErrorBudgetFastBurn should go pending, then firing
# expected: the recording rule job:slo_errors_per_request:ratio_rate5m is about 0.10 and the page alert fires
# once the 1h ratio crosses 0.0144 (the lab's virtual clock reaches this after about 9 minutes of fault)# Lab Prometheus: scrapes the Go API, loads the SLO rules.
global:
scrape_interval: 5s
evaluation_interval: 5s
rule_files:
- /etc/prometheus/slo-rules.yml
- /etc/prometheus/slo-alerts.yml
scrape_configs:
- job_name: orders-api
static_configs:
- targets: ["host.docker.internal:8080"]# Lab only. Not executed when this chapter was written (Docker daemon was down).
services:
prometheus:
image: prom/prometheus:v3.16.0
ports: ["9090:9090"]
extra_hosts: ["host.docker.internal:host-gateway"]
volumes:
- ./prometheus.yml:/etc/prometheus/prometheus.yml:ro
- ./slo-rules.yml:/etc/prometheus/slo-rules.yml:ro
- ./slo-alerts.yml:/etc/prometheus/slo-alerts.yml:roPart 4: Laravel (reviewed, not run). Install promphp/prometheus_client_php, enable the apcu extension, register RecordSli as above, hit /orders a few times and open /metrics: expect app_http_requests_total{code="200",method="GET",route="/orders"} and the app_http_request_duration_seconds_bucket series including le="0.3". Point the same recording rules at the app_ metric names by changing the metric prefix, or set the client namespace so the names match the Go service.
Common misconceptions
| Belief | Reality |
|---|---|
| "Our SLO is 100%" | Impossible and undesirable; the SRE book says 100% is probably never the right target. It also removes the error budget, so every release becomes a violation |
| "Average latency is a fine SLI" | Averages hide the tail; use a threshold ratio or percentile from histogram buckets |
| "SLA and SLO are the same" | An SLA has contractual consequences; an SLO is internal and tighter |
| "We measure in the app, so we see everything" | A dead process, a full queue or a panic is invisible to the app; measure at the load balancer too |
| "Three 99.9% components give 99.9%" | They give 99.7% in series; each hop in the critical path multiplies |
| "Two replicas make us 99.99%" | Only if failures are independent and failover works; shared database, zone or deploy breaks the math |
| "The error budget is a quota to use up" | It is a limit; unused budget means room to ship faster or a loose SLO |
| "A freeze is a punishment" | The example policy says it is permission to focus on reliability |
| "Page whenever the error rate exceeds the SLO ratio" | Low precision; page on burn rate over long and short windows |
"A for: 1h duration fixes noisy alerts" | Duration does not scale with severity and hurts recall; the Workbook does not recommend it for SLO alerts |
| "Monitoring health checks measure availability" | A /up that returns 200 says the app booted, not that checkout works |
| "More nines is always better" | Users cannot tell beyond their own device and network reliability; cost and slowdown grow |
| "Pulse gives me my SLO" | Pulse records slow requests, not good/total counts; it is a diagnosis dashboard |
Cheat sheet
| Topic | What to remember |
|---|---|
| SLI | good / valid events, 0 to 100%, measured near the user |
| SLO | A target on the SLI over a window, internal, tighter than the SLA |
| SLA | A contract with consequences (credits); looser than the SLO |
| Error budget | 1 - SLO; 99.9% over 30 days is 43.2 minutes |
| Burn rate | error ratio / (1 - SLO); 1 empties the budget exactly at window end |
| Page thresholds | 14.4x over 1 h and 5 m, 6x over 6 h and 30 m (99.9% SLO, 30 days) |
| Ticket thresholds | 3x over 1 d and 2 h, 1x over 3 d and 6 h |
| Short window | About 1/12 of the long window |
| Serial availability | Multiply: 0.999 to the 3rd = 99.7% |
| Parallel availability | 1 - (1-A)(1-B), needs independent failures |
| Windows | Rolling 28 days for users, calendar for contracts and planning |
| Percentiles | Count requests under a threshold from le buckets; never average percentiles |
| Histogram bucket | Put a boundary exactly on the SLO threshold |
| Policy | Written, signed by product, dev and SRE: freeze launches and work on reliability when empty |
| Measure at | Load balancer first, client for freshness and UX, probes for zero traffic |
| Laravel | /up is a boot check, Pulse is a dashboard, Prometheus client is the SLI source |
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 — What single question separates an SLO from an SLA? Must-know
Answer
Answer: "What happens if the target is missed?" If there is no explicit consequence, it is an SLO; an SLA carries consequences, usually financial.
2 — A service has a 99.95% SLO over 30 days. How many minutes of full outage does the budget allow? Must-know
Answer
Answer: 43,200 minutes × 0.0005 = 21.6 minutes.
3 — The error ratio is 0.6% and the SLO is 99.9%. What is the burn rate and how long until a fresh 30-day budget is gone? Important
Answer
Answer: Burn rate 0.6% / 0.1% = 6; 30 days / 6 = 5 days.
4 — Why is a single "error rate over the SLO ratio for 10 minutes" alert a poor design? Must-know
Answer
Answer: Low precision: a 0.1% error rate sustained for 10 minutes would page while spending only about 0.02% of the monthly budget (Workbook, iteration 1).
5 — What do the long and short windows each contribute in a multiwindow alert? Important
Answer
Answer: The long window gives significance (a meaningful share of budget is spent); the short window (about 1/12 of the long one) gives currency (it is still burning) and shortens reset time.
6 — Three services at 99.9% each, in series. What is the availability, and what two tactics help? Must-know
Answer
Answer: About 99.70%. Tactics: remove or soften a hard dependency (cache, default, async) or add independent redundancy in parallel for the weakest part.
7 — Why do you put a histogram bucket boundary at the SLO threshold? Important
Answer
Answer: The share of requests under the threshold is read exactly from the cumulative bucket; otherwise Prometheus interpolates and the estimate depends on bucket layout.
8 — Name two reasons to measure the availability SLI at the load balancer rather than only in the application. Important
Answer
Answer: The application cannot count requests it never received (crashes, full queues, panics that the middleware does not report) and the load balancer already exports status and latency for every request that reached the fleet, closer to the user.
9 — Your payment provider's SLA says 99.9%. Can you promise 99.9% for checkout? Must-know
Answer
Answer: Not if the provider is a hard serial dependency: the result is below 99.9% before your own components are counted. Decouple (queue and retry), add a second provider in parallel, or lower the checkout promise.
10 — What makes an error budget policy effective? Important
Answer
Answer: It is written down and signed by product, developers and SRE before it is needed, with explicit actions (freeze launches, reliability first), exceptions (company-wide outages, out-of-scope traffic) and an escalation path.
11 — Why is Laravel Pulse not an SLI source? Important
Answer
Answer: Pulse records slow requests above a threshold and aggregates for dashboards; an SLI needs the good and valid counts for all requests.
12 — A 99.99% SLO is requested for an internal admin tool. What do you ask first? Must-know
Answer
Answer: What users would notice and what a nine costs; the SRE book's price-per-nine argument usually shows 99% to 99.9% is enough for internal tools.
Glossary
| Term | One line |
|---|---|
| SLI (Service Level Indicator) | Measured ratio of good events to valid events |
| SLO (Service Level Objective) | Target on an SLI over a window |
| SLA (Service Level Agreement) | Contract with consequences for missing the target |
| Error budget | 1 minus the SLO: the failure you may spend |
| Burn rate | Error ratio divided by the error budget; speed of spending |
| Error budget policy | Agreed actions when the budget is gone |
| Nines | Count of 9s in the availability percentage (99.9% is three nines) |
| Availability | Share of valid requests that succeed, or share of time the service is up |
| Latency SLI | Share of requests faster than a threshold |
| Freshness | Share of data newer than a threshold |
| Correctness | Share of outputs that are right |
| Durability | Share of written data that can still be read |
| Request-based SLI | Counts events |
| Window-based SLI | Counts good time slices (minutes) |
| Rolling window | Window that always looks back a fixed length |
| Calendar window | Window aligned to a month or quarter |
| Percentile (pN) | Value below which N% of observations fall |
| Histogram | Counts observations per bucket; allows aggregation across instances |
Bucket boundary (le) | Cumulative upper bound of a Prometheus histogram bucket |
| Recording rule | Precomputed PromQL expression stored as a series |
| Alerting rule | PromQL condition that fires an alert, with labels and annotations |
| Multiwindow, multi-burn-rate alert | Fires when long and short windows both exceed a burn threshold |
| Precision / recall (alerting) | Share of alerts that were significant / share of significant events alerted |
| Detection time / reset time | Time to alert / time an alert keeps firing after recovery |
| Composite availability | Availability of a system built from parts: serial multiplies, parallel multiplies failures |
| Critical user journey | A task a user cares about, spanning several requests |
| Service credit | Money off a future bill when an SLA is missed |
| Monthly Uptime Percentage | 100% minus the share of the month's minutes the service was unavailable |
| Synthetic probe | An artificial request that checks the service from outside |
/up health route | Laravel's boot check, 200 if the app booted without exceptions |
| Laravel Pulse | First-party dashboard for application usage and performance |
| StatsD | UDP line protocol for counters and timings |
| Runbook | Written steps for responding to an alert |
References
- Beyer, Jones, Petoff, Murphy (eds.), Site Reliability Engineering, chapter 3 "Embracing Risk": https://sre.google/sre-book/embracing-risk/
- Same book, chapter 4 "Service Level Objectives": https://sre.google/sre-book/service-level-objectives/
- The Site Reliability Workbook, chapter 2 "Implementing SLOs": https://sre.google/workbook/implementing-slos/
- Same book, chapter 5 "Alerting on SLOs": https://sre.google/workbook/alerting-on-slos/
- Same book, appendix B "Example Error Budget Policy": https://sre.google/workbook/error-budget-policy/
- Amazon Compute Service Level Agreement (EC2), last updated May 25, 2022: https://aws.amazon.com/compute/sla/
- Google Cloud SQL Service Level Agreement: https://cloud.google.com/sql/sla
- Prometheus, histograms and summaries: https://prometheus.io/docs/practices/histograms/
- Prometheus, recording rules: https://prometheus.io/docs/prometheus/latest/configuration/recording_rules/
- Prometheus, alerting rules: https://prometheus.io/docs/prometheus/latest/configuration/alerting_rules/
- OpenTelemetry, metrics concepts: https://opentelemetry.io/docs/concepts/signals/metrics/
- Laravel 13 Pulse: https://laravel.com/docs/13.x/pulse
- Laravel 13 deployment, the health route: https://laravel.com/docs/13.x/deployment
- Laravel 13 middleware (terminable middleware): https://laravel.com/docs/13.x/middleware
- Laravel 13 logging: https://laravel.com/docs/13.x/logging
promphp/prometheus_client_php: https://github.com/PromPHP/prometheus_client_php- StatsD metric types: https://github.com/statsd/statsd/blob/master/docs/metric_types.md
- Go
expvarpackage: https://pkg.go.dev/expvar (documentation read locally withgo doc expvar) client_golangpromhttp: https://pkg.go.dev/github.com/prometheus/client_golang/prometheus/promhttp (documentation read locally withgo docfor version 1.22.0)- Sloth: https://github.com/slok/sloth; Pyrra: https://github.com/pyrra-dev/pyrra