Skip to content

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 forGo to
The four terms and the nines table in a minuteEverything in one minute
Why we write targets down at allWhy it exists
Where the vocabulary comes fromWhere it comes from
SLI, SLO, SLA, error budget, burn rate, one block eachThe concept catalogue
Which SLI to choose for which kind of serviceChoosing SLIs
Request-based versus window-based, and where to measureRequest vs window, Where to measure
99.9 versus 99.99 in minutes per yearThe nines
Serial and parallel availability mathComposite availability
Freeze features when the budget is goneError budget policy
Page on burn rate with Prometheus rulesAlerting on burn rate
Cloud SLA examples and creditsSLAs and credits
Go and Laravel instrumentationGo, Laravel
Monolith, microservices, latency budgetsIn architecture
A fault-injection lab with an alertLab
Wrong beliefs, cheat sheet, self-check, termsMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

The four terms. Every row is unpacked in the concept catalogue.

TermIn plain wordsTiny exampleWhat goes wrong without it
SLI (Service Level Indicator)A measured number about user experience, usually good events divided by valid events99.93% of /orders requests returned non-5xx in the last 28 daysEveryone 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 budget100% minus the SLO: the failure you may spend0.1% of requests, about 43 minutes of full outage in 30 daysReliability and feature speed fight with opinions instead of data
Burn rateHow fast the budget is spent relative to the SLO14.4 means the 30-day budget is gone in about 2 daysAlerts fire on blips or notice real incidents too late
Error budget policyThe agreed consequences of an empty budgetFreeze launches until back within SLOThe budget is a number nobody acts on

SLI, SLO, SLA in one table.

QuestionSLISLOSLA
What is itA measurementA target on the measurementA contract about the target
Examplegood / valid requestsat least 99.9% over 28 days99.9% monthly or a 10% credit
Who owns itThe team that runs the serviceProduct and engineering togetherBusiness and legal
Consequence of missingNone by itselfError budget policy (internal)Money, credits, contract terms (external)
StrictnessWhatever is trueTighter than the SLALooser than the SLO on purpose

The nines (availability over a 30-day month and a year), computed by the code in Go:

SLOError budgetPer dayPer 28 daysPer 30 daysPer year
99%1%14.4 min6.7 h7.2 h3.6 days
99.5%0.5%7.2 min3.4 h3.6 h43.8 h
99.9%0.1%1.4 min40.3 min43.2 min8.8 h
99.95%0.05%43.2 s20.2 min21.6 min4.4 h
99.99%0.01%8.6 s4.0 min4.3 min52.6 min
99.999%0.001%0.9 s24.2 s25.9 s5.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 rateError ratioTime to empty the budget
10.10%30 days
20.20%15 days
60.60%5 days
101.00%3 days
14.41.44%2.1 days
363.60%20 hours
1000100%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 targetsWith SLI, SLO and an error budget
Operations says "too risky", product says "too slow", nobody has a numberA shared number says how much risk is left this month
Users form their own expectations, often wrongPublished SLOs set expectations, so users neither over-rely nor under-rely
Alerts fire on every error spike, on-call burns outAlerts fire when the budget is threatened
Reliability work loses every prioritisation fightAn empty budget makes reliability work the agreed priority
Good for: a prototype with five usersGood for: any service another team or a customer depends on
SLAcontract +consequencesSLOtarget on the SLI,over a windowerror budget = 1 - SLOSLIgood events / valid eventsmeasured, never promisedOwner: business + legal99.9% uptime, else 10% creditLooser than the SLO on purposeOwner: product + engineering99.95% of requests succeedMissed: error budget policy appliesTighter than the SLA (safety margin)Owner: the team that runs itrate(5xx) / rate(all) from the LBSame unit, same query, every timeTighter targets inside, looser promises outside: SLI < SLO target < SLA promise

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 ​

  1. "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.
  2. "More nines is always better." No. Past a point users cannot tell, features slow down and cost explodes (the "99% reliable smartphone" argument below).
  3. "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 ​

SourceWhat 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 BAn example error budget policy
Cloud provider SLAs (AWS, Google Cloud)The contract side: uptime percentages, definitions of "unavailable", credits and exclusions
Prometheus and OpenTelemetry docsThe 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 caller

Real 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 SLO

Real 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.

100%75%50%25%0%day 0day 10day 20day 30budget exhausted: freeze features, spend time on reliabilityburn 10: gone on day 3burn 2: day 15burn 1: exactly day 30one 40% incident on day 9, then slow burnremaining error budget

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.

IndicatorGood eventTypical forExample SLO
AvailabilityThe request succeeded (non-5xx, valid response)Request-driven services, APIs99.9% of requests succeed
LatencyThe request was faster than a thresholdRequest-driven services, storage99% of requests under 300 ms
QualityThe answer was not degraded (full results, not a fallback)Services that degrade gracefully99.5% of search results use the full index
CorrectnessThe right answer or record came outPipelines, billing, any data99.99% of invoices match the ledger
FreshnessThe data is newer than a thresholdPipelines, caches, read replicas99% of reads see data under 10 minutes old
CoverageEnough of the input was processedBatch and streaming jobs99% of nightly jobs process at least 99.9% of records
ThroughputThe system processed enough per unit of timePipelines, queues, ingestion95% of 5-minute intervals ingest at least 1,000 events/s
DurabilityA written record can still be readStorage systems99.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-basedWindow-based (good minutes, uptime)
UnitRequest or eventMinute (or other slice)
Numerator and denominatorGood requests, valid requestsGood minutes, minutes with traffic
Weights busy time moreYes: busy hours dominateNo: each minute counts the same
Works with zero trafficUndefinedNeeds a rule (probe or skip)
Matches contractsRarelyOften: SLAs usually count unavailable minutes
AlertingEasy with rate ratiosHarder, needs a per-minute good/bad series
Used inInternal SLOs, Prometheus burn-rate alertsCloud 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.

sql
-- 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
WhereSeesMissesCost
1. Client (browser, mobile app, RUM)Real latency, JavaScript failures, DNS and network problemsNeeds instrumentation, noisy, depends on user networksHighest
2. CDN or edgeCache hits, geo problemsOrigin internalsLow if you already pay for it
3. Load balancerEvery request that reached the fleet, including ones the app dropped; status and latencyClient-side rendering, anything before the LBLow: metrics already exist
4. ApplicationBusiness-level success (a 200 with an error body), per-route detailCrashes, queue time, requests that never arrivedLow, but blind to its own death
5. DependencyCause of failuresUser impactCheap, but it is a cause, not an SLI
Synthetic probe (black box)Works at zero traffic, checks the whole pathOnly the paths you probe, not real usersMedium

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.

StyleSLO sentenceHow to computeNotes
Threshold ratio (preferred)99% of requests under 300 msbucket{le="0.3"} divided by _countExact if a bucket boundary sits at 0.3
Quantile estimatep99 under 300 mshistogram_quantile(0.99, sum by (le) (rate(..._bucket[5m])))Interpolated inside a bucket; error grows with wide buckets
Averagemean under 100 msrate(sum) divided by rate(count)Hides the tail; do not use as an SLO
Summary quantilep99 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 windowCalendar window
Matches usersYesNo: resets forget incidents
Matches business planningWeaklyYes: quarterly reviews and contracts
Mid-period forecastStableUncertain: unknown traffic for the rest of the period
Typical choiceFour 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.

SLO30-day budgetWhat it implies for the designTypical fit
99%7.2 hA single server and manual recovery are acceptableInternal tools, batch dashboards
99.9%43.2 minRedundant app tier, automated failover, on-call, safe deploysMost B2B and consumer APIs
99.95%21.6 minMulti-AZ everything, zero-downtime migrations, fast rollbackPayments front doors, important SaaS
99.99%4.3 minNo human in the loop: automated detection and recovery, multi-region or cell designCore infrastructure, regional cloud services
99.999%25.9 sActive-active, dependency isolation, almost no change riskTelecom, 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.

Serial: every part must work, so multiplyGateway99.9%Orders99.9%Database99.9%= 99.70%130 min/mo0.999 x 0.999 x 0.999 = 0.997: three three-nines parts do not make three nines.Parallel: any one part is enough, so multiply the failuresLoadbalancerReplica A99%Replica B99%Pool99.99%99.99%pool only1 - (0.01 x 0.01) = 0.9999, but only if failures are independent and the LB and the failover work.Shared database, shared zone or shared deploy makes the "independent" assumption false.
PatternFormulaExampleResult
Serial (all needed)A × B × C3 services at 99.9%99.70% (about 130 min per 30 days)
Serial, longer chainproduct of all5 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%
Mixedserial of parallel groupsLB 99.99% → app 2 × 99.5% → DB 99.95%99.94% (about 27 min per 30 days)
With a fallbackserial, but the dependency failure is maskedRecommendations with cached defaultAvailability 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 typeTactic
Internal team serviceAgree an SLO, a latency budget and an error budget policy for the dependency; alert on its SLI
Third-party SaaSRead 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 featureDegrade gracefully and count the response as "quality" good or bad
Hard, critical, weak dependencyIsolate 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:

TriggerAction
Service at or above SLOReleases proceed according to the release policy
Error budget exceeded for the preceding four-week windowHalt all changes and releases except P0 issues and security fixes until back within SLO
A code bug or procedural error caused the missThe team must work on reliability
A postmortem shows a hard dependency could be softenedThe team must work on reliability
Outage caused by a company-wide network problem, or by another team that has itself frozenThe 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 weeksPostmortem required, with at least one P0 action item
One class of outage consumes more than 20% of the budget over a quarterA P0 item in the next quarter's planning
Disagreement about the calculation or actionsEscalate 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 lifted

SLAs 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, 2022Google Cloud: Cloud SQL SLA
TargetRegion-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 tiers10% 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 countedMinutes in which all running instances in two or more AZs have no external connectivityDowntime Period: one consecutive minute in which all valid requests fail; shorter blips do not count
How to claimOpen a support case within two billing cycles, with request logsCustomer must request the credit
RemedyCredit against future payments only, not a refundCredit to future bills; sole and exclusive remedy
Notable exclusionsForce majeure, your own actions, your software or equipmentScheduled 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.

JourneyStepsSLIWeight
Searchquery, results pageavailability and latency of resultsMedium
Add to cartadd, view cartavailabilityHigh
Paycreate order, authorise, confirmavailability and correctnessHighest: 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 ​

QuantityFormulaExample (SLO 99.9%, window 30 d)
Error budget1 − SLO0.001
Allowed downtimewindow × (1 − SLO)43.2 min
Burn rateerror ratio / (1 − SLO)1.44% / 0.1% = 14.4
Time to exhaustionwindow / burn rate30 d / 14.4 = 2.08 d
Budget spent while burningburn rate × held time / window14.4 × 1 h / 720 h = 2%
Burn rate for a chosen spendspend × window / alert window0.02 × 720 h / 1 h = 14.4
Serial availabilityproduct of availabilities0.999³ = 0.997
Parallel availability1 − product of failures1 − 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).

#DesignGoodBad
1Error ratio over 10 minutes above the SLO's ratioDetects a full outage in under a secondLow precision: a 0.1% error rate for 10 minutes alerts while spending 0.02% of the monthly budget
2Longer window (36 hours, alert at 5% of the budget)Better precisionReset time very poor: a 100% outage keeps alerting for 36 hours
3Add a duration (for)Higher precisionPoor 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
4Alert on burn rate (1 h window, burn rate 36 for 5% spend)Good precision and detection time, reset 58 minutesLow recall: a 35x burn never alerts but empties the budget in 20.5 hours
5Multiple burn rates and windowsPages for fast burn, tickets for slow burn; good recallEven longer reset time because of the three-day window
6Multiwindow, multi-burn-rateAdds a short window (about 1/12 of the long one) so the alert stops soon after the problemMore 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):

SeverityLong windowShort windowBurn rateBudget consumed
Page1 hour5 minutes14.42%
Page6 hours30 minutes65%
Ticket3 days6 hours110%

(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 ​

KnobWhereMeaning
record:rule groupPrecompute an expression and store it as a new series; the name convention is level:metric:operations
expr:recording and alerting ruleThe PromQL expression evaluated each interval
interval:rule groupHow often the group is evaluated (global evaluation_interval is the default)
for:alerting ruleThe 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 ruleKeep an alert firing this long after the condition stops matching, to avoid flapping
labels: and annotations:alerting ruleRouting labels such as severity: page and human text such as a runbook URL
rate(x[5m])PromQLPer-second average increase of a counter over the window
increase(x[28d])PromQLTotal increase over the window (expensive over long windows: use a recording rule)
le="0.3"histogram bucket labelCumulative 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         RESOLVES
04080120140 minfault, 10% errors (min 60-75)multiwindow 1h AND 5m1h window onlyfires 69, resolves 80fires 69, resolves 127Same detection time, but the short window ends the page 47 minutes earlier.

Both 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.

go
// 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:

go
// 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):

go
// 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 ​

OptionWhat it givesLimit
promhttp handler wrappersCounter, histogram and in-flight gauge middleware, /metrics handlerOnly code and method partition labels; a panicking handler reports nothing; wide histograms are costly
prometheus.NewHistogramVec with chosen bucketsA bucket boundary exactly at the SLO thresholdChanging buckets later means changing code and handling mixed layouts
Native histograms (Prometheus)Dynamic exponential buckets, change the threshold without redeployingInterpolated, newer feature; check your Prometheus version and client support
OpenTelemetry metrics SDKCounter, UpDownCounter, Gauge, Histogram instruments, Views to change aggregation, vendor-neutral exportMore moving parts; same SLI maths
expvar (standard library)Counters as JSON on /debug/vars with no dependencyNo 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.

go
// 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
<?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
<?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
<?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
<?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 ​

PieceWhat the docs sayUse for SLOs
Health route /upServed 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 checkLoad balancer and Kubernetes probes; exclude it from the SLI
Laravel PulseA 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 entriesHuman 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 middlewareterminate($request, $response) runs after the response is sent under FastCGI; a fresh instance is resolved unless registered as a singletonTiming without delaying the response
LoggingChannels and context (Log::withContext)Structured request logs for log-based SLIs and exemplars
Prometheus clientpromphp/prometheus_client_php with APCu or Redis storage; in-memory resets every request under PHP-FPMThe real SLI instruments
StatsDA 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
<?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
<?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" ​

StepActionOutput
1List the critical user journeysThree to five journeys
2Pick one availability and one latency SLI per journey, as good/valid ratiosSLI specifications
3Measure at the load balancer firstSLI implementations
4Compute the last 28 days, set the target slightly below what users already tolerate, never at 100%A first SLO
5Agree the error budget policy with productA signed document
6Add burn-rate alerts, remove cause-based alerts that nobody acts onQuieter on-call

The SQL for steps 3 to 4 (and the credit lookup) lives in the snippet:

sql
-- 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:

yml
# 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
          )
yml
# 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" ​

CauseFix
SLO tighter than users needLoosen it; the SRE book says it is better to start loose and tighten
One dependency eats the budgetSoften 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 errorsCanary, progressive delivery, fast rollback (the example policy's background says changes represent roughly 70% of outages)
No capacity headroomRevisit 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 ​

SituationSLITarget and windowExtra techniqueReason
Public REST API, B2BAvailability (non-5xx) and latency (under 300 ms) at the LB99.9% over 28 days, 99% under 300 msBurn-rate alerts, synthetic probeContracts follow, easy to measure
Checkout and paymentAvailability and correctness (no double charge)99.95% over 28 daysIdempotency keys, reconciliation jobOne failure costs more than many
Internal admin toolAvailability, coarse99% over a quarterTicket-only alertsCost of a nine is not justified
Search or listing pageLatency and quality (full results)99% under 500 ms; 99.5% undegradedGraded SLOsThe tail drives bounces
Nightly batch or ETLFreshness and coverage99% of runs finish before 06:00Window-based per runUsers care about "is it there when I need it"
Read replica fed dashboardsFreshness99% of reads under 10 s behindLag metric as SLISee replication
Object or file storageDurability and availabilityA durability number is a design claim, not a measurement; measure read-after-write successScrubbing, checksumsDurability is hard to observe directly
Message pipelineThroughput, end-to-end latency, correctness95% of messages processed under 30 sDead-letter queue as an SLI inputBacklog is the failure signal
Low-traffic serviceAvailability with synthetic traffic99% over 28 daysLarger windows, group servicesRatios are noisy
Selling an SLASame SLIs, window-basedSLA 99.9% monthly, internal SLO 99.95%Credit exposure budgetGap 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).

ModuleBudget sliceTechnique
Catalogue (read-heavy)30% of the checkout latency budgetCache, read replica
Pricing10%In-process, no I/O
Payment50%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 ms

Rules for services:

RuleWhy
One SLO per service, plus journey SLOs on the critical pathService SLOs tell who owns a failure; journey SLOs tell what users feel
Each hop gets a share of the latency budgetBudgets 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 boundaryA 4xx from a bad client must not burn the callee's budget
Dependencies need written SLOs and alerts on their SLIsThe Chubby lesson
Gateway and mesh are the cheapest place to measure edge SLIsSee API Gateway, BFF & Service Mesh
Many services, many SLOs: use templates or generatorsHand-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 ​

ComponentSLI that mattersTrap
Read replicaFreshness (replica lag)A replica can be 100% available and 20 minutes stale; measure lag, not ping
CacheHit ratio and freshness, plus the origin's SLICache hides origin failures until it expires; the SLI of the page is still the page
Message queueEnd-to-end age of the oldest message, throughputProducers succeed while consumers fall behind
Multi-region active-passiveRecovery time and data lossFailover time counts as downtime in the SLO
Multi-region active-activeAvailability per region and globallyCorrelated failures (shared control plane, bad deploy) break the parallel formula
Object storageDurability, availabilityDurability 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× ​

ScaleSLO practiceWhat changes
1× (one team, one service)One availability and one latency SLO per journey, LB metrics, a wiki page and a weekly lookFew alerts, manual reviews
10× (several teams)SLOs per service and journey, burn-rate alerts via recording rules, error budget policy signed per teamStandard 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-offGovernance: 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 examples

Expected: 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%).

go
// 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 ./lab

Actual 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.

go
// 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)
yml
# 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"]
yml
# 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:ro

Part 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 ​

BeliefReality
"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 ​

TopicWhat to remember
SLIgood / valid events, 0 to 100%, measured near the user
SLOA target on the SLI over a window, internal, tighter than the SLA
SLAA contract with consequences (credits); looser than the SLO
Error budget1 - SLO; 99.9% over 30 days is 43.2 minutes
Burn rateerror ratio / (1 - SLO); 1 empties the budget exactly at window end
Page thresholds14.4x over 1 h and 5 m, 6x over 6 h and 30 m (99.9% SLO, 30 days)
Ticket thresholds3x over 1 d and 2 h, 1x over 3 d and 6 h
Short windowAbout 1/12 of the long window
Serial availabilityMultiply: 0.999 to the 3rd = 99.7%
Parallel availability1 - (1-A)(1-B), needs independent failures
WindowsRolling 28 days for users, calendar for contracts and planning
PercentilesCount requests under a threshold from le buckets; never average percentiles
Histogram bucketPut a boundary exactly on the SLO threshold
PolicyWritten, signed by product, dev and SRE: freeze launches and work on reliability when empty
Measure atLoad 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 ​

Show:
  • 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 ​

TermOne 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 budget1 minus the SLO: the failure you may spend
Burn rateError ratio divided by the error budget; speed of spending
Error budget policyAgreed actions when the budget is gone
NinesCount of 9s in the availability percentage (99.9% is three nines)
AvailabilityShare of valid requests that succeed, or share of time the service is up
Latency SLIShare of requests faster than a threshold
FreshnessShare of data newer than a threshold
CorrectnessShare of outputs that are right
DurabilityShare of written data that can still be read
Request-based SLICounts events
Window-based SLICounts good time slices (minutes)
Rolling windowWindow that always looks back a fixed length
Calendar windowWindow aligned to a month or quarter
Percentile (pN)Value below which N% of observations fall
HistogramCounts observations per bucket; allows aggregation across instances
Bucket boundary (le)Cumulative upper bound of a Prometheus histogram bucket
Recording rulePrecomputed PromQL expression stored as a series
Alerting rulePromQL condition that fires an alert, with labels and annotations
Multiwindow, multi-burn-rate alertFires 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 timeTime to alert / time an alert keeps firing after recovery
Composite availabilityAvailability of a system built from parts: serial multiplies, parallel multiplies failures
Critical user journeyA task a user cares about, spanning several requests
Service creditMoney off a future bill when an SLA is missed
Monthly Uptime Percentage100% minus the share of the month's minutes the service was unavailable
Synthetic probeAn artificial request that checks the service from outside
/up health routeLaravel's boot check, 200 if the app booted without exceptions
Laravel PulseFirst-party dashboard for application usage and performance
StatsDUDP line protocol for counters and timings
RunbookWritten steps for responding to an alert

References ​

Built by Morteza Negahi