cloud

Build a Fargate Cost Agent: Right-Size ECS Task CPU and Memory, Find Idle Services, and Ship Fargate Spot and arm64 Moves as Terraform PRs Without an OOM Kill

Build a Fargate cost agent that right-sizes ECS task CPU and memory from CloudWatch, finds idle services, and ships Spot and arm64 moves as Terraform PRs.

December 5, 2026·13 min read·
#ai#aws#finops#cost-optimization#cloud#automation#devops#containers#terraform#serverless

What This Agent Does

A Fargate cost agent reads 14 days of CPU and memory utilization for every ECS service in the account, snaps the measured peak plus headroom to the nearest valid Fargate task size, finds load-balanced services that received zero requests, and checks which services could run on arm64 or Fargate Spot. All of that is deterministic code. The LLM gets one job: read the Terraform for the task definition, write the PR that changes the right lines, and name in the description the one thing a reviewer must check, which is usually a heap flag buried in an environment variable. The agent never calls ecs:UpdateService or ecs:RegisterTaskDefinition, and it skips any service that was OOM-killed in the last 30 days.

Fargate needs its own agent because the waste is structural. You pay for the task size you declared, not for what the containers use, and there is no node to bin-pack onto. A service declared at 2 vCPU and 8 GB that peaks at 0.6 vCPU and 2.1 GB wastes more than half its bill every hour, and nothing in the console says so. This post follows the same shape as the EC2 right-sizing agent and the Lambda cost agent: read-only collector, fixed findings with thresholds, PRs as the only output.

The Four Places Fargate Spend Hides

BucketHow it happensWhat fixes it
Oversized tasksSize was copied from another service or doubled during an incidentLower cpu and memory to measured peak plus headroom
Idle servicesOld API version, abandoned preview environment, dev running nights and weekendsScale to zero, or schedule it
x86 where arm64 would dox86 is the default when no runtime_platform is setMove to ARM64 for a 20% lower rate
On-demand where Spot would doNobody set a capacity provider strategyPut the tasks above a safe base on FARGATE_SPOT

Prices here are us-east-1 Linux list prices. Keep them in a config file, because the agent will outlive the next price change.

# fargate_price.py — per hour
PRICE = {
    "X86_64": {"vcpu": 0.04048, "gb": 0.004445},
    "ARM64":  {"vcpu": 0.03238, "gb": 0.00356},
}
SPOT_DISCOUNT = 0.60   # assumption; Spot price moves, read the real rate from your CUR

def task_month(cpu_units, mem_mb, arch="X86_64", hours=730):
    p = PRICE[arch]
    return ((cpu_units / 1024) * p["vcpu"] + (mem_mb / 1024) * p["gb"]) * hours

Worked example, used through the rest of the post: a checkout service running 6 tasks at 2 vCPU and 8 GB on x86.

current        2 vCPU / 8 GB x86      $85.06 per task   $510.36 per month
right-sized    1 vCPU / 3 GB x86      $39.28 per task   $235.71 per month
plus arm64     1 vCPU / 3 GB ARM64    $31.43 per task   $188.60 per month
plus Spot      3 on-demand + 3 Spot at the assumed 60% off   about $132 per month

The right-sizing step alone is worth more than the other two combined. That ordering holds for nearly every service, and it is why the agent ships sizing PRs first.

Step 1: Collect Utilization Without Paying for Container Insights

The role needs ecs:ListClusters, ecs:ListServices, ecs:DescribeServices, ecs:DescribeTaskDefinition, cloudwatch:GetMetricData, application-autoscaling:DescribeScalableTargets, application-autoscaling:DescribeScalingPolicies, elasticloadbalancing:DescribeTargetGroups, ecr:BatchGetImage, logs:StartQuery, logs:GetQueryResults, and compute-optimizer:GetECSServiceRecommendations. Add an explicit Deny on ecs:UpdateService, ecs:RegisterTaskDefinition, and ecs:DeleteService. The IAM right-sizing agent post explains why the deny is worth the extra lines.

You do not need Container Insights for this. Every ECS service already publishes CPUUtilization and MemoryUtilization to the free AWS/ECS namespace, as a percentage of the task's declared size. The Maximum statistic is the busiest task in each period, which is the number sizing has to respect.

# collect_fargate.py — read-only, one dict per service
import boto3
from datetime import datetime, timedelta, timezone

ecs, cw = boto3.client("ecs"), boto3.client("cloudwatch")
NOW = datetime.now(timezone.utc)

def peak_pct(cluster, service, metric, days=14):
    r = cw.get_metric_data(
        StartTime=NOW - timedelta(days=days), EndTime=NOW,
        MetricDataQueries=[{
            "Id": "m", "ReturnData": True,
            "MetricStat": {
                "Metric": {"Namespace": "AWS/ECS", "MetricName": metric,
                           "Dimensions": [{"Name": "ClusterName", "Value": cluster},
                                          {"Name": "ServiceName", "Value": service}]},
                "Period": 300, "Stat": "Maximum"}}])
    vals = r["MetricDataResults"][0]["Values"]
    return (max(vals), len(vals)) if vals else (None, 0)

def collect(cluster, service):
    svc = ecs.describe_services(cluster=cluster, services=[service])["services"][0]
    td = ecs.describe_task_definition(taskDefinition=svc["taskDefinition"])["taskDefinition"]
    cpu_pct, n = peak_pct(cluster, service, "CPUUtilization")
    mem_pct, _ = peak_pct(cluster, service, "MemoryUtilization")
    return {
        "cluster": cluster, "service": service,
        "desired": svc["desiredCount"],
        "cpu": int(td["cpu"]), "memory": int(td["memory"]),
        "arch": td.get("runtimePlatform", {}).get("cpuArchitecture", "X86_64"),
        "on_spot": any(s["capacityProvider"] == "FARGATE_SPOT"
                       for s in svc.get("capacityProviderStrategy", [])),
        "peak_cpu_units": cpu_pct and cpu_pct / 100 * int(td["cpu"]),
        "peak_mem_mb": mem_pct and mem_pct / 100 * int(td["memory"]),
        "datapoints": n,
        "target_groups": [lb["targetGroupArn"] for lb in svc.get("loadBalancers", [])],
        "images": [c["image"] for c in td["containerDefinitions"]],
    }

Two rules on the data. A service with fewer than 3,600 datapoints (about 12.5 of the 14 days) is skipped, because it is new or was scaled to zero for part of the window. And the 14 days must include the service's known peak. If checkout peaks at month-end, a mid-month window will recommend a size that fails on the 30th. The agent reads a peak_calendar.yaml that service owners maintain and widens the window to 63 days (the retention limit for 5-minute data) when a peak is not covered.

Compute Optimizer also produces Fargate recommendations via get_ecs_service_recommendations. The agent pulls them as a second opinion and records disagreement in the PR, but it sizes from its own numbers, because it needs to explain the math line by line and apply its own headroom.

Step 2: Snap to a Valid Fargate Size

Fargate does not accept arbitrary sizes. Each CPU value allows a fixed memory range, and memory can force a larger CPU: there is no 0.25 vCPU task with 3 GB.

# snap.py
FARGATE = {                                   # cpu units: allowed memory in MB
    256:   [512, 1024, 2048],
    512:   list(range(1024, 4097, 1024)),
    1024:  list(range(2048, 8193, 1024)),
    2048:  list(range(4096, 16385, 1024)),
    4096:  list(range(8192, 30721, 1024)),
    8192:  list(range(16384, 61441, 4096)),
    16384: list(range(32768, 122881, 8192)),
}
CPU_PEAK_TARGET = 0.70    # measured peak should sit at 70% of the new size
MEM_HEADROOM = 1.30       # memory is a hard wall, give it 30%

def snap(peak_cpu_units, peak_mem_mb):
    cpu_needed = peak_cpu_units / CPU_PEAK_TARGET
    mem_needed = peak_mem_mb * MEM_HEADROOM
    for cpu in sorted(FARGATE):
        if cpu < cpu_needed:
            continue
        fits = [m for m in FARGATE[cpu] if m >= mem_needed]
        if fits:
            return cpu, fits[0]
    return None

For checkout, peak CPU is 635 units and peak memory is 2,150 MB. CPU needed is 907 units, memory needed is 2,795 MB, and the first size that fits both is 1024 CPU with 3072 MB.

CPU and memory get different treatment for a reason. CPU over the limit means throttling and slower responses. Memory over the limit means the container is killed with exit code 137. The asymmetry is the same one described in the Kubernetes OOMKilled guide, minus the node: on Fargate the task size is the wall.

The autoscaling trap

If the service has a target tracking policy on CPU, shrinking the task's CPU does not save what the math says. Utilization is a percentage of the declared size, so halving the size doubles the percentage, the policy scales out, and you end up with twice as many half-sized tasks. The agent checks describe_scaling_policies and applies this rule:

  • No CPU target tracking: recommend both CPU and memory.
  • CPU target tracking, and the service sat at its minimum capacity for the whole window: recommend both, because scaling never engaged and the minimum is what you pay for.
  • CPU target tracking that actively scales: recommend memory only, and say why in the PR.

Step 3: Three Guards Before Any Finding

No recent OOM kills. Stopped tasks disappear from describe-tasks after about an hour, so you need history. Create one EventBridge rule that sends task stops to a log group, then query it.

{
  "source": ["aws.ecs"],
  "detail-type": ["ECS Task State Change"],
  "detail": { "lastStatus": ["STOPPED"] }
}
filter @message like /OutOfMemoryError/
| stats count(*) as oom_kills by detail.group

detail.group is service:checkout for service tasks. Any service with one or more OOM kills in 30 days gets no downsizing finding. The same log group answers a second question later: filter on detail.stopCode = "SpotInterruption" to see how often Spot actually reclaims your tasks.

Idle means zero requests, and only for load-balanced services. For each target group, sum RequestCount from AWS/ApplicationELB over 14 days. Zero requests with a desired count above zero is an idle finding. Queue workers and scheduled consumers have no request metric, so the agent does not guess. It lists them as "not assessed" instead.

arm64 requires an arm64 image for every container. The agent asks ECR for the manifest and looks for a linux/arm64 entry. A single-architecture image, or one sidecar without an arm64 build, removes the finding.

import json, boto3
ecr = boto3.client("ecr")
INDEX_TYPES = ["application/vnd.oci.image.index.v1+json",
               "application/vnd.docker.distribution.manifest.list.v2+json"]

def has_arm64(repo, tag):
    r = ecr.batch_get_image(repositoryName=repo, imageIds=[{"imageTag": tag}],
                            acceptedMediaTypes=INDEX_TYPES)
    if not r["images"]:
        return False
    m = json.loads(r["images"][0]["imageManifest"])
    return any(x.get("platform", {}).get("architecture") == "arm64"
               for x in m.get("manifests", []))

Skip this check and the task fails at start with the error covered in the exec format error guide. Images outside ECR are marked "verify manually".

Step 4: Spot Eligibility Is a Rule List, Not a Judgment Call

Fargate Spot gives a two-minute warning, sends SIGTERM, and then kills the task. A service qualifies only when all of these are true:

  • Desired count is 4 or more, so a base of 2 on-demand tasks still leaves something to move.
  • It sits behind a load balancer with a deregistration delay of 60 seconds or less.
  • No container sets stopTimeout above 120 seconds, which is the Fargate maximum anyway.
  • It is not tagged spot=never. Owners use that tag for anything that holds in-flight state it cannot hand off.

The strategy the agent proposes keeps a fixed base on-demand and splits the rest 1 to 3.

resource "aws_ecs_service" "checkout" {
  # launch_type must be removed; it cannot coexist with a strategy

  capacity_provider_strategy {
    capacity_provider = "FARGATE"
    base              = 2
    weight            = 1
  }
  capacity_provider_strategy {
    capacity_provider = "FARGATE_SPOT"
    weight            = 3
  }
}

With 6 tasks that is 2 base, then 4 split into 1 on-demand and 3 Spot. Spot is also outside Savings Plans coverage, so if you have a commitment, moving tasks to Spot can strand part of it. Run the Savings Plans coverage agent after right-sizing settles, not before.

Step 5: Hand the LLM One Finding and One File

Each finding is a small JSON object. The model never sees the account, only this and the Terraform file that grep matched on the task family.

{
  "service": "checkout",
  "kind": "resize",
  "current": { "cpu": 2048, "memory": 8192 },
  "proposed": { "cpu": 1024, "memory": 3072 },
  "evidence": {
    "peak_cpu_units": 635, "peak_mem_mb": 2150, "window_days": 14,
    "oom_kills_30d": 0, "cpu_target_tracking": false,
    "compute_optimizer": { "cpu": 1024, "memory": 4096 }
  },
  "monthly_saving_usd": 274.65
}

The system prompt is short and restrictive:

You edit Terraform for one ECS service. You may change only: the task-level
cpu and memory arguments, the runtime_platform block, and
capacity_provider_strategy blocks. Use exactly the values in "proposed".

Before writing the diff, read every container definition and environment
variable in the file. List any setting that fixes memory or CPU inside the
container: container-level cpu, memory, or memoryReservation; JVM -Xmx or
MaxRAMPercentage; NODE_OPTIONS max-old-space-size; GOMEMLIMIT; worker or
thread counts derived from CPU. If any of them exceeds or assumes the old
size, do NOT change it. Put it first in the PR description under
"Reviewer must check".

If the file does not contain this service's task definition, return
{"skip": "reason"} and no diff.

That second paragraph is where the model earns its place. A regex finds -Xmx6g. It does not find a heap size assembled from two variables in a wrapper script, or a Gunicorn worker count set for 2 vCPU. A container-level memory of 8192 under a task-level 3072 fails at registration, which is loud. A 6 GB heap in a 3 GB task registers fine and dies under load, which is not.

A CI check on the agent's branch then enforces the first paragraph without trusting the model: it parses the diff and fails if any changed line is outside cpu, memory, runtime_platform, or capacity_provider_strategy, or if the new values differ from the finding. The model's output is a proposal, and the diff check is the control, as argued in GitOps for AI Agents.

Step 6: One Change Type per PR, in Order

The agent opens at most one PR per service at a time, in this order: resize, then arm64, then Spot. Each one waits until the previous has been merged for 7 days with zero OOM kills in the task-stop log group. Combining them saves a week and makes every rollback a guessing game.

For Spot PRs the description carries one more warning. Depending on your AWS provider version, changing capacity_provider_strategy on an existing service either updates in place with a forced deployment or destroys and recreates the service. The agent cannot know which without a plan, so the PR pipeline runs terraform plan and the diff check fails the PR if the plan contains a replacement of aws_ecs_service.

Idle findings do not get an automatic PR at all. They go to the owning team as an issue with the request graph attached, and for dev environments the suggested fix is a pair of aws_appautoscaling_scheduled_action resources that set min and max capacity to 0 at 20:00 and restore them at 07:00 on weekdays. That cuts a dev service's hours from 730 to about 240 a month without deleting anything.

Honest Limits

  • Service-level metrics hide per-container shape. AWS/ECS reports the task as a whole. If a sidecar owns half the memory, you only see the sum. Container Insights gives per-container numbers and is worth enabling on the few services where this matters.
  • Fourteen days is not a year. The peak calendar exists because no window is long enough on its own. A service nobody has registered a peak for gets a note in the PR saying so.
  • Spot capacity is not guaranteed. When Spot is unavailable, ECS does not fall back to on-demand by itself. The base of 2 is what keeps the service up, so size the base to survive a full Spot outage at low traffic.
  • arm64 image present does not mean arm64 tested. A manifest proves the image exists. Native dependencies can still behave differently, so the arm64 PR should go through staging like any other release.
  • Fargate may be the wrong answer. A steady, large fleet is often cheaper on EC2 capacity. The Lambda vs containers cost comparison covers where that line falls.

Summary

Fargate bills the size you declare, so the largest saving is almost always correcting the declaration. Collect peak CPU and memory from the free AWS/ECS metrics, snap peak plus headroom to a valid task size, and refuse to shrink anything that has been OOM-killed or whose CPU autoscaling would simply add tasks back. Check images for arm64 before proposing it, and treat Spot eligibility as a fixed rule list with an on-demand base. Let the LLM read the Terraform and find the heap flags a regex misses, and let a diff check, a plan check, and a human reviewer decide whether its PR merges.

#ai#aws#finops#cost-optimization#cloud#automation#devops#containers#terraform#serverless
D
DevToCashAuthor

Senior DevOps/SRE Engineer · 10+ years · Professional Trader (IDX, Crypto, US Equities)

I write about real infrastructure patterns and trading strategies I use in production and in live markets. No courses, no affiliate hype — just documentation of what actually works.

More about me →