Skip to content
devops/architect
19 sre-playbooks 01 01 sre playbooks & toil automation
0/7 read · lab 0/1
SRE RELIABILITY ENGINEERING
19 / 19 • SRE PLAYBOOKS & TOIL ELIMINATION

SRE Playbooks & Toil Automation

The best incident is the one that never pages you. Master LitmusChaos experiments to find failure modes before production does, automated OOMKill remediation runbooks, error budget burn-rate alerting, PagerDuty escalation policies, chaos game days, and blameless postmortem culture that actually improves reliability over time.

SLO + Alertmanager LitmusChaos + Auto-Remediation Chaos GameDay + Error Budget Policy

Lesson objective

What it teaches
SLO, SLI & Error Budget Enforcement · Auto-Remediation Runbooks · LitmusChaos: Production Readiness Testing · Measuring & Reducing Toil · Hands-On Labs · Troubleshooting · Predict the Result: Error-Budget Arithmetic
Why it matters
A required lesson for SRE, DevOps / Platform Architect. Recommended for Observability Engineer. See the role paths
What you demonstrate
  • Simulated lab: Track toil via PagerDuty API — how many alerts are "noisy" vs actionable. Recorded as lab evidence.
  • Predict 3 results this lesson prints. You mark each one yourself.
  • Optional, real environment: 8 hands-on tasks on your own machine or an external lab site (checklist). Not tracked as evidence.
  1. Orient
  2. Read
  3. Predict
  4. Run
  5. Verify
  6. Reflect
  7. Continue (not in this lesson)

 Real Postmortem: 47-Minute Payments Outage

Date: 2024-03-15 14:22 UTC  |  Impact: 100% payment failures, ~$280K revenue loss  |  Duration: 47 minutes

Time (UTC)Event
14:22Deploy payments-api v2.3.1 — Redis connection pool size reduced from 50→5 (misconfiguration)
14:24Redis connection exhaustion under normal load. Requests queue. P99 latency climbs to 15s.
14:26SLO error budget burn alert fires (1h window). PagerDuty pages on-call SRE.
14:31On-call SRE joins. Reviews Grafana. Sees Redis connection errors in logs. Suspects Redis cluster issue.
14:38Redis cluster scaled up (wrong fix). No improvement.
14:44Second SRE joins. Reviews deployment diff. Finds pool size change.
14:48Hotfix deployed. Connection pool restored to 50. Recovery begins.
15:09Full recovery confirmed. P99 back to 120ms.

Root Cause: Redis connection pool config was in a separate values file from the main chart. PR review missed it. No automated smoke test for connection pool behavior.

Action Items: (1) Add integration test verifying Redis connectivity under load. (2) Add config diff check in CI. (3) Implement canary deployment for payments-api (10% traffic first). (4) Build automated rollback on SLO breach.

SLO, SLI & Error Budget Enforcement 19.1

slo-payments-api.yaml (OpenSLO format)
apiVersion: openslo/v1
kind: SLO
metadata:
  name: payments-api-availability
  namespace: production
spec:
  service: payments-api
  description: "Payment API must be available 99.9% of the time"
  timeWindow:
    - duration: 30d
      isRolling: true
  indicator:
    metadata:
      name: payment-success-rate
    spec:
      ratioMetric:
        good:
          metricSource:
            type: Prometheus
            spec:
              query: |
                sum(rate(http_request_total{
                  service="payments-api",
                  status_code!~"5.."
                }[5m]))
        total:
          metricSource:
            type: Prometheus
            spec:
              query: |
                sum(rate(http_request_total{
                  service="payments-api"
                }[5m]))
  objectives:
    - target: 0.999         # 99.9% = 43.2 min/month error budget
      timeWindow: 30d

---
# Prometheus recording rules for SLO tracking
# In prometheus-rules.yaml:
# - record: slo:payments_availability:ratio_rate5m
#   expr: |
#     sum(rate(http_requests_total{job="payments-api",status!~"5.."}[5m]))
#     /
#     sum(rate(http_requests_total{job="payments-api"}[5m]))
burn-rate-alerting-rules.yaml
# Multi-window burn-rate alerting (Google SRE Workbook pattern)
# Catches fast burns early AND slow burns over time
groups:
  - name: payments-api-slo-alerts
    rules:
      # 1h window: burning 14x faster than budget allows
      # → pages immediately (fast burn = big incident)
      - alert: PaymentsSLOBurnRateFastHigh
        expr: |
          (
            1 - slo:payments_availability:ratio_rate1h
          ) / (1 - 0.999) > 14
        for: 2m
        labels:
          severity: critical
          team: payments
        annotations:
          summary: "Payments SLO burning 14x fast (1h window)"
          description: >
            Error budget consuming at 14x normal rate over 1h.
            At this rate, 30-day budget exhausted in {{ printf "%.1f" (30 / 14) }} days.
            Current error rate: {{ $value | humanizePercentage }}

      # 6h window: burning 6x — page but less urgently
      - alert: PaymentsSLOBurnRateMedium
        expr: |
          (
            1 - slo:payments_availability:ratio_rate6h
          ) / (1 - 0.999) > 6
        for: 15m
        labels:
          severity: warning
          team: payments

      # Both windows must fire to reduce false positives
      - alert: PaymentsSLOBurnRateFastConfirmed
        expr: |
          (
            (1 - slo:payments_availability:ratio_rate1h) / (1-0.999) > 14
            and
            (1 - slo:payments_availability:ratio_rate5m) / (1-0.999) > 14
          )
        for: 0m
        labels:
          severity: critical
          pagerduty: true
error-budget-policy.md
# Error Budget Policy — Payments Team
# Adopted: 2024-01-01 | Owner: Platform SRE Team

## Error Budget Thresholds and Actions

### Green (>50% budget remaining)
- Normal deployment velocity permitted
- Feature releases: up to 3 per week
- Risky changes: allowed with testing

### Yellow (25-50% remaining)
- Review all upcoming risky changes with SRE
- No infrastructure maintenance windows
- Increase release gate testing coverage

### Red (10-25% remaining)
- Feature deployments FROZEN
- Only bugfixes and reliability improvements
- Mandatory SRE review of every deployment
- Weekly error budget review meeting

### Critical (<10% remaining)
- All deployments BLOCKED (requires VP approval)
- War room activated to identify root cause
- Incident retrospective within 48h
- Error budget thaw only after reliability improvements shipped

## Automated Enforcement
The following CI gate checks error budget via API:
  curl https://sloth.monitoring.acme.com/api/v1/slo/payments-api \
    | jq '.errorBudgetPercent' | awk '{if($1<10) exit 1}'

Auto-Remediation Runbooks 19.2

oomkill-remediation-runbook.sh
#!/bin/bash
# Auto-remediation: OOMKill detected → increase memory limit by 25%
# Triggered by Alertmanager webhook → Lambda → this script runs in K8s Job
set -euo pipefail

NAMESPACE="${1:-production}"
DEPLOYMENT="${2:-}"
ALERT_THRESHOLD=3  # Only auto-remediate if OOMKilled > 3 times in 1h

if [[ -z "$DEPLOYMENT" ]]; then
  # Find deployments with recent OOMKills
  DEPLOYMENT=$(kubectl get pods -n "$NAMESPACE" \
    --field-selector=status.phase=Running \
    -o json | jq -r '
      .items[] |
      select(.status.containerStatuses[]?.lastState.terminated.reason == "OOMKilled") |
      .metadata.labels."app"
    ' | sort -u | head -1)
fi

echo "=== OOMKill Auto-Remediation: $DEPLOYMENT in $NAMESPACE ==="

# Count OOMKills in last hour
OOMKILL_COUNT=$(kubectl get events -n "$NAMESPACE" \
  --field-selector=reason=OOMKilling \
  --sort-by='.lastTimestamp' \
  -o json | \
  jq --arg app "$DEPLOYMENT" '
    .items[] |
    select(.involvedObject.name | test($app)) |
    select(.lastTimestamp > (now - 3600 | todate))
  ' | jq -s 'length')

echo "OOMKill count in last 1h: $OOMKILL_COUNT"

if [[ $OOMKILL_COUNT -lt $ALERT_THRESHOLD ]]; then
  echo "Below threshold ($ALERT_THRESHOLD). No auto-remediation."
  exit 0
fi

# Get current memory limit
CURRENT_LIMIT=$(kubectl get deployment "$DEPLOYMENT" -n "$NAMESPACE" \
  -o jsonpath='{.spec.template.spec.containers[0].resources.limits.memory}')

echo "Current memory limit: $CURRENT_LIMIT"

# Parse and increase by 25%
CURRENT_MI=$(echo "$CURRENT_LIMIT" | sed 's/Mi//')
NEW_MI=$(echo "scale=0; $CURRENT_MI * 1.25 / 1" | bc)
NEW_LIMIT="${NEW_MI}Mi"

echo "Increasing to: $NEW_LIMIT"

# Apply patch
kubectl patch deployment "$DEPLOYMENT" -n "$NAMESPACE" \
  --type='json' \
  -p="[{
    \"op\": \"replace\",
    \"path\": \"/spec/template/spec/containers/0/resources/limits/memory\",
    \"value\": \"${NEW_LIMIT}\"
  }]"

# Post remediation event to Slack
curl -s -X POST "$SLACK_WEBHOOK_URL" -H 'Content-type: application/json' \
  -d "{
    \"text\": \"🤖 *Auto-Remediation* | $DEPLOYMENT in $NAMESPACE\",
    \"attachments\": [{
      \"color\": \"#f59e0b\",
      \"fields\": [
        {\"title\": \"Action\", \"value\": \"Memory limit increased: $CURRENT_LIMIT → $NEW_LIMIT\"},
        {\"title\": \"OOMKill Count\", \"value\": \"$OOMKILL_COUNT in last 1h\"},
        {\"title\": \"Next Step\", \"value\": \"Review with VPA recommendation and open ticket to right-size properly\"}
      ]
    }]
  }"

echo "Auto-remediation complete. Deployment rolling update started."
disk-full-remediation.sh
#!/bin/bash
# Auto-remediation: node disk pressure → clean up unused images + logs
# Triggered when node hits 85% disk usage

NODE="${1:-}"
THRESHOLD=85

echo "=== Disk Pressure Auto-Remediation: $NODE ==="

# Check which node is at risk
if [[ -z "$NODE" ]]; then
  NODE=$(kubectl get nodes -o json | jq -r '
    .items[] |
    select(.status.conditions[] |
      select(.type == "DiskPressure" and .status == "True")
    ) | .metadata.name' | head -1)
fi

if [[ -z "$NODE" ]]; then
  echo "No node in DiskPressure state. Checking by usage..."
  NODE=$(kubectl top nodes --no-headers | \
    awk '{gsub(/%/,"",$5); if($5>'$THRESHOLD') print $1}' | head -1)
fi

echo "Target node: $NODE"

# Run safe unprivileged cleanup job on that specific node
# (Replaces unsafe privileged docker.sock with scoped log pruning & kubelet GC)
cat <
alertmanager-webhook-receiver.yaml
# Alertmanager routes alerts to webhook receivers
# which trigger automated runbooks
route:
  group_by: ['alertname', 'deployment', 'namespace']
  group_wait: 30s
  group_interval: 5m
  repeat_interval: 4h
  receiver: default-slack

  routes:
    # OOMKill alerts → auto-remediation first, then Slack
    - matchers:
        - alertname =~ "OOMKill.*"
      receiver: oomkill-remediation
      continue: true   # Also send to default-slack after

    # Disk pressure → auto-cleanup
    - matchers:
        - alertname = "NodeDiskPressure"
      receiver: disk-remediation

    # SLO burn → PagerDuty
    - matchers:
        - pagerduty = "true"
      receiver: pagerduty

receivers:
  - name: oomkill-remediation
    webhook_configs:
      - url: 'https://remediation-api.acme.internal/oomkill'
        send_resolved: false
        http_config:
          bearer_token_file: /var/run/secrets/remediation-token

  - name: disk-remediation
    webhook_configs:
      - url: 'https://remediation-api.acme.internal/disk-pressure'

  - name: pagerduty
    pagerduty_configs:
      - routing_key: '{{ secrets.PAGERDUTY_KEY }}'
        severity: '{{ .GroupLabels.severity }}'
        description: '{{ .CommonAnnotations.summary }}'

  - name: default-slack
    slack_configs:
      - api_url: 'https://hooks.slack.com/YOUR_WEBHOOK'
        channel: '#sre-alerts'
        title: '{{ .Status | toUpper }} {{ .GroupLabels.alertname }}'
        text: '{{ range .Alerts }}{{ .Annotations.description }}{{ end }}'
SECURITY ANALYSIS & HARDENED RUNBOOK

Production Host-Cleanup Security & Scoped Remediation

The legacy auto-remediation pattern of mounting the Docker daemon socket (/var/run/docker.sock) inside a privileged: true Kubernetes Job with hostPID: true introduces severe production risks. According to the Kubernetes Pod Security Standards and CIS Benchmark:

  • Full Host Takeover via Docker Socket: Any pod with access to docker.sock can spawn unconfined containers that mount the node root filesystem (-v /:/host), bypassing Kubernetes admission controllers, auditing, and RBAC to extract node TLS keys and secrets.
  • Namespace Escape via privileged: true: Privileged containers receive all Linux capabilities (including CAP_SYS_ADMIN) and unmasked /proc and /sys filesystems, allowing container breakout.
  • Secret Exposure via hostPID: true: Disabling PID namespace isolation lets the cleanup container inspect all processes running on the host, read unmasked environment variables from /proc/<pid>/environ (exposing database credentials of adjacent workloads), and send arbitrary signals.
  • Runtime Deprecation (Kubernetes 1.24+): Modern clusters utilize containerd or CRI-O via CRI. A job expecting /var/run/docker.sock fails immediately or leaves stale sockets exposed.

Upstream Declarative Standard: Official Kubernetes Node-pressure Eviction specifies that image garbage collection must be managed natively by the kubelet via KubeletConfiguration parameters (imageGCHighThresholdPercent: 80, imageGCLowThresholdPercent: 70, and evictionHard: {"nodefs.available": "10%"}). When out-of-band ephemeral log cleanup is required, run an unprivileged job with dry-run support that strictly targets rotated application files and verifies thresholds.

scoped-disk-remediation.sh
#!/usr/bin/env bash
# Scoped, non-privileged log rotation cleanup with dry-run protection
# Upstream Reference: Kubernetes Node-pressure Eviction Architecture (v1.28+)
# Assumptions: Linux host with standard POSIX tools; run within a least-privilege pod
set -euo pipefail

TARGET_DIR="${1:-/var/log/pods}"
THRESHOLD_PERCENT=85
DRY_RUN="${DRY_RUN:-true}"

if [[ "$*" == *"--dry-run"* ]]; then
  DRY_RUN="true"
fi

echo "=== Disk Pressure Triage & Remediation (DRY_RUN=$DRY_RUN) ==="

# Check filesystem capacity without root elevation
CURRENT_USAGE=$(df -P "$TARGET_DIR" 2>/dev/null | awk 'NR==2 {gsub(/%/,"",$5); print $5}')
if [[ -z "$CURRENT_USAGE" ]]; then
  echo "WARN: Target directory $TARGET_DIR unreadable or not mounted. Checking root mount..."
  CURRENT_USAGE=$(df -P / | awk 'NR==2 {gsub(/%/,"",$5); print $5}')
fi

echo "Current filesystem utilization: ${CURRENT_USAGE}% (Threshold: ${THRESHOLD_PERCENT}%)"

if [[ "$CURRENT_USAGE" -lt "$THRESHOLD_PERCENT" ]]; then
  echo "Disk utilization is within normal bounds. No cleanup required."
  exit 0
fi

# Locate only rotated archived logs (*.log.gz or *.log.*.gz or *.1) older than 24 hours.
# NEVER delete active application *.log descriptors or system journals.
CANDIDATE_FILES=$(find "$TARGET_DIR" -type f \( -name "*.log.gz" -o -name "*.log.*.gz" -o -name "*.1" \) -mtime +1 2>/dev/null || true)

if [[ -z "$CANDIDATE_FILES" ]]; then
  echo "No stale archived log files found to reclaim."
  exit 0
fi

RECLAIMABLE_BYTES=$(du -cb $CANDIDATE_FILES 2>/dev/null | awk 'END {print $1}')
echo "Identified $(echo "$CANDIDATE_FILES" | wc -l) candidate files totaling $RECLAIMABLE_BYTES bytes."

if [[ "$DRY_RUN" == "true" ]]; then
  echo "[DRY-RUN] Candidate files for pruning:"
  echo "$CANDIDATE_FILES" | head -n 5
  echo "[DRY-RUN] Planned action: would unlink candidate archives. Set DRY_RUN=false to execute."
  exit 0
fi

echo "Executing safe unprivileged purge of rotated archives..."
while IFS= read -r file; do
  [[ -f "$file" ]] && rm -f "$file"
done <<< "$CANDIDATE_FILES"

NEW_USAGE=$(df -P "$TARGET_DIR" 2>/dev/null | awk 'NR==2 {gsub(/%/,"",$5); print $5}')
echo "Cleanup complete. New filesystem utilization: ${NEW_USAGE}%"

LitmusChaos: Production Readiness Testing 19.3

The only way to know your system handles failures is to deliberately inject them before production does. LitmusChaos is a CNCF project that runs chaos experiments as Kubernetes CRDs — pod kills, network delays, CPU hogs, and disk pressure.

chaos-pod-delete.yaml
apiVersion: litmuschaos.io/v1alpha1
kind: ChaosEngine
metadata:
  name: payments-pod-delete
  namespace: production
spec:
  appinfo:
    appns: production
    applabel: "app=payments-api"
    appkind: deployment
  # Chaos will stop if SLO is violated
  jobCleanUpPolicy: delete
  monitoring: true
  annotationCheck: 'false'
  engineState: 'active'
  experiments:
    - name: pod-delete
      spec:
        components:
          env:
            # Kill 1 pod every 30s for 5 minutes
            - name: TOTAL_CHAOS_DURATION
              value: "300"
            - name: CHAOS_INTERVAL
              value: "30"
            # Kill 30% of pods (not all at once)
            - name: FORCE
              value: "false"
            - name: PODS_AFFECTED_PERC
              value: "30"
        probe:
          # Abort chaos if SLO drops below 99%
          - name: payments-availability-probe
            type: promProbe
            promProbe/inputs:
              endpoint: http://prometheus.monitoring.svc.cluster.local:9090
              query: |
                sum(rate(http_request_total{service="payments-api",status!~"5.."}[1m]))
                /
                sum(rate(http_request_total{service="payments-api"}[1m]))
            mode: Continuous
            runProperties:
              probeTimeout: 5
              interval: 5
              retry: 1
            comparator:
              type: float
              criteria: ">="
              value: "0.99"   # Abort if availability drops below 99%
chaos-network-latency.yaml
apiVersion: litmuschaos.io/v1alpha1
kind: ChaosEngine
metadata:
  name: inventory-network-latency
  namespace: production
spec:
  appinfo:
    appns: production
    applabel: "app=inventory-service"
    appkind: deployment
  experiments:
    - name: pod-network-latency
      spec:
        components:
          env:
            # Add 500ms latency to simulate degraded upstream
            - name: NETWORK_LATENCY
              value: "500"    # milliseconds
            - name: JITTER
              value: "50"     # ±50ms jitter
            # Only affect traffic to specific destination
            - name: DESTINATION_IPS
              value: "10.0.0.0/8"
            - name: TOTAL_CHAOS_DURATION
              value: "180"
            - name: PODS_AFFECTED_PERC
              value: "50"
        probe:
          # Expect circuit breaker to open → verify fallback works
          - name: fallback-working
            type: httpProbe
            httpProbe/inputs:
              url: https://checkout.acme.com/health
              insecureSkipVerify: false
              responseTimeout: 2000
              method:
                get:
                  criteria: ==
                  responseCode: "200"
            mode: Continuous
            runProperties:
              probeTimeout: 2
              interval: 5
              retry: 1
chaos-cpu-stress.yaml
apiVersion: litmuschaos.io/v1alpha1
kind: ChaosEngine
metadata:
  name: payments-cpu-stress
  namespace: production
spec:
  appinfo:
    appns: production
    applabel: "app=payments-api"
    appkind: deployment
  experiments:
    - name: pod-cpu-hog
      spec:
        components:
          env:
            # Consume 80% of CPU limit for 2 minutes
            - name: CPU_CORES
              value: "0"        # 0 = use % of request
            - name: CPU_LOAD
              value: "80"       # 80% CPU load
            - name: TOTAL_CHAOS_DURATION
              value: "120"
            - name: PODS_AFFECTED_PERC
              value: "50"
        probe:
          # HPA should scale out — verify it does
          - name: hpa-scale-check
            type: k8sProbe
            k8sProbe/inputs:
              group: autoscaling
              version: v2
              resource: horizontalpodautoscalers
              namespace: production
              resourceNames: "payments-api"
              operation: present
            mode: OnChaos
            runProperties:
              probeTimeout: 5
              interval: 10
              retry: 3
chaos-gameday-runbook.md
# Chaos Game Day Runbook — Payments Platform
# Frequency: Monthly | Duration: 3h | Owner: Platform SRE

## Pre-Game Day Checklist
- [ ] Notify all teams in #engineering Slack channel (3 days before)
- [ ] Confirm on-call rotations are staffed
- [ ] Verify Grafana dashboards are accessible
- [ ] Document current SLO baseline and error budget
- [ ] Confirm rollback procedures are documented
- [ ] Get product owner approval for traffic reduction

## Game Day Agenda (All Times UTC)

### 14:00 — Kick-off
- Confirm participant attendance (Zoom call)
- Review today's scenarios and abort conditions
- Verify monitoring is working (send test alert)

### 14:15 — Scenario 1: Pod Delete (Low Risk)
- Run: pod-delete chaos on payments-api (30% pods, 5 min)
- Observe: HPA response time, alert firing, PDB protection
- Expected: no SLO impact, HPA scales within 2 min
- Abort if: error rate > 1% for > 30 seconds

### 14:45 — Scenario 2: Network Latency (Medium Risk)
- Run: 500ms latency on inventory-service calls
- Observe: circuit breaker trip, fallback behavior
- Expected: checkout continues with degraded inventory check
- Abort if: checkout error rate > 5%

### 15:15 — Scenario 3: AZ Failure Simulation (High Risk)
- Cordon all nodes in us-east-1a
- Drain workloads to remaining AZs
- Observe: anti-affinity rules, cross-AZ traffic
- Abort if: total service downtime > 2 minutes

### 15:45 — Review & Retrospective
- Document findings per scenario
- Identify gaps in alerting
- Create reliability improvement tickets
- Update runbooks with learnings

## Abort Criteria (Any of these = stop immediately)
- SLO error budget consumes > 20% of monthly budget
- Customer-visible error rate > 2% for > 60 seconds
- On-call team loses control of incident
CHAOS RESILIENCE VERIFICATION

Multi-AZ Outage: LitmusChaos Experiment & Blast-Radius Control

A true disaster recovery drill tests the failure of an entire Availability Zone (AZ) to ensure cross-zone traffic failover and anti-affinity scheduling protect customer SLOs. According to the LitmusChaos 3.x Documentation, chaos experiments targeting infrastructure nodes must include blast-radius constraints, automatic rollback reconciliation, and continuous Prometheus abort probes.

chaos-az-failure.yaml (LitmusChaos CRD)
apiVersion: litmuschaos.io/v1alpha1
kind: ChaosEngine
metadata:
  name: payments-az-failure-drill
  namespace: production
spec:
  appinfo:
    appns: production
    applabel: "app=payments-api"
    appkind: deployment
  jobCleanUpPolicy: retain
  monitoring: true
  annotationCheck: 'false'
  engineState: 'active'
  experiments:
    - name: node-drain
      spec:
        components:
          env:
            - name: TARGET_ZONE
              value: "us-east-1a"
            - name: NODES_AFFECTED_PERC
              value: "33"
            - name: TOTAL_CHAOS_DURATION
              value: "300"
            - name: DRAIN_TIMEOUT
              value: "180"
            - name: FORCE
              value: "false"
        probe:
          - name: multi-az-availability-slo
            type: promProbe
            promProbe/inputs:
              endpoint: http://prometheus.monitoring.svc.cluster.local:9090
              query: |
                sum(rate(http_requests_total{job="payments-api",status!~"5.."}[1m]))
                /
                sum(rate(http_requests_total{job="payments-api"}[1m]))
            mode: Continuous
            runProperties:
              probeTimeout: 5
              interval: 5
              retry: 1
            comparator:
              type: float
              criteria: ">="
              value: "0.995"
          - name: remaining-zones-health
            type: httpProbe
            httpProbe/inputs:
              url: https://payments.acme.internal/healthz
              insecureSkipVerify: false
              responseTimeout: 1500
              method:
                get:
                  criteria: ==
                  responseCode: "200"
            mode: Continuous
            runProperties:
              probeTimeout: 2
              interval: 4
              retry: 2

Recovery & Blast-Radius Guardrails: The experiment drains nodes in us-east-1a while respecting Kubernetes PodDisruptionBudgets (PDBs). If the availability SLI across remaining zones drops below 99.5%, Litmus aborts the drill immediately.

simulated-az-failure-timeline.txt (Labeled Simulation)
SIMULATED EXPERIMENT RUN (OFFLINE - NOT RUN LIVE)
Prerequisites: Multi-AZ EKS cluster (us-east-1a, us-east-1b, us-east-1c) with topology spread constraints.
Target: Cordon and drain worker nodes labeled topology.kubernetes.io/zone=us-east-1a.

[T+00:00] Pre-flight Check: All 3 Availability Zones Healthy (18/18 nodes Ready).
[T+00:15] Probe Baseline: Availability SLI = 99.98%, P99 Latency = 48ms.
[T+00:30] Chaos Injected: Cordon applied to 6 nodes in us-east-1a (SchedulingDisabled).
[T+01:00] Eviction Started: Pod eviction initiated with 180s drain timeout.
[T+01:45] Traffic Shift: AWS ALB detects target unhealth in us-east-1a; shifts traffic to us-east-1b/c.
[T+02:15] Continuous Probe Check: promProbe query result = 0.9982 (Criteria >= 0.995 PASS).
[T+02:30] Continuous Probe Check: httpProbe https://payments.acme.internal/healthz (200 OK PASS).
[T+05:00] Chaos Duration (300s) Expired: Initiating automated post-chaos reconciliation.
[T+05:15] Recovery Step: Executing kubectl uncordon -l topology.kubernetes.io/zone=us-east-1a
[T+06:00] Post-Chaos Verification: Nodes in us-east-1a returned to Ready/Schedulable.
[T+06:30] Workload Balance: Descheduler rebalances deployment replicas evenly across all 3 AZs.
[T+07:00] Drill Result: SUCCESS. 0 customer errors; availability SLI preserved above 99.5%.

Measuring & Reducing Toil 19.4

What Counts as Toil

  • Manual, repetitive operational work
  • Running the same script every deploy
  • Manually scaling resources reactively
  • Copy-pasting secrets between systems
  • Answering the same ticket type >2x/week
  • Manually rotating SSL certificates
  • Clicking through consoles to check status

Toil Elimination Targets

  • Google SRE target: <50% time on toil
  • Track toil weekly in team retrospectives
  • Automate any task done >2x identical
  • Self-service > ticket for all dev requests
  • Auto-cert renewal via cert-manager
  • Auto-scaling replacing manual scaling
  • Runbook automation via SSM/Lambda
# Track toil via PagerDuty API — how many alerts are "noisy" vs actionable
$ curl -H "Authorization: Token token=$PD_TOKEN" \
  "https://api.pagerduty.com/incidents?time_zone=UTC&since=2024-01-01&until=2024-02-01&limit=100" \
  | jq '.incidents[] | {
      service: .service.summary,
      resolved_by: .resolved_by_user.summary,
      duration_min: ((.last_status_change_at | fromdateiso8601) -
                     (.created_at | fromdateiso8601)) / 60 | round,
      acknowledged: (.acknowledgements | length)
    }' | jq -s 'group_by(.service) | .[] | {
      service: .[0].service,
      total_pages: length,
      avg_duration_min: ([.[].duration_min] | add / length | round)
    }'
{
  "service": "payments-api",
  "total_pages": 47,
  "avg_duration_min": 12
}
← 47 pages in 1 month = investigate noisy alert or recurring bug
TOIL PRIORITIZATION FRAMEWORK

Worked Toil Dataset: Prioritizing Automation by ROI & Risk

According to the Google SRE Book (Chapter 5), operational teams must cap toil at 50% of their engineering time. However, blindly automating every manual task is inefficient: engineering effort must be prioritized based on annual recurrence, engineering effort to automate, and operational blast-radius risk.

Task Name Recurrence Annual Hours Automation Effort Risk Profile Calculated ROI Score
Task A: Manual TLS Cert Renewal 2 hrs / 2 weeks 52 hrs/yr 24 hrs (3 days) Low (1.0x) - Idempotent cert-manager 2.17
Task B: DB Replica Throttle Tuning 1 hr / day 250 hrs/yr 120 hrs (3 wks) High (2.5x) - Primary DB starvation risk 0.83
Task C: Runner Disk Pruning 0.5 hr / 2x wk 52 hrs/yr 4 hrs (0.5 day) Very Low (1.0x) - Scoped ephemeral test runners 13.00
Task D: User SCIM / SSO Sync 4 hrs / week 208 hrs/yr 80 hrs (2 wks) Medium (1.5x) - Access permission boundaries 1.73

Scoring Methodology & Justified Ranking: ROI Score = Annual Hours Saved / (Effort Hours × Risk Multiplier).

  • Rank 1: Task C (Runner Disk Cleanup) [Score: 13.00]: Outstanding quick win. At just 4 hours of development for a scoped cron/timer, it pays for itself in less than 4 weeks with negligible operational risk.
  • Rank 2: Task A (Manual TLS Cert Renewal) [Score: 2.17]: High reliability payoff and fast return. Automating via cert-manager permanently eliminates catastrophic Sev-1 certificate expiration outages for low effort.
  • Rank 3: Task D (User Account SCIM / SSO Sync) [Score: 1.73, 208 hrs eliminated]: High absolute volume of recurring toil (>26 workdays per year), but requires 2 weeks of engineering effort and identity boundary integration.
  • Rank 4: Task B (DB Replica Throttle Tuning) [Score: 0.83]: Defer automation. Despite high recurring hours, automating production database throttling carries a severe blast radius (risk of query drops or cascade failures). The system should first be redesigned with query caching, proper indexes, or connection pooling before attempting dynamic automation.

Critical SRE Caveats:

  • Caveat 1: Automation Maintenance Burden: Automations are software that must be monitored, patched, and tested against upstream API changes. Low-frequency tasks (<10 hrs/yr) rarely justify the ongoing maintenance overhead.
  • Caveat 2: Risk of Automated Disaster: Automating a high-risk manual procedure without abort probes, rate limiting, and circuit breakers converts occasional human errors into instant, high-speed outages.
  • Caveat 3: Simplify Before Automating: Never automate an unnecessary process. If database replicas lag daily, fix the indexing or query patterns first rather than writing auto-throttling daemons.
toil-priority-calculator.mjs
// Deterministic Toil Priority Ranking Calculator
// Formula: ROI = Annual_Saved_Hours / (Effort_Hours * Risk_Factor)
const dataset = [
  { id: 'Task A', name: 'Manual TLS Cert Renewal', savedHoursPerYear: 52, effortHours: 24, riskWeight: 1.0 },
  { id: 'Task B', name: 'DB Replica Throttle Tuning', savedHoursPerYear: 250, effortHours: 120, riskWeight: 2.5 },
  { id: 'Task C', name: 'Runner Disk Pruning', savedHoursPerYear: 52, effortHours: 4, riskWeight: 1.0 },
  { id: 'Task D', name: 'User SCIM / SSO Sync', savedHoursPerYear: 208, effortHours: 80, riskWeight: 1.5 }
];

const scored = dataset.map(task => {
  const adjustedCost = task.effortHours * task.riskWeight;
  const score = Number((task.savedHoursPerYear / adjustedCost).toFixed(2));
  return { ...task, score };
});

// Rank descending by ROI score; break ties by absolute saved hours
scored.sort((a, b) => b.score - a.score || b.savedHoursPerYear - a.savedHoursPerYear);

// Expose to sandbox / test assertion
if (typeof results !== 'undefined') {
  results = scored;
}

Hands-On Labs 19.5

SRE Reliability Labs

  • Define SLO for a sample service using OpenSLO spec, implement recording rules in Prometheus
  • Configure multi-window burn-rate alerting (1h 14x + 6h 6x) in Alertmanager
  • Install LitmusChaos on kind, run pod-delete experiment on a sample deployment
  • Write OOMKill auto-remediation script and test it by manually creating OOM conditions
  • Configure Alertmanager webhook route that calls a remediation endpoint for OOMKill alerts
  • Write a complete blameless postmortem for the Redis connection pool incident (use template)
  • Plan and document a Chaos Game Day agenda for a 3-service system with clear abort criteria
  • Track your own toil for 1 week — log every manual task and identify top 3 automation opportunities

Troubleshooting 19.6

Burn-rate alert firing too frequently (noisy)

Use the two-window approach: both the fast (1h) and slow (6h) windows must fire simultaneously. Add a for: 2m to avoid transient spikes. Review your SLI query — if it includes health checks or internal traffic, exclude them. Use job_name != "blackbox-health" filters.

LitmusChaos experiment not starting

Check: (1) The target pod has the correct label matching applabel in ChaosEngine. (2) ChaosServiceAccount has RBAC permissions to delete pods. (3) annotationCheck: 'false' — if true, pods need litmuschaos.io/chaos: "true" annotation. Check ChaosEngine status: kubectl describe chaosengine <name> -n <ns>.

Auto-remediation causing flapping

Add a cooldown period — track last remediation timestamp in a ConfigMap or DynamoDB table. Only trigger remediation if last run was >30 minutes ago. Cap auto-escalation: allow max 2 automatic increases, then create a Jira ticket for human review. Always Slack-notify with a clear "MANUAL ACTION REQUIRED IF PERSISTS" message.

Predict the Result: Error-Budget Arithmetic 19.7

Recorded from a real run of scripts/recordings/sre-playbooks.sh; every output below is pasted from scripts/recordings/sre-playbooks.out. Cover the output, predict it, then compare.

Environment: mawk 1.3.4 on Linux. A 30-day window is 30 × 24 × 60 = 43,200 minutes.

recorded run
# Minutes of full outage a 99.9% SLO allows in 30 days
$ awk 'BEGIN { printf "%.1f\n", (1 - 0.999) * 30 * 24 * 60 }'
43.2

# The same for 99.95%
$ awk 'BEGIN { printf "%.1f\n", (1 - 0.9995) * 30 * 24 * 60 }'
21.6

# Burn rate when 0.5% of requests fail against a 99.9% SLO
$ awk 'BEGIN { printf "%.1f\n", 0.005 / (1 - 0.999) }'
5.0

# Hours until a 30-day budget is gone at burn rate 14.4
$ awk 'BEGIN { printf "%.1f\n", 30 * 24 / 14.4 }'
50.0

Burn rate is the error rate divided by the error budget. At 1 the budget lasts exactly the window; at 14.4 a 30-day budget is gone in 50 hours, and 2% of it in one hour, which is why fast-burn pages commonly use 14.4 over 1 hour. Each extra nine halves or more the minutes you have to detect and mitigate.

Predict: results this lesson prints

Write what you expect, then compare with the lesson. You mark each result yourself; it is recorded as predict evidence.

What result does the lesson show for this command?

$ awk 'BEGIN { printf "%.1f\n", (1 - 0.999) * 30 * 24 * 60 }'
Show the lesson's result

The lesson shows:

43.2

What result does the lesson show for this command?

$ awk 'BEGIN { printf "%.1f\n", (1 - 0.9995) * 30 * 24 * 60 }'
Show the lesson's result

The lesson shows:

21.6

What result does the lesson show for this command?

$ awk 'BEGIN { printf "%.1f\n", 0.005 / (1 - 0.999) }'
Show the lesson's result

The lesson shows:

5.0

Practice: troubleshoot and decide

Commit to an answer before each result is shown. Finishing a drill or a decision is recorded as evidence for the sections it builds on.

Troubleshooting drill

The on-call deleted a 16 MB log. The disk is still 100 percent full.

Output recorded from a real run on alpine:3.20 container on Docker Desktop, run from Git Bash on Windows. The node's log volume is a 16 MB tmpfs at /var/log/app; a busybox shell loop stands in for the checkout app, keeps app.log open in append mode and writes about 1 MB of log lines per second. Process ids and descriptor numbers vary per run. Nothing runs on your machine.

Builds on Auto-Remediation Runbooks, Troubleshooting.

At 03:12 checkout health checks start failing on one node and writes to /var/log/app fail with "No space left on device". The on-call engineer finds a 16 MB app.log, deletes it, and expects the alert to clear. It does not: df still shows the volume 100 percent full, while du says the directory is empty.

  1. Step 1 of 3: The volume is full. What do you confirm before deleting anything?

Design decision

OOMKilled again: raise the memory limit automatically, or send it to a human?

Builds on Auto-Remediation Runbooks, Troubleshooting.

The auto-remediation runbook raises a Deployment's memory limit by 25% after repeated OOMKills and posts to Slack. Over one quarter the orders service grew from 512Mi to 3Gi through automatic raises. Its memory had been climbing since a release three months earlier, and last week the node ran out of memory and evicted other pods.

Constraints

  • An OOMKill loop at night must not page anyone when a safe automatic action exists
  • A memory leak must reach the owning team within one working day
  • Automation must never grow a limit without bound
  • Two SREs; the fix must not add a stream of manual tickets
Which do you choose?

Lab: simulated terminal, nothing runs on your machine

Simulated nothing runs on your machine

  1. 1 Track toil via PagerDuty API — how many alerts are "noisy" vs actionable
Track toil via PagerDuty API — how many alerts are "noisy" vs actionable

Ready. Type the command for the current goal.

Check yourself

An SLO burn-rate alert fires too frequently on transient spikes and noisy alerts. Which remediation strategy does the lesson recommend?

Explanation

In 'Troubleshooting 19.6', 'Burn-rate alert firing too frequently (noisy)' recommends adopting the two-window approach where both fast (1h) and slow (6h) burn windows must fire simultaneously, adding 'for: 2m' to smooth transient spikes.

Why is running auto-remediation host cleanup by mounting docker.sock into a privileged Kubernetes Job dangerous in production?

Explanation

In 'Production Host-Cleanup Security & Scoped Remediation', mounting '/var/run/docker.sock' in a privileged pod allows containers to mount the node root filesystem ('-v /:/host'), bypassing admission controllers, auditing, and RBAC to compromise node keys and secrets.

According to Google SRE principles described in the lesson, what is the maximum percentage of engineering time that should be spent on operational toil?

Explanation

In 'Measuring & Reducing Toil 19.4', 'Toil Elimination Targets' specifies the Google SRE target of less than 50% time spent on toil, tracking toil weekly in retrospectives and redirecting recovered engineering time to systemic reliability work.

When running a Multi-AZ outage chaos experiment with LitmusChaos, what safeguards must be configured to protect customer SLOs?

Explanation

In 'Multi-AZ Outage: LitmusChaos Experiment & Blast-Radius Control', experiments targeting infrastructure nodes must include blast-radius constraints, automatic rollback reconciliation, and continuous Prometheus abort probes to prevent cascading SLO failures.

What is an Error Budget in site reliability engineering?

The allowable percentage of unreliable service (100% minus SLO target) during a specified rolling time window.

Space flips the current card.

Capability coverage: L1, L2, L3 covered

No lesson evidence yet. Start reading this lesson, then run its free lab to record demonstrated checks.

Each cell counts this lesson's sections for that skill and level. Complete needs a demonstrated check (today only the lab); reading a section shows Developing. Not covered means the lesson has no material there.

Skills by experience level for this lesson
SkillL1 FoundationL2 PractitionerL3 ProductionL4 Architect
Understand Missing · 1 section Not covered Not covered Not covered
Operate Not covered Missing · 1 section Not covered Not covered
Troubleshoot Not covered Not covered Missing · 3 sections Not covered
Automate Not covered Not covered Missing · 2 sections Not covered
Secure Not covered Not covered Not covered Not covered
Observe Not covered Not covered Missing · 1 section Not covered
Design Not covered Not covered Not covered Not covered
Make trade-offs Not covered Not covered Missing · 1 section Not covered

How this lesson fits each role