Workflow: Experiments With a Way to Stop

The Experiment

Chaos engineering is the scientific method applied to a running system:

StepWhat it isIn the lab
Steady statewhat “working” looks like, measured from outsidea probe through the backend’s Service: every request 200
Hypothesisa prediction, written before the fault - what users will see, for how long“requests fail for less than 30 seconds, then all succeed; no alert fires”
One faulta single, chosen failure - one at a time, or you cannot tell what caused whatthe only backend pod in develop deleted
Measurethe same probe, during and afterthe failures with their times: the outage, in seconds
Stop conditionwhen you stop early - decided in advancethe outage passes the hypothesis twice over, or anything outside develop changes
Compareas predicted, or a findinga hardening action either way

The prediction is the point. “It recovered” is not a result; “it recovered in 9 seconds, and we expected under 30” is.

Measure Users, Not Pods

kubectl get pods says a new pod exists. It does not say whether requests succeeded while it started. Neither does the absence of an alert. In this lab’s case none of the backend’s alerts can fire. The probe’s requests to /version are user requests, so develop is above the error-budget rules’ traffic floor while it runs - but its failures are 000: connections that never reach a backend, so the backend counts no 5xx and the error ratio stays empty. And BackendNoReadyPods needs two minutes without an available replica (Chapter 11); the outage lasts seconds. With real traffic, a short burst of 5xx can fire BackendErrorBudgetBurnFast, if its windows stay above the threshold for the rule’s hold time - the probe measures users either way.

The probe is a pod that sends a request to the backend’s Service five times a second and prints every failure with its time, and the first success after them (back) - from a pod the network policies let in (-l app=frontend, Chapter 06). It runs before the fault (the steady state), during it and after it, and ends with a count. Independent of the thing it measures: it does not ask Kubernetes how things are, it asks the service.

What a Pod Deletion Tests - and What It Does Not

Safety netTested by kubectl delete pod?Why
ReplicaSetyesthe Deployment’s ReplicaSet sees one pod missing and creates a replacement - this is what recovers
Readiness probeyesthe Service sends traffic to the new pod only once it is Ready - the end of the outage
PodDisruptionBudgetnoa PDB guards voluntary evictions through the Eviction API (kubectl drain); a plain delete goes around it
HPAnothe HPA scales on load, not on a missing pod - and in develop its minimum and maximum are both 1

So this experiment is about recovery from losing a pod. Disruption budgets and autoscaling were tested where they belong, in Chapter 09 - an eviction against a budget, an HPA scaling a busy Deployment. With one replica, an outage is expected: the question is how long, and whether that is acceptable.

The Monkey and Its Limits

A Chaos Monkey turns one deliberate fault into a recurring, random one: a CronJob that deletes one random frontend or backend pod in develop per run. Random faults find what nobody thought to test - but only once the deliberate one is understood, and only with limits the tool cannot override.

The Chaos Monkey

Show cronjob.yaml
---
                  set -- ${TARGET_APPS}
                  count="$#"
                  [ "$count" -gt 0 ] || skip "no target apps configured"
                  index="$(awk -v n="$count" 'BEGIN{srand(); print int(rand()*n)+1}')"
                  eval "app=\${$index}"

                  pods="$(kubectl -n "${TARGET_NAMESPACE}" get pods -l "app=${app}" --field-selector=status.phase=Running -o jsonpath='{range .items[*]}{.metadata.name}{"\n"}{end}')"
                  target="$(printf '%s\n' "$pods" | awk 'NF {a[++n]=$0} END {if (n>0) {srand(); print a[int(rand()*n)+1]}}')"
                  [ -n "${target}" ] || skip "no running pod for app=${app}"

                  ts="$(date -u +%Y-%m-%dT%H:%M:%SZ)"
                  echo "{\"event\":\"chaos_monkey_delete_pod\",\"timestamp\":\"${ts}\",\"namespace\":\"${TARGET_NAMESPACE}\",\"app\":\"${app}\",\"pod\":\"${target}\"}"
                  kubectl -n "${TARGET_NAMESPACE}" delete pod "${target}" --wait=false
              resources:
                requests:
                  cpu: 10m
                  memory: 32Mi
                  ephemeral-storage: 64Mi
                limits:
                  cpu: 100m
                  memory: 128Mi
                  ephemeral-storage: 128Mi
              volumeMounts:
                - name: tmp
                  mountPath: /tmp
          volumes:
            - name: tmp
              emptyDir:
                sizeLimit: 16Mi

Where it lives, what it touches. The CronJob and its ServiceAccount are in flux-system, the platform’s own namespace; the apps in develop hold no API credentials at all (their pods set automountServiceAccountToken: false, Chapter 07). What the monkey may do comes from the RoleBinding chaos-monkey in develop: it gives that ServiceAccount the Role chaos-monkey - get, list and delete pods - in develop and nowhere else. The identity that acts and the blast radius it acts on are separate on purpose.

LimitEnforced byWhat it stops
Off unless someone turns it onsuspend: true in Git; Flux sets it backa forgotten schedule
develop onlyRBAC - the Role exists in develop and nowhere elsea run in staging or production
Frontend and backend onlythe admission policy chaos-monkey-targetsthe database, or anything else in develop - RBAC cannot select by label
Weekdays, inside a UTC windowthe script; a skip is logged as chaos_monkey_skip with its reasonfaults at night or at the weekend, when nobody watches
One pod per Jobthe script picks oneseveral faults in one run
Scheduled runs never overlapconcurrencyPolicy: Forbid - for Jobs the schedule creates; a Job created by hand from the CronJob is not serialized, so run manual Jobs one after anotherseveral faults at once

The admission policy that limits the targets

Show target-guard.yaml
---
# RBAC cannot select by label: the Role lets the chaos-monkey ServiceAccount delete ANY pod in
# develop - app-postgres-1 included. The script picks only frontend and backend, but a script is an
# instruction, not a guardrail. This policy is the guardrail: a pod deletion by that ServiceAccount
# is refused unless the pod is labelled app=frontend or app=backend. Native ValidatingAdmissionPolicy
# (GA since Kubernetes 1.30), Deny from the start - like oidc-flux-operator-fields.
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingAdmissionPolicy
metadata:
  name: chaos-monkey-targets
spec:
  failurePolicy: Fail
  matchConstraints:
    resourceRules:
      - apiGroups: [""]
        apiVersions: ["v1"]
        operations: ["DELETE"]
        resources: ["pods"]
  matchConditions:
    - name: chaos-monkey
      expression: "request.userInfo.username == 'system:serviceaccount:flux-system:chaos-monkey'"
  validations:
    # On DELETE the pod being deleted is oldObject (object is null).
    - expression: >-
        has(oldObject.metadata.labels) && 'app' in oldObject.metadata.labels
        && oldObject.metadata.labels['app'] in ['frontend', 'backend']
      message: "chaos-monkey may delete only frontend and backend pods"
---
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingAdmissionPolicyBinding
metadata:
  name: chaos-monkey-targets
spec:
  policyName: chaos-monkey-targets
  validationActions: [Deny]

The script’s own checks - the window, one pod - are instructions to itself; the RBAC and the admission policy hold even if the script is changed. That is the difference between the story and the platform.

A run outside the window is not a failed run. It logs {"event":"chaos_monkey_skip","reason":"outside 10-16 UTC"} and deletes nothing. There is no override: a manual run obeys the same window. When the window is closed, the deliberate experiment - which you run by hand, with a hypothesis - is the one to do.

Known tech debt. The monkey needs a shell, awk and kubectl; the official kubectl image has no shell. It uses the community image alpine/k8s, pinned by digest - outside the platform’s trusted registries, so the Kyverno policy require-trusted-registries-audit reports it. A signed image of the platform’s own is the fix (Chapter 17).

Stopping: Suspend Is Not Enough

suspend: true stops future runs. A Job that has started goes on. The full stop:

  1. Suspend the CronJob - set suspend: true, do not just read it. Git says the same, so Flux keeps it there.
  2. Delete the active Job - its pod goes with it.
  3. Check that no Job and no pod of the monkey is left.
  4. Check the service - with the probe. Stopping the tool does not bring back the pod it already deleted; the ReplicaSet does.

Time to Detect, Time to Recover

For an experiment you caused, the injection time T0 is known exactly. From the probe’s output:

  • Time to detect = first failed request − T0 - how fast users felt it. For an alert-driven drill: the alert’s firing time − T0.
  • Time to recover = the first successful request after the failures − T0 - when users were served again.
  • Outage = that first success − the first failed request.

Averaged over many drills these become MTTD and MTTR. One drill gives one honest number.

Guardrails That Stop It

  • The monkey’s targets (admission policy) - only frontend and backend pods, whatever the script says.
  • The monkey’s namespace (RBAC) - develop only.
  • Off by default (Git + Flux) - suspend: true; turning it on is a change someone made and Flux reverts.
  • The window (script) - weekdays, inside the UTC hours; every skip says why.
  • One fault, written hypothesis, probe (instruction, runbook) - what makes it an experiment.

Safe Workflow (Step-by-Step)

  1. Steady state - run the probe without a fault: all requests succeed.
  2. Hypothesis and stop condition - written down before anything breaks.
  3. One fault - note T0 in UTC.
  4. Measure - the probe during and after; the Kubernetes events for the replacement.
  5. Stop fully - suspend, delete the active Job, check, probe again.
  6. Compare and record - the scorecard; one hardening action, or “as predicted” with the numbers.

Instructions for Your AI Agent

The rules this chapter adds:

  1. Never run a chaos experiment outside develop, and never without a written hypothesis, a probe of the service and a stop condition. Enforced by: RBAC - the monkey’s Role exists in develop only; the rest - instruction only.
  2. Never widen the monkey’s targets, window or schedule outside Git, and never unsuspend it for longer than one run. Enforced by: Flux reverts changes made outside Git, and the admission policy chaos-monkey-targets holds the targets; keeping it unsuspended for one run only - instruction only.
  3. To stop an experiment, suspend the CronJob and delete its active Job - suspend alone stops only future runs. Enforced by: instruction only.

This builds on: Backup & Restore (Chapter 12) - a restore you have proven is what makes breaking things on purpose acceptable. This enables: AI-Assisted SRE Guardian (Chapter 14) - the Guardian sees routed alerts, Kubernetes Warning events and its own scanners’ findings. A short drill like B2 may leave no trace there at all; a longer one reaches it like a real fault - nothing marks it as a drill, so you read its incident knowing what you caused.