Data and monitoring · Intermediate · 22 min
Define SLOs and error budgets for a service
By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · Prometheus 3.16.0 (promtool) · Python 3
You will have two SLOs for a small payments API, its error budget in minutes and requests, Prometheus recording rules for the SLIs that pass promtool unit tests, and a written error-budget policy.
On this page
"Is the payments API reliable enough?" is a question nobody can answer until you say what "enough" means. A service level objective (SLO) is that answer written down: a measurement of what users experience, a target for it, and a period to measure over. Once you have one, the gap between the target and perfection becomes an error budget, an amount of failure you are allowed to spend on releases, experiments and bad luck. When the budget runs low, the team slows down. When there is plenty left, it can move faster.
This tutorial works through one small service: a payments API that takes card and mobile-money payments for an online shop. You pick two service level indicators (SLIs) that users feel, set targets over a 28-day window, work out the budget in minutes and in requests with a short Python script, and write the SLIs as Prometheus recording rules. You prove the rules with promtool test rules, which feeds them made-up traffic and checks the answers, so you do not need a running service to start. Last, you write the error-budget policy: what the team agrees to do when the budget is spent.
The rules assume the API exposes two common metrics: a counter http_requests_total with a code label for the HTTP status, and a histogram http_request_duration_seconds. If your service does not have them yet, instrument a Python app with Prometheus metrics shows how to add metrics, but its names differ: it exports shop_http_requests_total with a status label and shop_http_request_duration_seconds. If you use that app, change the metric names, the code label to status, and job="payments-api" to your scrape job, in both the rules and the tests.
Step 1 · Make a folder and check the tools
You need Python 3 for the budget arithmetic and promtool for the rules. Ubuntu Server ships Python 3; the install command makes sure of it. Make a folder for the files you write in this tutorial:
sudo apt update
sudo apt install -y python3
mkdir -p ~/slo-demo
cd ~/slo-demo
python3 --version
promtool --version | head -n 1Check it worked
The python3 --version line starts with Python 3., and the promtool line starts with promtool, version 3.16.0. If promtool is not found, install Prometheus as in monitor a server with Prometheus and Node Exporter, which puts promtool in /usr/local/bin.
Step 2 · Choose SLIs your users feel
An SLI is a ratio: good events divided by all events, so it is always between 0 and 1. The hard part is choosing which events count as good. Start from what a customer at the checkout notices, not from what is easy to measure on the server.
A customer paying for an order notices two things. Either the payment request worked, or it failed with an error. And either it came back quickly, or they stared at a spinner. That gives the payments API two SLIs:
- Availability: the share of requests that did not fail with a server error. A
5xxstatus is bad. A4xxstatus, such as a declined card or a missing field, is the API doing its job correctly, so it counts as good. - Latency: the share of requests answered in under 300 milliseconds.
Things you could measure but should not use as SLIs here: CPU use, memory, the number of pods running. A server at 95% CPU that answers every payment in 80 ms is fine; one at 10% CPU that returns errors is not.
Where you measure matters too. Your service only sees requests that reach it. If many of your customers pay from phones on prepaid mobile data, as is common across much of Africa, a request that dies on a weak connection never shows up in your server's metrics. Measuring at the load balancer is a little closer to the user than measuring in the app, and a small probe that calls the API from a mobile network in the regions you serve catches what both miss. Start with server-side numbers, and write down what they cannot see.
Write the SLIs down before any targets. Plain text is enough:
cd ~/slo-demo
cat > payments-api-slos.md <<'EOF'
# payments-api: service level objectives
Owner: payments team
Users: shoppers paying by card or mobile money at checkout
## SLI 1: availability
Good: requests that did not return a 5xx status.
Valid: all requests to payments-api, as counted by http_requests_total.
4xx responses (declined card, bad input) count as good.
## SLI 2: latency
Good: requests answered in under 300 ms (histogram bucket le="0.3").
Valid: all requests to payments-api, as counted by http_request_duration_seconds_count.
## Not measured here
Requests that never reach the server, such as those lost on a mobile network.
EOFCheck it worked
Run grep -c '^## SLI' ~/slo-demo/payments-api-slos.md. It prints 2. Read each SLI out loud as a sentence a customer would recognise: "my payment failed", "my payment was slow". If one only makes sense to an engineer, swap it for something closer to the user.
Step 3 · Set targets and a 28-day window
An SLO is an SLI plus a target over a window. For the payments API:
- Availability: 99.9% of requests succeed, over a rolling 28 days.
- Latency: 99% of requests take under 300 ms, over a rolling 28 days.
Why 28 days and not a calendar month: 28 days is exactly four weeks, so every window holds the same number of Mondays and Saturdays, and a quiet weekend or a busy payday Friday does not make one window look better than another. Calendar months vary from 28 to 31 days, which makes the numbers jump at month boundaries. Rolling means the window always ends now, so a bad day fades out of the numbers 28 days later rather than all at once.
Why these targets: pick the lowest target at which users stay happy, then check you can meet it today. Look at the last few weeks of your real numbers if you have them. A target you already miss every week only teaches people to ignore it. A target far above what users need wastes effort.
Add the targets to the SLO file:
cd ~/slo-demo
cat >> payments-api-slos.md <<'EOF'
## Objectives (rolling 28-day window)
Availability SLO: 99.9% of valid requests are good.
Latency SLO: 99% of valid requests are good.
Review these targets every quarter, or after any change to how users pay.
EOFCheck it worked
Run grep SLO: ~/slo-demo/payments-api-slos.md. You see two lines, one with 99.9% and one with 99%, and nowhere does the file say 100%.
Step 4 · Work out the error budget
The error budget is everything the target leaves over. A 99.9% target allows 0.1% of requests in the window to fail. Two ways of putting that in numbers help different people:
- In requests: the budget is the window's expected traffic times 0.1%. This is what the SLI measures, so it is the true budget.
- In minutes: the window's length times 0.1%. This is how long a full outage could last before the budget is gone. It assumes traffic is even, so treat it as a rough guide; an outage at peak time burns budget faster than one at 3 a.m.
Write a short script that does the arithmetic for several targets at once. It uses Decimal so that 100 minus 99.9 is exactly 0.1, not 0.0999999:
cd ~/slo-demo
cat > budget.py <<'PY'
"""Work out the error budget for one or more SLO targets."""
import argparse
from decimal import Decimal
parser = argparse.ArgumentParser(description="Error budget for SLO targets")
parser.add_argument("targets", nargs="+", type=Decimal, help="targets in percent, such as 99.9")
parser.add_argument("--days", type=int, default=28, help="length of the SLO window in days")
parser.add_argument("--requests", type=int, required=True, help="requests expected in one window")
args = parser.parse_args()
window_minutes = args.days * 24 * 60
print(f"Window: {args.days} days = {window_minutes:,} minutes, {args.requests:,} requests")
print(f"{'target':<9} {'budget':<8} {'minutes':>8} {'requests':>9}")
for target in args.targets:
if not 0 < target <= 100:
parser.error(f"target {target} is not between 0 and 100")
budget = (100 - target) / 100
minutes = window_minutes * budget
requests = int(args.requests * budget)
print(f"{str(target) + '%':<9} {str(100 - target) + '%':<8} {minutes:>8.2f} {requests:>9,}")
PYThe payments API handles about 3 million requests in 28 days. Run the script for a range of targets, from two nines to 100%:
cd ~/slo-demo
python3 budget.py --days 28 --requests 3000000 99 99.5 99.9 99.99 100Read the table from the bottom up. At 100% the budget is zero: one failed payment in four weeks breaks the objective. That target is wrong for three reasons:
- You cannot reach it. Networks drop packets, disks fail, card networks and mobile-money providers have their own outages. Your users' phones lose signal. A 100% target is missed before you start.
- It stops all change. Every deploy carries some risk. With no budget, the only safe release is no release.
- Users cannot tell. A customer whose phone is on a patchy connection fails more often than your API does. Going from 99.99% to 100% costs a great deal and changes nothing they notice.
At 99.99% the payments API could be down for about 4 minutes in four weeks, less than one slow rollback. At 99.9% it has about 40 minutes, or 3,000 failed requests. That is enough room to ship weekly with a tested rollback, which is why the team chose it. For latency, the 99% target allows 30,000 slow requests in the window.
Check it worked
The 99.9% row shows 40.32 minutes and 3,000 requests, and the 100% row shows 0.00 and 0. Run the script with your own traffic, for example python3 budget.py --requests 450000 99.9. If the request budget comes out under about 100, your service is quiet enough that a handful of failures will swing the SLI, so consider a longer window or a lower target until traffic grows.
Step 5 · Write the SLIs as recording rules
A recording rule is a query that Prometheus runs on a schedule and stores as a new series. Recording the SLIs means every dashboard and alert reads the same definition, and the long 28-day queries run once every few minutes instead of every time someone opens a graph. The names follow the Prometheus convention level:metric:operations: the labels the result keeps, what it measures, and how it was computed.
Create the rules file:
cd ~/slo-demo
cat > payments-slo-rules.yml <<'YAML'
groups:
- name: payments-api-sli
interval: 1m
rules:
# Share of requests without a 5xx status, over the last 5 minutes.
- record: job:sli_availability:ratio_rate5m
expr: |
sum by (job) (rate(http_requests_total{job="payments-api", code!~"5.."}[5m]))
/
sum by (job) (rate(http_requests_total{job="payments-api"}[5m]))
# Share of requests faster than 300 ms, over the last 5 minutes.
- record: job:sli_latency:ratio_rate5m
expr: |
sum by (job) (rate(http_request_duration_seconds_bucket{job="payments-api", le="0.3"}[5m]))
/
sum by (job) (rate(http_request_duration_seconds_count{job="payments-api"}[5m]))
- name: payments-api-slo-window
interval: 5m
rules:
# The same ratios over the whole 28-day SLO window.
- record: job:sli_availability:ratio_rate28d
expr: |
sum by (job) (increase(http_requests_total{job="payments-api", code!~"5.."}[28d]))
/
sum by (job) (increase(http_requests_total{job="payments-api"}[28d]))
- record: job:sli_latency:ratio_rate28d
expr: |
sum by (job) (increase(http_request_duration_seconds_bucket{job="payments-api", le="0.3"}[28d]))
/
sum by (job) (increase(http_request_duration_seconds_count{job="payments-api"}[28d]))
# Error budget left: 1 means untouched, 0 means spent, below 0 means overspent.
- record: job:slo_availability:error_budget_remaining
expr: 1 - (1 - job:sli_availability:ratio_rate28d) / (1 - 0.999)
- record: job:slo_latency:error_budget_remaining
expr: 1 - (1 - job:sli_latency:ratio_rate28d) / (1 - 0.99)
YAML
promtool check rules payments-slo-rules.ymlWhat each part does:
code!~"5.."keeps every status that does not start with 5, so declined cards (402,422) count as good, as the SLI says.- The latency rule divides the histogram's
le="0.3"bucket, the count of requests that took 0.3 seconds or less, by_count, the count of all requests. Your histogram must have a bucket boundary at exactly 0.3 for this to work; check the buckets your code defines. - The 5-minute ratios are for dashboards and for the burn-rate alerts in the next tutorial. The 28-day ratios answer "are we meeting the SLO?". They use
increase()over[28d], which reads four weeks of raw samples, so that group runs every 5 minutes rather than every minute. - The budget rules turn the SLI into the budget left. With an SLI of 0.9995 against a 99.9% target, the bad share is 0.0005 out of an allowed 0.001, so half the budget is used and
0.5is left. With a target of 100% the divisor would be zero, one more sign that 100% does not work as a target.
Check it worked
promtool check rules prints the file name and a line like SUCCESS: 6 rules found. If it prints FAILED with a parse error, the cause is nearly always indentation: record and expr must line up under the same -.
Step 6 · Prove the rules with promtool
A typo in a label (job="payment-api") does not make a rule fail. It makes it return nothing, and you find out weeks later on a blank dashboard. promtool test rules catches that now: you describe a short stretch of made-up traffic, and it checks that each rule returns the value you expect.
Values such as 0+999x30 mean "start at 0 and add 999 each interval, 30 times", which describes a counter growing steadily. Floating-point arithmetic can leave the tenth decimal place slightly off, so each test wraps the rule in round(..., 0.0001) to compare at four decimal places:
cd ~/slo-demo
cat > payments-slo-test.yml <<'YAML'
rule_files:
- payments-slo-rules.yml
evaluation_interval: 1m
tests:
# 30 minutes of steady traffic: per minute, 999 good requests, 1 server
# error, and 990 of every 1,000 requests under 300 ms.
- interval: 1m
input_series:
- series: 'http_requests_total{job="payments-api", code="200"}'
values: '0+999x30'
- series: 'http_requests_total{job="payments-api", code="503"}'
values: '0+1x30'
- series: 'http_request_duration_seconds_bucket{job="payments-api", le="0.3"}'
values: '0+990x30'
- series: 'http_request_duration_seconds_count{job="payments-api"}'
values: '0+1000x30'
promql_expr_test:
- expr: round(job:sli_availability:ratio_rate5m, 0.0001)
eval_time: 20m
exp_samples:
- labels: '{job="payments-api"}'
value: 0.999
- expr: round(job:sli_latency:ratio_rate5m, 0.0001)
eval_time: 20m
exp_samples:
- labels: '{job="payments-api"}'
value: 0.99
# 700 hours, longer than the 28-day window: per hour, 20,000 requests.
# 500 are declined cards (422, good), 10 are server errors (500, bad).
# 19,940 are under 300 ms.
- interval: 1h
input_series:
- series: 'http_requests_total{job="payments-api", code="200"}'
values: '0+19490x700'
- series: 'http_requests_total{job="payments-api", code="422"}'
values: '0+500x700'
- series: 'http_requests_total{job="payments-api", code="500"}'
values: '0+10x700'
- series: 'http_request_duration_seconds_bucket{job="payments-api", le="0.3"}'
values: '0+19940x700'
- series: 'http_request_duration_seconds_count{job="payments-api"}'
values: '0+20000x700'
promql_expr_test:
- expr: round(job:sli_availability:ratio_rate28d, 0.0001)
eval_time: 700h
exp_samples:
- labels: '{job="payments-api"}'
value: 0.9995
- expr: round(job:sli_latency:ratio_rate28d, 0.0001)
eval_time: 700h
exp_samples:
- labels: '{job="payments-api"}'
value: 0.997
- expr: round(job:slo_availability:error_budget_remaining, 0.0001)
eval_time: 700h
exp_samples:
- labels: '{job="payments-api"}'
value: 0.5
- expr: round(job:slo_latency:error_budget_remaining, 0.0001)
eval_time: 700h
exp_samples:
- labels: '{job="payments-api"}'
value: 0.7
YAML
promtool test rules payments-slo-test.ymlThe second test covers the full window. Of 20,000 requests an hour, 10 fail, so the availability SLI is 0.9995 and half the availability budget is left. 60 requests an hour are slow, a bad share of 0.003 against an allowed 0.01, so 70% of the latency budget is left. The 422 responses count as good, exactly as the SLO file says.
Check it worked
The output names the test file and ends with SUCCESS. To see a failure, change value: 0.5 to value: 0.6 and run the test again: promtool prints FAILED, the expression, and the expected and actual values side by side. Change it back before you continue.
Step 7 · Write the error-budget policy
Numbers alone change nothing. The policy is the agreement, made in advance and signed off by the people who decide what gets built, about what happens as the budget runs down. Agreeing it while everything is calm stops the argument from happening in the middle of an incident.
A useful policy is short and answers four questions: what triggers it, what changes, who decides, and what does not count.
Write it next to the SLOs:
cd ~/slo-demo
cat > error-budget-policy.md <<'EOF'
# payments-api: error-budget policy
Applies to: the availability and latency SLOs in payments-api-slos.md
Budget source: job:slo_availability:error_budget_remaining and
job:slo_latency:error_budget_remaining (1 = full, 0 = spent)
Agreed by: payments engineering lead, product manager for checkout
Review: every quarter
## Budget left, and what we do
Above 50%: ship as usual. Spare budget may be spent on experiments and
planned maintenance.
50% to 25%: smaller releases; every deploy has a tested rollback.
25% to 0%: only bug fixes, security fixes and configuration changes ship.
The next sprint puts reliability work first.
Spent (0% or below): feature freeze. Only reliability and security changes
ship until the 28-day window has budget again.
## Single incidents
Any incident that uses more than 20% of a budget in one go gets a written
review within five working days, with at least one action to stop it
happening again.
## What does not count against the budget
Planned maintenance announced to customers 48 hours ahead.
## Third-party outages
Outages of a card network or mobile-money provider are counted, but the
review may decide to add a fallback rather than freeze features.
## Disagreements
If the team disagrees on applying this policy, the engineering lead and
the checkout product manager decide together within one working day.
EOFAdjust the thresholds and names to your team. The point is that everyone knows in advance what "the budget is spent" means for their work this week.
Check it worked
Open ~/slo-demo/error-budget-policy.md and check that each threshold names an action someone can actually take or refuse, and that the file names who agreed it. grep -c '^Above 50%\|^50% to 25%\|^25% to 0%\|^Spent' ~/slo-demo/error-budget-policy.md prints 4. Share it with the people named in it before you treat it as agreed.
Step 8 · Load the rules into Prometheus
If you run Prometheus as in the Prometheus and Node Exporter tutorial and it scrapes your API under job="payments-api", copy the rules into its configuration folder:
sudo install -d -o root -g root -m 0755 /etc/prometheus/rules
sudo install -o root -g root -m 0644 ~/slo-demo/payments-slo-rules.yml /etc/prometheus/rules/payments-slo-rules.ymlOpen /etc/prometheus/prometheus.yml with sudo nano /etc/prometheus/prometheus.yml and add this block at the top level, below global:. If the file already has a rule_files: list, add the line to that list instead of a second block:
rule_files:
- /etc/prometheus/rules/*.ymlCheck the configuration, which also loads and checks every rules file it names, then reload Prometheus:
promtool check config /etc/prometheus/prometheus.ymlsudo systemctl reload prometheusCheck it worked
promtool check config reports the config file as valid and /etc/prometheus/rules/payments-slo-rules.yml with SUCCESS: 6 rules found. After the reload and a few minutes of scraping, ask Prometheus for the budget left:
curl -s http://127.0.0.1:9090/api/v1/query --data-urlencode 'query=job:slo_availability:error_budget_remaining'The JSON holds one result with "job":"payments-api" and a value close to 1 for a service that has been healthy. The 28-day rules only cover the whole window once Prometheus has 28 days of data; until then they describe the time since scraping started.
Step 9 · Remove the demo files
The burn-rate tutorial uses the same payments-api metrics and SLO, but starts with its own folder, so you can remove this one. To remove everything this tutorial created:
rm -rf ~/slo-demo
sudo rm -f /etc/prometheus/rules/payments-slo-rules.ymlThen delete the rule_files: block from /etc/prometheus/prometheus.yml if you added it only for this tutorial, run promtool check config /etc/prometheus/prometheus.yml, and reload Prometheus.
Check it worked
ls ~/slo-demo reports No such file or directory, and ls /etc/prometheus/rules no longer lists payments-slo-rules.yml.
Next steps
- Get paged only when the budget is burning fast: alert on SLO burn rate with multi-window alerts in Prometheus.
- Go deeper on the queries behind these rules: write PromQL for request rates, errors and latency.
- Learn when recording rules pay off and how to name them: speed up dashboards with Prometheus recording rules.
- Put the budget on a screen the team sees: build your first Grafana dashboard.
Related tutorials
- Alert on SLO burn rate with multi-window alerts in PrometheusYou will have Prometheus 3.16 recording rules for a payments API's error ratio over five windows, a fast-burn page and a slow-burn ticket from the multi-window, multi-burn-rate method, and promtool unit tests proving which incidents page, which open a ticket and which stay quiet.
- Write PromQL for request rates, errors and latencyYou will write the PromQL queries for a service's request rate, error ratio and p95 latency, plus week-on-week and missing-data checks, and prove every one with promtool unit tests over synthetic data.
- How to Monitor a Linux Server with Prometheus and Node ExporterYou will install Node Exporter 1.12 and Prometheus 3.16 from the official release files on Ubuntu 26.04, run both as locked-down systemd services that listen on localhost only, and query your server's CPU, memory and uptime with PromQL.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials