Kubernetes Auto-Remediation: Self-Healing with Guardrails

Many 3 a.m. pages need one of three fixes: grow a full volume, roll back a stuck deployment or replace a leaking pod. Kubernetes auto-remediation lets a small worker apply those fixes straight from Alertmanager alerts. By the end you will have the webhook wiring, three playbooks, guardrails that keep automation from worsening an outage, and PromQL that proves whether MTTR dropped.
How Kubernetes auto-remediation works
It is a control loop, like any Kubernetes controller: observe, act, observe again. Prometheus evaluates alert rules. Alertmanager groups firing alerts and POSTs them as JSON to a remediation worker. The worker picks a playbook, checks its guardrails and calls the Kubernetes API through kubectl. When the alert clears, Alertmanager sends a resolved notification, which closes the loop.
On-call still receives every alert, so automation never hides a problem, and the worker reads a kill-switch ConfigMap before each action. You need kube-prometheus-stack (my Kubernetes cluster monitoring guide sets it up), Python 3.9+ and a ServiceAccount for the worker.
Route only the alerts you have playbooks for, using a child route and a webhook receiver in alertmanager.yml:
route:
receiver: slack-oncall
routes:
- receiver: remediator
matchers:
- alertname=~"KubePersistentVolumeFillingUp|KubeDeploymentRolloutStuck|PodMemoryLeak"
continue: true # humans still get paged
- receiver: slack-oncall # catch-all sibling
receivers:
- name: remediator
webhook_configs:
- url: http://remediator.remediation.svc:8080/alerts
send_resolved: true # drives verification and MTTR
max_alerts: 10 # cap per POST
continue: true makes Alertmanager keep checking sibling routes after a match, so the catch-all still pages Slack. Drop the sibling and the alert stops at the worker. Each POST carries status and an alerts array; every alert has labels, startsAt, endsAt and a stable fingerprint. After a reload, the Alertmanager Status page should show the new route.
Three playbooks: disk-full, stuck rollout, leaky pod
A playbook is one small, reversible action tied to one alert, with a manual equivalent on-call can repeat or undo.
| Alert | Action |
|---|---|
KubePersistentVolumeFillingUp | Grow the PVC 25% (kubectl patch) |
KubeDeploymentRolloutStuck | kubectl rollout undo |
PodMemoryLeak | Evict the pod via the Eviction API |
The first two alerts ship with the kubernetes-mixin rules. A stuck rollout is a Deployment whose Progressing condition turned False after progressDeadlineSeconds, and Kubernetes only reports it, never rolls back. The leak alert is custom:
- alert: PodMemoryLeak
expr: |
max by (namespace, pod, container) (container_memory_working_set_bytes{container!=""})
/ max by (namespace, pod, container) (kube_pod_container_resource_limits{resource="memory"}) > 0.9
for: 30m
It fires when a container stays above 90% of its memory limit for 30 minutes. Containers need memory limits: without one there is nothing to divide by.
The worker shells out to kubectl, so every action is a command you could paste into a terminal. DRY_RUN starts as True: it logs what it would do and changes nothing.
import json, logging, subprocess
DRY_RUN = True # shadow mode: log the command, change nothing
def kubectl(*args, stdin=None, mutate=True):
if mutate and DRY_RUN:
logging.info("DRY-RUN kubectl %s", " ".join(args))
return ""
return subprocess.run(["kubectl", *args], input=stdin, text=True, check=True,
capture_output=True, timeout=60).stdout
def expand_pvc(l):
pvc, ns = l["persistentvolumeclaim"], l["namespace"]
cur = kubectl("get", "pvc", pvc, "-n", ns, "-o",
"jsonpath={.spec.resources.requests.storage}", mutate=False)
gib = int(cur.removesuffix("Gi")) # raises on Mi/Ti: page instead
new = min(gib * 5 // 4, 500) # +25%, hard cap 500Gi
patch = {"spec": {"resources": {"requests": {"storage": f"{new}Gi"}}}}
kubectl("patch", "pvc", pvc, "-n", ns, "--type", "merge", "-p", json.dumps(patch))
def undo_rollout(l):
kubectl("rollout", "undo", f"deployment/{l['deployment']}", "-n", l["namespace"])
def evict_pod(l):
ns, pod = l["namespace"], l["pod"]
body = {"apiVersion": "policy/v1", "kind": "Eviction",
"metadata": {"name": pod, "namespace": ns}}
kubectl("create", "--raw", f"/api/v1/namespaces/{ns}/pods/{pod}/eviction",
"-f", "-", stdin=json.dumps(body))
PLAYBOOKS = {"KubePersistentVolumeFillingUp": expand_pvc,
"KubeDeploymentRolloutStuck": undo_rollout, "PodMemoryLeak": evict_pod}
expand_pvc adds 25% and patches the claim. Kubernetes grows mounted volumes online only if the StorageClass sets allowVolumeExpansion: true, and it can never shrink one, hence the cap. evict_pod uses the Eviction API instead of a delete, so a PodDisruptionBudget can refuse with HTTP 429 when too few replicas are healthy. In dry-run mode the log shows:
INFO:root:DRY-RUN kubectl rollout undo deployment/checkout -n shop
The usual failure is RBAC. The ServiceAccount needs get and patch on PVCs and Deployments, list on ReplicaSets (rollout undo reads them), create on pods/eviction and get on ConfigMaps.
Guardrails: blast radius, rate limit, circuit breaker, kill switch
Automation fails fast and at scale. A bad playbook that runs once is an incident; one that runs on every alert in a storm is an outage. When I built guard-railed automated upgrades for a 2000+ machine fleet, the guardrails took more code than the upgrades. The flowchart shows every check before an action.
The webhook handler stays small: for each firing alert, look up PLAYBOOKS, call guard(), run the playbook and schedule a check 15 minutes later. If the alert has not resolved by then, the failure counter rises and a human is paged. Here is the guard:
import time
ALLOWED_NS = {"shop", "search", "db"} # opt-in namespaces only
MAX_TARGETS, MAX_PER_HOUR, MAX_FAILURES = 3, 5, 3
acted, recent, state = {}, [], {"failures": 0}
def kill_switch_on():
try:
return kubectl("get", "configmap", "remediation-control", "-n", "remediation",
"-o", "jsonpath={.data.enabled}", mutate=False) != "true"
except subprocess.SubprocessError:
return True # fail closed: unreadable switch means no automation
def guard(alert, firing_in_group):
l, now = alert["labels"], time.time()
recent[:] = [t for t in recent if now - t < 3600]
if kill_switch_on(): return "kill switch off"
if state["failures"] >= MAX_FAILURES: return "circuit breaker open"
if l.get("namespace") not in ALLOWED_NS: return "namespace not allowed"
if firing_in_group > MAX_TARGETS: return "blast radius exceeded"
if alert["fingerprint"] in acted: return "already acted"
if len(recent) >= MAX_PER_HOUR: return "rate limit"
acted[alert["fingerprint"]] = now
recent.append(now)
return None
Global stops come first, per-alert checks last, and counters change only when an action is allowed:
- Kill switch: one ConfigMap value stops everything; unreadable counts as off.
- Blast radius: a namespace allowlist plus a cap on objects per alert group. Five PVCs filling at once is systemic.
- Idempotency: Alertmanager resends firing alerts every
repeat_interval, so act once per fingerprint. - Rate limit and breaker: five actions an hour; three unresolved actions in a row open the breaker until a human resets it.
Create the switch, then test it before you trust it:
kubectl create configmap remediation-control -n remediation --from-literal=enabled=true
kubectl patch configmap remediation-control -n remediation --type merge -p '{"data":{"enabled":"false"}}'
The next alert should be skipped with reason kill switch off. Then rehearse each playbook on purpose (fill a test volume, ship a broken image, run a memory hog) with the methods in chaos engineering in production. Never trust a remediation you have not seen fire.
Measuring Kubernetes auto-remediation: auto-closed rate and MTTR
The worker exports two metrics with the official Python client: a counter remediation_actions_total labelled playbook and result, and a histogram alert_resolve_seconds labelled alertname and handled (auto or human), observed as endsAt minus startsAt on each resolved notification. Run one month in dry-run first: people fix those alerts, giving an honest baseline.
# Share of alerts the worker closed itself (30 days)
sum(increase(remediation_actions_total{result="resolved"}[30d]))
/ sum(increase(alert_resolve_seconds_count[30d]))
# MTTR in minutes per alert: handled="human" (shadow month) vs "auto"
sum by (alertname, handled) (increase(alert_resolve_seconds_sum[30d]))
/ sum by (alertname, handled) (increase(alert_resolve_seconds_count[30d])) / 60
The first query returns a ratio from 0 to 1; the second, one MTTR per alert and handler, as charted below. Thirty-day windows need 30 days of Prometheus retention; otherwise use [7d].
A rising unresolved share means a playbook treats a symptom, not the cause.
Where an LLM fits, and where it must not
An LLM helps at the edges of this loop, not inside it. For alerts without a playbook, let it gather context and suggest one from the allowlist for a human to approve. That is how I approach automated root-cause analysis: the model investigates, a deterministic playbook acts (see LLM root cause correlation). Version the prompt, run evals on past incidents and track token cost per alert. Never let the model write the kubectl command.
Common pitfalls
- Remediating a symptom forever. Evicting the same pod daily hides a bug; open a ticket after the third repeat.
- Forgetting state. The counters live in memory, so a restart resets the breaker. Run one replica and persist state.
- Failing open. If the kill switch or API is unreachable, do nothing and page.
- Silent automation. Post every action and skip to the incident channel.
Key takeaways
- Start with a few boring, reversible playbooks for your noisiest alerts.
- Send alerts to the worker and to humans; never hide a page.
- Guardrails are the product: kill switch, blast radius, rate limit, circuit breaker.
- Run in dry-run mode first, then prove the win with auto-closed rate and MTTR.
Related articles

Rolling Out a JDK Upgrade to 2,000+ Jenkins Agents
A JDK upgrade reached most of a client's 2,000+ Jenkins agents in half an hour and broke builds with a misleading error. How the client's rollouts work, how Claude Code found the deleted JDK, and how they roll out now.

LLM Root Cause Analysis: Correlate Logs, Metrics, Traces
Most incidents follow a change. Give an LLM the deploy history, one PromQL result, filtered logs and a trace, and it returns ranked root-cause hypotheses with evidence for and against, plus the guardrails that keep it honest.

ML Anomaly Detection for Metrics: Beyond Static Thresholds
Static thresholds page at lunch and sleep at 4 a.m. Learn to score Prometheus metrics with an isolation forest in Python and gate pages on SLO burn rate, cutting pager noise without missing real incidents.