What This Agent Does
A Karpenter consolidation agent answers one question for every node in the cluster: if this node is mostly empty, why is it still here? It reads Karpenter's own DisruptionBlocked and Unconsolidatable events, joins them with PodDisruptionBudgets, pod annotations, NodePool settings, and a day of Prometheus usage, and assigns each stuck node exactly one blocker class. Then it opens a pull request against the manifest that causes the block: a PDB that allows zero disruptions, a karpenter.sh/do-not-disrupt annotation on a Deployment, a NodePool with too few instance types for spot-to-spot moves. It never drains, cordons, or deletes a node. Karpenter does that on its own once the blocker is gone.
The reason to build it: Karpenter not consolidating is silent. The Karpenter vs Cluster Autoscaler comparison credits consolidation for most of the savings, and that holds only while consolidation is allowed to run. One PDB with minAvailable equal to the replica count pins every node its pods land on, and nothing alerts. The bill just stops going down.
The Six Blockers
| Blocker | How Karpenter reports it | Who owns the fix | Agent action |
|---|---|---|---|
| PDB allows zero disruptions | DisruptionBlocked event naming the PDB | Service team | PR: maxUnavailable: 1 or one more replica |
do-not-disrupt on a long-lived pod | DisruptionBlocked event naming the pod | Service team | PR: remove annotation, add a PDB |
| Inflated requests | No event, node looks full | Service team | Hand off to request right-sizing |
| Spot-to-spot not possible | Unconsolidatable event | Platform team | PR: widen instance-type requirements |
| NodePool budget or policy | karpenter_nodepools_allowed_disruptions at 0, or WhenEmpty | Platform team | Report only |
| Scheduling constraints | Unconsolidatable: no cheaper replacement | Service team | Report only |
The third row matters most and has no event at all. Karpenter consolidates on resource requests, not on usage. A node whose pods request 90% of its CPU and use 8% is, from Karpenter's side, a well-packed node. No event will ever say otherwise, so the agent has to find those from metrics.
Step 1: Collect What Karpenter Already Says
Karpenter publishes its reasoning as Kubernetes events on Node and NodeClaim objects. Both are cluster-scoped, so the events land in the default namespace. Check what your version emits before writing any parser:
kubectl get events -n default \
--field-selector reason=DisruptionBlocked \
-o custom-columns=OBJ:.involvedObject.name,MSG:.message | sort | uniq -c | sort -rn | head -20
kubectl get events -n default --field-selector reason=Unconsolidatable
Two things to know. Message wording has changed between Karpenter releases, so match on loose substrings (pdb, do-not-disrupt, spot) and send anything unmatched to an unknown class instead of guessing. And the API server keeps events for one hour by default while Karpenter deduplicates repeated ones, so a single snapshot misses blockers. Run the collector every 15 minutes and append to a small store, or read from an event exporter if you already ship events to Loki.
# consolidation/collect.py
from kubernetes import client, config
config.load_incluster_config()
core = client.CoreV1Api()
policy = client.PolicyV1Api()
custom = client.CustomObjectsApi()
def karpenter_nodes() -> list:
return core.list_node(label_selector="karpenter.sh/nodepool").items
def blocker_events() -> dict[str, list[str]]:
by_node: dict[str, list[str]] = {}
for reason in ("DisruptionBlocked", "Unconsolidatable"):
events = core.list_namespaced_event(
"default", field_selector=f"reason={reason}").items
for e in events:
if e.involved_object.kind == "Node":
by_node.setdefault(e.involved_object.name, []).append(e.message)
return by_node
def zero_budget_pdbs() -> list:
pdbs = policy.list_pod_disruption_budget_for_all_namespaces().items
return [p for p in pdbs if p.status.disruptions_allowed == 0]
def nodepools() -> dict[str, dict]:
items = custom.list_cluster_custom_object(
"karpenter.sh", "v1", "nodepools")["items"]
return {np["metadata"]["name"]: np["spec"] for np in items}
The ServiceAccount needs get and list on nodes, pods, events, poddisruptionbudgets, and nodepools. Nothing else. No patch, no delete, no pods/eviction.
Step 2: Measure Requested vs Used per Node
Two ratios per node, from kube-state-metrics and cAdvisor. The node label on cAdvisor series depends on your scrape config (kube-prometheus-stack adds it); adjust if yours uses instance.
# consolidation/usage.py
QUERIES = {
"cpu_requested_ratio": '''
sum by (node) (
kube_pod_container_resource_requests{resource="cpu"}
* on (namespace, pod) group_left()
(kube_pod_status_phase{phase="Running"} == 1)
) / on (node) kube_node_status_allocatable{resource="cpu"}''',
"cpu_used_p95_ratio": '''
quantile_over_time(0.95, (
sum by (node) (rate(container_cpu_usage_seconds_total{container!=""}[5m]))
)[24h:5m]) / on (node) kube_node_status_allocatable{resource="cpu"}''',
"mem_requested_ratio": '''
sum by (node) (
kube_pod_container_resource_requests{resource="memory"}
* on (namespace, pod) group_left()
(kube_pod_status_phase{phase="Running"} == 1)
) / on (node) kube_node_status_allocatable{resource="memory"}''',
"mem_used_p95_ratio": '''
quantile_over_time(0.95, (
sum by (node) (container_memory_working_set_bytes{container!=""})
)[24h:5m]) / on (node) kube_node_status_allocatable{resource="memory"}''',
}
For dollars, Karpenter exports karpenter_cloudprovider_instance_type_offering_price_estimate, labeled by instance type, capacity type, and zone. Join it to each node's node.kubernetes.io/instance-type, karpenter.sh/capacity-type, and topology.kubernetes.io/zone labels and you get an hourly price without calling the AWS Pricing API. It is an estimate and knows nothing about your Savings Plans, so treat the totals as a ranking signal, not an invoice.
Step 3: Classify in Code
One class per node, checked in a fixed order. Explicit blockers from events win over inferred ones.
# consolidation/classify.py
MIN_AGE_HOURS = 6 # younger nodes have not had a fair chance
LOW_REQ = 0.50 # under half requested: should have been consolidated
FULL_REQ = 0.80 # looks packed to Karpenter
IDLE_USE = 0.25 # but barely used
def classify(node: dict, msgs: list[str], pool: dict) -> str:
if node["age_hours"] < MIN_AGE_HOURS:
return "too_young"
text = " ".join(msgs).lower()
req = max(node["cpu_requested_ratio"], node["mem_requested_ratio"])
use = max(node["cpu_used_p95_ratio"], node["mem_used_p95_ratio"])
if "pdb" in text:
return "pdb_blocked"
if "do-not-disrupt" in text:
return "do_not_disrupt"
disruption = pool.get("disruption", {})
if disruption.get("consolidationPolicy") == "WhenEmpty" \
or disruption.get("consolidateAfter") == "Never":
return "policy_disabled" if req < LOW_REQ else "healthy"
if "spot" in text and node["capacity_type"] == "spot":
return "spot_to_spot"
if req >= FULL_REQ and use < IDLE_USE:
return "request_inflated"
if req < LOW_REQ and msgs:
return "scheduling_constraint"
if req < LOW_REQ:
return "unknown"
return "healthy"
max() across CPU and memory is deliberate. A node is packed if either dimension is packed, and it is idle only if both are. Using CPU alone flags every memory-bound JVM node as waste.
The pdb_blocked class needs one more split before the model sees it, because a PDB at zero allowed disruptions is not always a bug. If status.currentHealthy is below status.desiredHealthy, the workload is unhealthy right now and the PDB is doing its job; the agent files that as pdb_unhealthy and stays out. If the PDB is at zero while every pod is healthy, the budget is unsatisfiable by construction: minAvailable: 2 on two replicas, maxUnavailable: 0, or minAvailable: 1 on a singleton. Those never allow a voluntary eviction, and they are the same PDBs that stall the node drain agent during upgrades.
Step 4: The Model Picks the Narrowest Fix
Code decides that a node is blocked and why. The model's job is narrower: given one blocker, the workload manifest, and the service tier, choose a fix from a closed list and write the PR description. It receives one finding at a time and must return this:
{
"name": "propose_fix",
"input_schema": {
"type": "object",
"required": ["action", "target_file", "rationale", "risk"],
"properties": {
"action": {"enum": [
"pdb_to_max_unavailable_1",
"add_replica_keep_pdb",
"remove_do_not_disrupt_add_pdb",
"widen_nodepool_instance_types",
"handoff_request_rightsizing",
"report_only"
]},
"target_file": {"type": "string"},
"rationale": {"type": "string", "maxLength": 600},
"risk": {"enum": ["low", "medium", "high"]}
}
}
}
The system prompt carries the rules that need judgment:
You propose one fix for one Karpenter consolidation blocker.
- A pod owned by a Job or CronJob with do-not-disrupt is legitimate. Return report_only.
- A Deployment with do-not-disrupt in its pod template blocks its node forever.
Propose removing it and adding a PDB with maxUnavailable: 1.
- For a singleton with minAvailable: 1, prefer add_replica_keep_pdb only if the
manifest shows the app is stateless. Otherwise report_only and say why.
- Never propose deleting a PDB. Never propose changing NodePool disruption budgets.
- If the evidence does not clearly support an action, return report_only.
Route the call through the LiteLLM gateway so this agent has its own budget. A typical run is a few dozen findings, each a small prompt, so cost is not the concern. The per-agent key is there so a bug that loops over every node cannot spend without a ceiling.
After the model answers, code validates again: the target_file must exist in the GitOps repo and must define the object named in the event, tier-1 services are forced to report_only regardless of the answer, and a StatefulSet never gets pdb_to_max_unavailable_1 without a human label on the finding.
Step 5: Ship PRs, One Blocker Each
Following the pull requests, not kubectl pattern, every fix is a small diff with the evidence in the description. For an unsatisfiable PDB:
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
name: checkout-api
spec:
- minAvailable: 3
+ maxUnavailable: 1
+ unhealthyPodEvictionPolicy: AlwaysAllow
selector:
matchLabels:
app: checkout-api
unhealthyPodEvictionPolicy: AlwaysAllow lets the eviction API remove pods that are already not Ready, so a crash-looping replica cannot pin a node. The PR body lists the nodes this PDB currently holds, their requested ratio, the estimated hourly price of each, and the exact event message Karpenter emitted. A reviewer should be able to approve it without opening a terminal.
For spot nodes, single-node spot-to-spot consolidation needs the SpotToSpotConsolidation feature gate and a NodePool flexible enough to offer at least 15 candidate instance types; that floor exists so Karpenter does not chase the cheapest, most-interrupted pool. If the NodePool pins three instance types, the PR widens node.kubernetes.io/instance-type requirements to category and generation instead. The spot interruption handling guide covers why wide requirements also cut interruption rates.
request_inflated nodes produce no PR here. The fix is lower requests on the workloads, which is the job of the FinOps agent, so this agent writes the top five requesters per inflated node into that agent's queue and stops.
Guardrails
| Rule | Enforced where |
|---|---|
| Read-only RBAC, no eviction or node verbs | ClusterRole |
| At most 5 PRs per run, one open PR per target file | PR opener |
| Tier-1 and StatefulSet findings are report-only by default | Post-model validation |
| Never delete a PDB, never edit NodePool budgets | Action enum has no such option |
| Skip nodes younger than 6 hours | Classifier |
unknown class is reported verbatim, never auto-fixed | Classifier |
The PR cap matters more than it looks. Removing ten blockers in one afternoon means Karpenter suddenly has a lot of consolidation to do, and every consolidation is a round of evictions. Before the first batch merges, make sure the NodePool has a disruption budget that limits the pace:
spec:
disruption:
consolidationPolicy: WhenEmptyOrUnderutilized
consolidateAfter: 5m
budgets:
- nodes: "10%"
- nodes: "0"
schedule: "0 9 * * mon-fri"
duration: 8h
reasons: ["Underutilized"]
The second budget stops underutilization moves during business hours while still allowing empty-node cleanup. The agent reads these budgets so it does not report a deliberate freeze as a problem.
What the Report Looks Like
An illustrative run on a 60-node cluster, posted weekly to the platform channel:
Karpenter consolidation blockers (24h window, 61 nodes, 9 skipped as too young)
pdb_blocked 7 nodes est. $1.92/h 3 PDBs -> 3 PRs opened
do_not_disrupt 4 nodes est. $1.10/h 1 Deployment, 2 Jobs -> 1 PR, 2 report-only
request_inflated 11 nodes est. $3.40/h handed to request right-sizing
spot_to_spot 5 nodes est. $0.48/h nodepool "batch" has 4 instance types -> 1 PR
scheduling_constraint 2 nodes est. $0.55/h required anti-affinity on hostname, report-only
unknown 1 node message: "..." (unparsed, attached)
healthy 22 nodes
The dollar column is price times the unrequested fraction of the node, or times the unused fraction for request_inflated. It overstates what you will get back, because consolidated pods still need to land somewhere. Use it to order the work.
Honest Limits
- The agent cannot replay Karpenter's simulation. Karpenter decides consolidation by simulating scheduling against every instance type and price. The agent reads the outcome from events. When there is no event and no obvious metric signal, the answer is
unknown, and that is the right answer. - Events are lossy. Deduplication and the one-hour TTL mean a blocker can go unobserved for a cycle. Persisting events fixes most of it. A node that is blocked for two consecutive days is a finding; one sighting is not.
- Removing a blocker trades cost for churn. A service that sat still for months will start moving. If it has slow startup or no readiness probe, consolidation turns a cost problem into an availability one. The PR description says so for every
mediumrisk fix. - Inflated requests are usually the biggest number and the slowest fix. PDB and annotation PRs merge in a day. Request changes need a per-service conversation, and lowering CPU requests carelessly lands you in the cases the CPU throttling agent exists to catch.
Start with the report only, no PRs, for two weeks. The first run usually shows a handful of PDBs and one forgotten annotation holding a meaningful share of the idle capacity, and that list alone tells you whether the PR automation is worth wiring up.