Pidoku

Archive

This learning material is in the archive. It is not currently maintained and has not been updated with the latest information, so tool versions, prices and dates may be out of date.

SLOs in Practice

Module 2 Lesson 2.e 45 min Difficulty 3/5

Prerequisites 2.d

The idea in one minute#

Writing burn-rate rules by hand for every service is error-prone: five recording rules and three alerts per SLO, each with the same expression copied five times. In practice teams write a short SLO definition and let a generator produce the rules — Sloth and Pyrra for Prometheus, OpenSLO as a vendor-neutral format, or a vendor’s SLO feature (Datadog, Grafana Cloud, Google Cloud, Dynatrace, Nobl9). Then SLOs become part of the team’s routine: a dashboard everyone looks at, a weekly glance at budgets, and a quarterly review that changes targets.

An analogy#

Nobody writes assembly for every program. You write the intent in a higher-level language and a compiler produces the instructions consistently. An SLO definition is the source; the Prometheus rules are the compiled output.

A picture#

flowchart LR
  Y[":i-file-text: <b>SLO definition</b><br/><small>YAML in the service repo</small>"] --> CI[":github: <b>CI</b><br/><small>validate</small>"]
  CI --> GEN["<b>Generator</b><br/><small>Sloth / Pyrra / oslo</small>"]
  GEN --> RR[":prometheus: <b>Recording rules</b><br/><small>5m … 30d ratios</small>"]
  GEN --> AR[":prometheus: <b>Burn-rate alerts</b><br/><small>page + ticket</small>"]
  RR --> G[":grafana: <b>SLO dashboard</b><br/><small>budget remaining</small>"]
  AR --> AM["<b>Alertmanager</b>"] --> PD[":pagerduty: <b>On-call</b>"]
  class Y memory
  class CI,GEN compute
  class RR,AR queue
  class G io
  class AM,PD warn

How it really works#

Sloth#

Sloth reads a small YAML file (or a Kubernetes PrometheusServiceLevel resource) and generates the recording and multiwindow alerting rules from 2.d. Its spec also supports OpenSLO input.

YAML
version: "prometheus/v1"
service: "checkout"
labels:
  team: payments
slos:
  - name: "requests-availability"
    objective: 99.9
    description: "Checkout requests do not fail on the server side."
    sli:
      events:
        error_query: sum(rate(http_requests_total{job="checkout",code=~"5..|429"}[{{.window}}]))
        total_query: sum(rate(http_requests_total{job="checkout"}[{{.window}}]))
    alerting:
      name: CheckoutHighErrorRate
      labels:
        category: availability
      annotations:
        runbook: "https://runbooks.example.com/checkout/error-budget-burn"
      page_alert:
        labels:
          severity: page
      ticket_alert:
        labels:
          severity: ticket

sloth generate -i checkout.yml -o checkout-rules.yml produces a Prometheus rule file; sloth validate runs in CI so a broken query never reaches production.

Pyrra#

Pyrra uses a Kubernetes custom resource and adds a web UI that lists every SLO with its budget remaining and burn-rate graphs.

YAML
apiVersion: pyrra.dev/v1alpha1
kind: ServiceLevelObjective
metadata:
  name: checkout-availability
  namespace: payments
spec:
  target: "99.9"
  window: 28d
  indicator:
    ratio:
      errors:
        metric: http_requests_total{job="checkout",code=~"5..|429"}
      total:
        metric: http_requests_total{job="checkout"}

OpenSLO#

OpenSLO is a vendor-neutral YAML specification (version 1.0 since 2022) for SLOs, SLIs, alert policies and data sources. It is useful when an organisation has more than one monitoring backend, or wants SLO definitions that survive a vendor change. The reference CLI, oslo, validates and converts files.

YAML
apiVersion: openslo/v1
kind: SLO
metadata:
  name: checkout-availability
  displayName: Checkout availability
spec:
  service: checkout
  budgetingMethod: Occurrences
  timeWindow:
    - duration: 28d
      isRolling: true
  indicator:
    metadata:
      name: checkout-good-ratio
    spec:
      ratioMetric:
        counter: true
        good:
          metricSource:
            type: Prometheus
            spec:
              query: sum(http_requests_total{job="checkout",code!~"5..|429"})
        total:
          metricSource:
            type: Prometheus
            spec:
              query: sum(http_requests_total{job="checkout"})
  objectives:
    - displayName: Good
      target: 0.999

budgetingMethod: Occurrences is request-based; Timeslices is the window-based SLI from 2.a.

Choosing#

OptionChoose when
Hand-written rulesOne or two SLOs, learning
SlothPrometheus, GitOps, you want generated rules and nothing else
PyrraPrometheus on Kubernetes, and you want a UI for budgets
OpenSLO + a converterSeveral monitoring backends, or vendor neutrality matters
Vendor SLO featureThe organisation already standardised on that vendor

The SLO dashboard#

One dashboard per service, top to bottom:

  1. SLO status: current SLI over the window, target, budget remaining (%). One number per SLO, big.
  2. Burn rate over 1 h and 6 h, with the 14.4 and 6 thresholds drawn.
  3. Budget burndown: budget remaining over the last 28 days. The slope is the story.
  4. SLI over time at 5-minute resolution, so incidents are visible as dips.
  5. Links: SLO document, error budget policy, runbook, recent postmortems.

SLOs in the team’s routine#

WhenWhatWho
Every pageThe alert links to the SLO dashboard and runbookOn-call
Weekly ops reviewBudget remaining per SLO; any incident that used > 10%Team + SRE
Before a risky launchCheck budget; level 2 or 3 of the policy needs sign-offLaunch owner
QuarterlySLO review: was the target right? Did users complain inside budget? Did we page for things users did not feel?Team, product, SRE
YearlyRetire SLOs nobody looks at; add ones for new journeysTeam

The quarterly review asks two questions that keep SLOs honest:

  • Were users unhappy while we were within SLO? Then the SLI or target is wrong.
  • Were users happy while we were out of SLO? Then the target is too strict, or the SLI measures the wrong thing.

A worked example#

A team adopts SLOs for twelve services. By hand that would be 12 × (5 recording + 2 alerting) rules, with the same expression copied 60 times. With Sloth, each service gets one 20-line file in its repo, reviewed like code. Three months later:

  • One team discovers its SLI query counted health checks — sloth validate passed (the query was valid) but the quarterly review caught it, because users complained while the SLO was green.
  • One service’s 99.99% target was missed every week; it was lowered to 99.9% because the database underneath only offered 99.95%.
  • Pages for “CPU > 80%” were deleted for every service with an SLO alert. Pages per week fell by about two thirds.

Code#

A miniature generator, to show there is no magic: given an SLO definition, emit the recording rules and multiwindow alerts from 2.d.

Go
// slogen.go — generate Prometheus recording and burn-rate alert rules from an SLO definition.
package main

import (
	"fmt"
	"os"
	"strings"
	"text/template"
)

type SLO struct {
	Service    string
	Name       string
	Objective  float64 // e.g. 99.9
	ErrorQuery string  // with {{.window}} placeholder
	TotalQuery string
	Runbook    string
}

type window struct{ Name string }

type alertRule struct {
	Severity                string
	LongWin, ShortWin       string
	Burn                    float64
	SecondLong, SecondShort string
	SecondBurn              float64
}

const tpl = `groups:
  - name: {{.S.Service}}-{{.S.Name}}-recordings
    rules:
{{- range .Windows}}
      - record: slo:{{$.S.Service}}_{{$.S.Name}}:error_ratio_{{.Name}}
        expr: ({{q $.S.ErrorQuery .Name}}) / ({{q $.S.TotalQuery .Name}})
{{- end}}
  - name: {{.S.Service}}-{{.S.Name}}-alerts
    rules:
{{- range .Alerts}}
      - alert: {{title $.S.Service}}{{title $.S.Name}}BudgetBurn{{title .Severity}}
        expr: |
          (slo:{{$.S.Service}}_{{$.S.Name}}:error_ratio_{{.LongWin}} > ({{.Burn}} * {{$.Budget}})
            and slo:{{$.S.Service}}_{{$.S.Name}}:error_ratio_{{.ShortWin}} > ({{.Burn}} * {{$.Budget}}))
{{- if .SecondLong}}
          or
          (slo:{{$.S.Service}}_{{$.S.Name}}:error_ratio_{{.SecondLong}} > ({{.SecondBurn}} * {{$.Budget}})
            and slo:{{$.S.Service}}_{{$.S.Name}}:error_ratio_{{.SecondShort}} > ({{.SecondBurn}} * {{$.Budget}}))
{{- end}}
        labels:
          severity: {{.Severity}}
          service: {{$.S.Service}}
        annotations:
          runbook_url: {{$.S.Runbook}}
{{- end}}
`

func main() {
	slo := SLO{
		Service:    "checkout",
		Name:       "availability",
		Objective:  99.9,
		ErrorQuery: `sum(rate(http_requests_total{job="checkout",code=~"5..|429"}[{{.window}}]))`,
		TotalQuery: `sum(rate(http_requests_total{job="checkout"}[{{.window}}]))`,
		Runbook:    "https://runbooks.example.com/checkout/error-budget-burn",
	}
	funcs := template.FuncMap{
		"q":     func(query, win string) string { return strings.ReplaceAll(query, "{{.window}}", win) },
		"title": func(s string) string { return strings.ToUpper(s[:1]) + s[1:] },
	}
	t := template.Must(template.New("rules").Funcs(funcs).Parse(tpl))
	data := map[string]any{
		"S":       slo,
		"Budget":  fmt.Sprintf("%.6g", (100-slo.Objective)/100), // 0.001, without float noise
		"Windows": []window{{"5m"}, {"30m"}, {"1h"}, {"6h"}, {"3d"}},
		"Alerts": []alertRule{
			{Severity: "page", LongWin: "1h", ShortWin: "5m", Burn: 14.4, SecondLong: "6h", SecondShort: "30m", SecondBurn: 6},
			{Severity: "ticket", LongWin: "3d", ShortWin: "6h", Burn: 1},
		},
	}
	if err := t.Execute(os.Stdout, data); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
}

Pipe the output into promtool check rules /dev/stdin if you have Prometheus installed. Real generators add more — per-SLO metadata series, budget-remaining recording rules, OpenSLO parsing — but the core is this template.

Remember this#

  • Write SLO definitions, not rules; generate rules with Sloth, Pyrra, OpenSLO tooling or your vendor.
  • Keep definitions in the service repo and validate them in CI.
  • One SLO dashboard per service, led by budget remaining and burn rate.
  • Review quarterly: were users unhappy inside SLO, or happy outside it?

Try it#

  1. Run slogen.go. Add a latency SLO whose error query counts requests slower than 500 ms.
  2. Install Sloth and generate rules for the YAML above. Compare with your program’s output.
  3. Draft the agenda for a 30-minute quarterly SLO review for your team.

Check yourself#

  1. What does budgetingMethod: Timeslices mean in OpenSLO?
  2. Why validate SLO definitions in CI if the queries are syntactically correct?
  3. Which two questions does the quarterly review ask?
  4. Why delete CPU-based pages once SLO alerts exist?

Sources#

↑↓ navigate↵ openesc close

100% drag to pan · scroll or pinch to zoom · double-click to zoom in