Automating Kubernetes Cost Optimization with an AI Agent
You ran the audit and shipped a rightsizing PR last month. It's already going stale. The service whose requests you trimmed got a new feature and a new memory profile. Someone raised an HPA's minReplicas during an incident and never put it back. Two new deployments shipped this week with requests copied from a template written in 2023. The fixes don't stick, because the cluster keeps changing after you fix it.
What closes that gap is cadence plus verification, and both are investigation work. This part shows CloudThinker agents doing it through your connections: kubectl through a read-only Kubernetes connection, PromQL through Prometheus, and a pull request through GitHub only when someone approves one.
One boundary up front. This isn't an Optimize feature. Optimize reads your AWS, GCP or Azure bill, where a cluster shows up as its billed nodes and services, and it doesn't split cost by namespace or workload. Everything below the node is agent work in the cluster.
Why point-in-time rightsizing loses
A cluster with 30 active deployments and a weekly release cadence sees hundreds of changes between audits. A dependency upgrade changes memory behavior. A traffic shift strands a node pool. A deleted namespace leaves its volumes and load balancers behind. The leaks from part one regenerate at deploy speed, while the audit runs at calendar speed.
The native tools don't close this on their own. VPA recommends, but doesn't reconcile its numbers with your HPA settings and PodDisruptionBudgets. The Cluster Autoscaler faithfully bin-packs whatever requests you give it, inflated or not.
The harder gap is verification: is that namespace really abandoned, does that PDB protect something real, will the smaller request survive Monday's peak. That checking is what gets skipped when the audit runs long, and skipping it is how a rightsizing PR turns into an incident.
Connecting: a read-only service account, about ten minutes
01Your connections
Cluster and repo
Kuberneteskubectl as a read-only service account
PrometheusPromQL for peaks and history
GitHub or GitLabHelm values and their history
get, list, watch. No Secrets.
02Investigation
CloudThinker
- Scheduled runThe part-two audit, as an automation
- Verify each findingPeaks, HPA floors, PDBs, recent changes
- Propose the changeNew values, estimate, rollback, owner
Nothing installed on your nodes
03Your team
Decides
- The run’s conversationFindings with the evidence attached
Pull requestOpened only after approval
- Auto ModeWhat runs alone, what waits
Writes need RBAC you grant
You apply a manifest that creates a cloudthinker namespace, a cloudthinker-reader service account, and a ClusterRole with get, list and watch on pods, logs, nodes, services, endpoints, PVs and PVCs, deployments, StatefulSets, HPAs, PodDisruptionBudgets and metrics. It can't read Secrets, and it doesn't cover custom resources, so add a rule if you want agents to read Karpenter NodePools. Then you build a kubeconfig with that account's token and the cluster CA embedded, because the aws, gcloud and az exec plugins that managed clusters use don't work outside your machine. The Kubernetes connection guide has the full manifest for your security review.
Three details to know before you start:
- The API server must be reachable from CloudThinker Cloud. A private-only endpoint fails the connection test. If you restrict API access with EKS public access CIDRs, GKE authorized networks or AKS authorized IP ranges, allowlist CloudThinker's egress IPs.
- One Kubernetes connection per workspace. Agents work in the kubeconfig's current context. For several clusters, use a workspace per cluster, or a Rancher connection for inventory across the clusters Rancher manages.
- Live usage needs Metrics Server. Without it, agents still see pod status and node conditions, but not CPU and memory. For a week of history, add a Prometheus connection so agents can run the PromQL from part two.
Add your cloud account for node prices, and GitHub or GitLab if you want changes proposed as pull requests.
Make it a schedule, not a project
The cadence comes from an automation: stored instructions plus a trigger. A weekly schedule is enough for most clusters, and a cron expression like 0 8 * * 1 runs it every Monday at 08:00. The instructions are the part-two audit in plain language:
Review the cluster for cost waste. For the ten deployments with the largest gap
between CPU requests and 14-day peak usage, check HPA floors, PDBs and recent
Helm changes before proposing anything. List Released PVs, LoadBalancer Services
with no ready endpoints, and nodes kept alive by scale-down blockers. Compare
with last week's run and only report what changed. Propose only, change nothing.
Set the automation to continue one conversation, so each run sees the last one and reports the difference instead of the same list. Every run shows up in the Runs view, linked to its conversation.
01Signal
Something moved
Node count, requests or a namespace changed since the last run.
02Context
Investigate
Requests, peak usage, HPAs, autoscaler state and recent Helm changes.
03Check
Verify safety
Peak traffic, PDBs and owners: anything the change could break.
04Output
Proposal
The change, the estimate, the rollback and who must agree.
One finding, investigated
Here's the stale minReplicas from the opening, the way a run works it. The details are illustrative.
On the 14th, the prod-general node pool is at 18 nodes. Two weeks earlier it ran at 14, and request traffic across the cluster is flat. Three readings fit:
01Reading 1
New or padded requests
Predicts requested CPU jumping where a deployment is new or its requests changed.
02Reading 2
A raised replica floor
Predicts one workload pinned at its HPA minReplicas with low CPU per pod.
03Reading 3
Blocked scale-down
Predicts flat requests and nodes marked unneeded that never leave.
Where did the requested CPU go?
sum(kube_pod_container_resource_requests{resource="cpu"}) by (namespace)
-
sum(kube_pod_container_resource_requests{resource="cpu"} offset 14d) by (namespace)
Requests rose by 24 cores, all of it in the search namespace, with no new deployments there. That weakens the first reading. Blocked scale-down wouldn't add requests, and the autoscaler status ConfigMap shows no nodes marked unneeded, so the third reading is out.
Is it the HPA?
kubectl get hpa -n search
search-api shows MINPODS 16, MAXPODS 20, REPLICAS 16, at 9% CPU against a 70% target. The HPA would scale down. The floor won't let it. Each pod requests 2 CPU, so twelve extra replicas account for the 24 cores. Through the GitHub connection, the agent finds the change:
gh pr list --repo acme/charts --state merged --search "search-api minReplicas"
A Helm values PR merged on the 2nd: "hotfix: raise search min replicas during reindex". The reindex job completed on the 3rd.
What does it actually need? The peak, not the average:
max_over_time(
sum(rate(container_cpu_usage_seconds_total{namespace="search", pod=~"search-api-.*", container!=""}[5m]))[14d:5m]
)
The busiest five minutes in two weeks used 6.8 cores. At 2 CPU per pod and a 70% target, that's five replicas. A floor of six leaves headroom.
The result, in the run's conversation:
search-api HPA floor still at 16 after the reindex.
minReplicaswent from 4 to 16 on the 2nd for a reindex that finished on the 3rd. The HPA sits at 9% CPU against a 70% target, and the 14-day peak needed five replicas. The floor holds about 20 cores, roughly three nodes inprod-general, around $840 a month at on-demand list price. Proposed: setminReplicasto 6 in the Helm values. Rollback: revert the PR. Owner: the search team, which owns the chart.
When the search team agrees, the agent opens the pull request through the GitHub connection:
# charts/search-api/values-prod.yaml
autoscaling:
enabled: true
minReplicas: 6 # was 16, raised on the 2nd for the reindex
maxReplicas: 20
targetCPUUtilizationPercentage: 70
Once it merges, the HPA scales down and the Cluster Autoscaler removes the empty nodes on its own. Found on day twelve instead of at the next quarterly review, with peak demand already checked.
You decide what the agent may touch
Two controls sit in front of every change. The first is the credential: the reader role can't write, so a scale or rollout restart fails with 403 until you bind write rules to the service account, ideally one namespace at a time. You can check what you've granted:
kubectl auth can-i patch deployments --subresource=scale -n search \
--as=system:serviceaccount:cloudthinker:cloudthinker-reader
The second is Auto Mode: every write, whether a PR or a kubectl change, goes through it, so you decide what runs on its own and what waits for a person. Scaling a staging namespace to zero overnight and changing a production node pool aren't the same kind of decision, and they don't have to get the same answer.
Why this beats the traditional approach
| Quarterly rightsizing audit | CloudThinker agents on a schedule | |
|---|---|---|
| When waste is found | Weeks after it starts | At the next scheduled run |
| Verification | Done when there's time | Peak usage, HPAs, PDBs and history, every run |
| Engineer time | An afternoon per cluster per audit | Reading the delta and deciding |
| From finding to fix | A PR someone else has to write | A PR opened after approval |
| Changes | Manual | RBAC you grant, then Auto Mode |
The deeper difference is where the hours go. In the audit, most of the afternoon goes to joining top output, PromQL, VPA objects and Helm history by hand, and too little to judging them. With the joining done, your time goes to the one decision that needs a person: whether the change is right for this workload.
What it won't do
- Write without the role. The reader account has no write verbs. Changes need RBAC you add, and still go through Auto Mode.
- Act in silence. Every proposal arrives with its evidence, and every run is recorded with its conversation.
- Bypass your guardrails. Changes go through the API server or your Git workflow like any other client, subject to your admission controllers, PDBs and quotas.
- Make architectural calls. It'll tell you a PodDisruptionBudget is blocking consolidation. Whether that PDB is load-bearing stays an engineering decision.
Getting started
Connect one cluster with the read-only service account, add Prometheus if you have it, and ask your first question:
"Show me the 10 deployments with the biggest gap between CPU requests and peak usage over the last 14 days. Propose only, change nothing."
"Which nodes could be removed right now, and what's stopping the autoscaler from doing it?"
"List every HPA sitting at its minReplicas floor with CPU far under target, and when each floor last changed."
"What would scaling the staging namespace to zero outside business hours save us?"
Next step: run the first prompt on your most expensive cluster. CloudThinker for Kubernetes covers the connection and what agents can check in a cluster.



