Thuta Learning
AWS Advanced
Reliability & OperationsDevOpsAdvanced

Cost Optimization: See It, Guard It, Reduce It

AWS AdvancedLesson 2850 min

What you'll walk away with

  • Break down spend with Cost Explorer, the Cost and Usage Report / Data Exports and cost allocation tags
  • Put guardrails in place with AWS Budgets and Cost Anomaly Detection
  • Decide when to use Savings Plans, Reserved Instances, Spot and Graviton
  • Find and fix cost traps such as NAT Gateway data processing, cross-AZ transfer and unattached EBS volumes
  • Control storage cost with S3 lifecycle rules and log retention

Explain it simply

Like a household electricity bill

With one electricity bill and no idea which room uses what, saving is hard — so first you fit a meter in every room (tags, in AWS). Then you switch off lights in empty rooms (idle resources), stop air-conditioning a whole hall for one person (right-sizing) and switch to more efficient bulbs (Graviton).

For the amount you will certainly use every day, a long-term contract is cheaper (Savings Plans), and flexible chores run when power is cheap (Spot). The order matters: see it, remove waste, and only then commit.

Problem → Why → Solution

The bill more than doubled in six months

A startup's monthly AWS bill more than doubled in six months and nobody knows why. All teams share one account with no tags. The biggest line in Cost Explorer is 'EC2 - Other' — which is not instances at all, but a category lumping together NAT Gateway, EBS volumes, snapshots and data transfer.

The investigation finds a data pipeline in private subnets reading terabytes from S3 through a NAT Gateway (paying a processing fee on every GB), 140 unattached EBS volumes left behind by deleted instances, and debug logs with no retention. Each looked small on its own; together they were a third of the bill.

where-did-it-go.sh
aws ce get-cost-and-usage \
  --time-period Start=2026-10-01,End=2026-11-01 \
  --granularity MONTHLY --metrics UnblendedCost \
  --group-by Type=DIMENSION,Key=SERVICE \
  --query 'ResultsByTime[0].Groups[].[Keys[0],Metrics.UnblendedCost.Amount]' \
  --output text | sort -k2 -nr | head -5
# EC2 - Other                    <- NAT, EBS, snapshots, data transfer
# Amazon Elastic Compute Cloud - Compute
# ...

Cost is a property of the architecture

Without visibility and ownership, waste piles up silently. The biggest items hide in categories like 'EC2 - Other' and data transfer, so looking only at instance prices never finds them. Learning about it from the bill means you are already a month late.

See it → guard it → reduce it

Cost allocation tag
A tag key (for example team or cost-center) activated in the Billing console — only after activation can Cost Explorer and billing data be grouped by it.

Visibility comes first. Cost Explorer is the quickest way to group by service, account, Region, usage type and tag, and to see trends. For detail, AWS Data Exports (including Cost and Usage Report 2.0) delivers line-item billing data to S3 for querying with Athena. Tags are the foundation of ownership: teams take responsibility once they can see their own spend.

Guardrails come second. AWS Budgets compares actual and forecasted spend to thresholds and sends alerts, and budget actions can respond by applying an IAM policy or SCP or stopping instances. Cost Anomaly Detection uses machine learning to learn normal spend patterns and flags unexpected increases within days, instead of at the end of the month.

Then reduce — in order. First remove waste: idle resources, unattached EBS volumes, snapshots nobody needs. Second right-size: AWS Compute Optimizer reads CloudWatch utilization and recommends smaller sizes or Graviton for EC2, Auto Scaling groups, EBS, Lambda and Fargate. Graviton (Arm-based) instances give better price-performance for many workloads but need arm64 builds, so measure with your own workload.

Only then commit. Savings Plans give a discount for committing to a dollar-per-hour amount for one or three years: Compute Savings Plans flex across EC2 instance family, Region and OS and also cover Fargate and Lambda, while EC2 Instance Savings Plans are tied to one family in one Region for a deeper discount and less flexibility. Reserved Instances remain the main commitment option for database services such as RDS, ElastiCache, OpenSearch and Redshift. Spot sells spare AWS capacity at a large discount but can be reclaimed with a two-minute interruption notice, so it suits only fault-tolerant work such as stateless services, batch and CI.

LeverBest forWatch out for
Savings PlansSteady baseline computeNever commit to the peak
Reserved InstancesDatabases such as RDS, ElastiCacheLess flexible if engine or size changes
SpotBatch, CI, stateless fleetsInterruptions — diversify instance types
GravitonMost Linux workloadsarm64 builds and dependencies
Right-sizingAnything with low utilizationCheck peaks and memory, not just average CPU
text
THE NAT GATEWAY TRAP AND ITS FIX
--------------------------------
 BEFORE                                   AFTER
 [private subnet]                         [private subnet]
   | 5 TB/month to S3                       | 5 TB/month to S3
   v                                        v
 [NAT Gateway]  <- per hour + per GB      [S3 gateway endpoint]
   |               processed                | no hourly, no per-GB fee
   v                                        v
 [Internet gateway] --> [Amazon S3]       [Amazon S3]

 Same for DynamoDB. Other services: interface endpoints (cheaper per GB
 than NAT, but billed per hour per AZ) - do the maths per service.
The order of savings
  1. See it: tags + Cost Explorer
  2. Guard it: Budgets + anomaly alerts
  3. Remove waste (idle, unattached)
  4. Right-size, then move to Graviton
  5. Commit last: Savings Plans / RIs

Buy a commitment first and you lock in the waste for one or three years. Never run the order backwards.

Cost by service and team tag

cost-by-team.sh
aws ce get-cost-and-usage \
  --time-period Start=2026-10-01,End=2026-11-01 \
  --granularity MONTHLY \
  --metrics UnblendedCost \
  --group-by Type=DIMENSION,Key=SERVICE Type=TAG,Key=team

--group-by accepts up to two groupings: here service and the team tag. Untagged resources appear under 'team$' (an empty value) — that amount is a good measure of your tagging coverage. The end date is exclusive, so 2026-11-01 means all of October.

A waste finder: unattached volumes, orphaned snapshots, idle IPs

This script is read-only — it deletes nothing. It finds unattached EBS volumes, snapshots whose source volume no longer exists (excluding those backing your own AMIs) and Elastic IPs not attached to anything, and estimates the monthly cost. Prices are approximate for us-east-1; always check the pricing page. Run it per account and per Region.

find_waste.py
import boto3

# Approximate us-east-1 prices in USD - always confirm on the pricing page
GB_MONTH = {"gp2": 0.10, "gp3": 0.08}
IPV4_MONTH = 0.005 * 730  # public IPv4 address: hourly rate x hours per month

ec2 = boto3.client("ec2", region_name="us-east-1")
ACCOUNT = boto3.client("sts").get_caller_identity()["Account"]


def name_of(resource):
    for tag in resource.get("Tags", []):
        if tag["Key"] == "Name":
            return tag["Value"]
    return "(no Name tag)"


def find_waste():
    findings = []
    volumes = []
    for page in ec2.get_paginator("describe_volumes").paginate():
        volumes.extend(page["Volumes"])
    live_ids = {v["VolumeId"] for v in volumes}

    for v in volumes:
        if v["State"] == "available":  # not attached to anything
            cost = v["Size"] * GB_MONTH.get(v["VolumeType"], 0.10)
            detail = f"{v['Size']} GiB {v['VolumeType']}"
            findings.append(("unattached volume", name_of(v), detail, cost))

    # Snapshots that back one of our AMIs are still in use
    ami_snaps = {
        bdm["Ebs"]["SnapshotId"]
        for image in ec2.describe_images(Owners=["self"])["Images"]
        for bdm in image.get("BlockDeviceMappings", [])
        if "SnapshotId" in bdm.get("Ebs", {})
    }
    pages = ec2.get_paginator("describe_snapshots").paginate(
        OwnerIds=["self"], Filters=[{"Name": "owner-id", "Values": [ACCOUNT]}]
    )
    for page in pages:
        for s in page["Snapshots"]:
            if s["VolumeId"] not in live_ids and s["SnapshotId"] not in ami_snaps:
                detail = f"from {s['VolumeSize']} GiB volume"
                findings.append(("orphaned snapshot", name_of(s), detail, None))

    for a in ec2.describe_addresses()["Addresses"]:
        if "AssociationId" not in a:  # allocated but not attached
            findings.append(("idle Elastic IP", name_of(a), "public IPv4", IPV4_MONTH))
    return sorted(findings, key=lambda f: (f[0], f[1]))


if __name__ == "__main__":
    total = 0.0
    for kind, name, detail, cost in find_waste():
        estimate = f"~{cost:.2f} USD/month" if cost else "review manually"
        print(f"{kind:<18} {name:<21} {detail:<20} {estimate}")
        total += cost or 0
    print(f"Estimated waste: ~{total:.2f} USD/month (plus snapshot storage)")

Not runnable in the browser

This code runs against a real AWS account, so it cannot run in the browser playground. Try it in your own terminal or in AWS CloudShell.

Code breakdown

  1. Paginate everythingfor page in ec2.get_paginator("describe_volumes").paginate():

    Large accounts can have thousands of volumes and snapshots, and one describe call returns a single page. Without a paginator you silently stop after page one and conclude there is no waste.

  2. Unattached = state 'available'if v["State"] == "available":

    An EBS volume is billed per provisioned GiB even when attached to nothing. State 'available' means not attached. Taking a final snapshot before deleting is the safe move.

  3. Orphaned, but not AMI-backingif s["VolumeId"] not in live_ids and s["SnapshotId"] not in ami_snaps:

    Snapshots whose source volume is gone may be waste, but snapshots backing your own AMIs are still needed until the AMI is deregistered. Some are kept for compliance too, so the script only says 'review manually'.

  4. Idle public IPv4if "AssociationId" not in a:

    Public IPv4 addresses are billed hourly whether attached or not. An Elastic IP that is not associated is certainly paying for nothing.

You should see
idle Elastic IP    old-bastion-ip        public IPv4          ~3.65 USD/month
orphaned snapshot  pre-migration-backup  from 200 GiB volume  review manually
unattached volume  jenkins-tmp           100 GiB gp3          ~8.00 USD/month
unattached volume  old-build-cache       500 GiB gp2          ~50.00 USD/month
Estimated waste: ~61.65 USD/month (plus snapshot storage)

Guardrails: tags, Budgets and anomaly alerts

Tag keys appear in billing data only after activation. Then add a budget that alerts when the forecast will exceed it (before actual spend does) and a per-service anomaly monitor that emails a daily summary when an anomaly's total impact exceeds $100.

notifications.json
[
  {
    "Notification": {
      "NotificationType": "FORECASTED",
      "ComparisonOperator": "GREATER_THAN",
      "Threshold": 100,
      "ThresholdType": "PERCENTAGE"
    },
    "Subscribers": [{ "SubscriptionType": "EMAIL", "Address": "finops@example.com" }]
  },
  {
    "Notification": {
      "NotificationType": "ACTUAL",
      "ComparisonOperator": "GREATER_THAN",
      "Threshold": 80,
      "ThresholdType": "PERCENTAGE"
    },
    "Subscribers": [{ "SubscriptionType": "EMAIL", "Address": "finops@example.com" }]
  }
]
guardrails.sh
aws ce update-cost-allocation-tags-status \
  --cost-allocation-tags-status TagKey=team,Status=Active TagKey=env,Status=Active

BUDGET='BudgetName=monthly-total,BudgetLimit={Amount=10000,Unit=USD},'
BUDGET+='TimeUnit=MONTHLY,BudgetType=COST'
aws budgets create-budget \
  --account-id 111122223333 \
  --budget "$BUDGET" \
  --notifications-with-subscribers file://notifications.json

MONITOR='{"MonitorName":"by-service","MonitorType":"DIMENSIONAL",'
MONITOR+='"MonitorDimension":"SERVICE"}'
MONITOR_ARN=$(aws ce create-anomaly-monitor --anomaly-monitor "$MONITOR" \
  --query MonitorArn --output text)

SUB_ARN=$(aws ce create-anomaly-subscription \
  --anomaly-subscription file://anomaly-subscription.json \
  --query SubscriptionArn --output text)
anomaly-subscription.json
{
  "SubscriptionName": "daily-anomalies",
  "MonitorArnList": [
    "arn:aws:ce::111122223333:anomalymonitor/0a1b2c3d-4e5f-6789-abcd-ef0123456789"
  ],
  "Subscribers": [{ "Type": "EMAIL", "Address": "finops@example.com" }],
  "Frequency": "DAILY",
  "ThresholdExpression": {
    "Dimensions": {
      "Key": "ANOMALY_TOTAL_IMPACT_ABSOLUTE",
      "MatchOptions": ["GREATER_THAN_OR_EQUAL"],
      "Values": ["100"]
    }
  }
}

Fixing the classic cost traps

  • NAT Gateway data processing — add gateway VPC endpoints (free) for S3 and DynamoDB traffic; for other services compare interface endpoints with NAT using your GB volume
  • Cross-AZ data transfer — traffic between AZs is billed per GB in each direction; look at chatty microservices and replication traffic and consider AZ-local routing
  • Inter-Region data transfer — every cross-Region replication and backup copy is billed per GB, so replicate only what you need
  • Idle resources — switch dev/test environments off at night and at weekends; a 60-hour office week is only 36% of 168 hours
  • Unattached EBS volumes and old snapshots — automate snapshot retention with Amazon Data Lifecycle Manager or AWS Backup lifecycle
  • Log retention — set retention on every log group and control the log level you ingest
fix-traps.sh
# S3 traffic from private subnets stops going through the NAT Gateway
aws ec2 create-vpc-endpoint \
  --vpc-id vpc-0a1b2c3d4e5f67890 \
  --vpc-endpoint-type Gateway \
  --service-name com.amazonaws.us-east-1.s3 \
  --route-table-ids rtb-0a1b2c3d4e5f67890 rtb-0f9e8d7c6b5a43210

aws logs put-retention-policy \
  --log-group-name /aws/lambda/checkout --retention-in-days 30

aws s3api put-bucket-lifecycle-configuration \
  --bucket app-logs-111122223333 \
  --lifecycle-configuration file://lifecycle.json

# Right-sizing and commitment recommendations
aws compute-optimizer update-enrollment-status --status Active
aws compute-optimizer get-ec2-instance-recommendations \
  --query 'instanceRecommendations[].[instanceArn,finding]' --output table
aws ce get-savings-plans-purchase-recommendation \
  --savings-plans-type COMPUTE_SP --term-in-years ONE_YEAR \
  --payment-option NO_UPFRONT --lookback-period-in-days THIRTY_DAYS
lifecycle.json
{
  "Rules": [
    {
      "ID": "logs-tiering",
      "Status": "Enabled",
      "Filter": { "Prefix": "logs/" },
      "Transitions": [
        { "Days": 30, "StorageClass": "STANDARD_IA" },
        { "Days": 90, "StorageClass": "GLACIER_IR" }
      ],
      "Expiration": { "Days": 365 },
      "NoncurrentVersionExpiration": { "NoncurrentDays": 30 },
      "AbortIncompleteMultipartUpload": { "DaysAfterInitiation": 7 }
    }
  ]
}

Lifecycle does not always save money

Standard-IA and the Glacier classes have minimum storage durations and a minimum billable object size, and each transition request is charged. With millions of tiny objects, transitioning can cost more than it saves. If you do not know the access pattern, consider S3 Intelligent-Tiering.

In production

How teams practice FinOps in production

Tagging is enforced as default tags in IaC and checked with AWS Organizations tag policies. Per-team cost reports (showback) are generated automatically from Data Exports with Athena and reviewed weekly. Mature teams watch unit economics such as cost per order — a bill that grows with traffic is normal; a growing cost per order is a problem.

Savings Plans are committed against the steady baseline, never the peak, with coverage and utilization reviewed monthly; teams tend to buy in several small tranches over time rather than one big purchase. Container and CI fleets mix an On-Demand baseline with Spot across many instance types, using capacity-optimized allocation to reduce interruptions. Some teams show IaC cost estimates in pull requests so engineers see cost before it ships.

Budgets and anomaly alerts are part of the IaC account baseline, so every new account gets guardrails automatically. Every alert has an owning team.

Common mistakes

Common mistakes

Committing before right-sizing

Buying a three-year Savings Plan on an oversized fleet locks the waste in at a discount. When you right-size later you can no longer use the full commitment and pay for the unused part anyway.

Routing S3 and DynamoDB traffic through a NAT Gateway

A NAT Gateway charges a processing fee on every GB that passes through it. Gateway endpoints for S3 and DynamoDB are free and only add a route table entry — one of the quickest wins for data pipelines.

Putting stateful workloads on Spot

Spot instances can be reclaimed with a two-minute notice. Put a stateful single instance such as a database primary on Spot and the outage costs more than the savings. Use Spot only for work that can checkpoint or retry.

Right-sizing on average CPU alone

Average CPU can be 10% while memory is full or a daily batch peaks. EC2 memory metrics need the CloudWatch agent, so check peaks and memory before applying Compute Optimizer recommendations.

💰 Cost & Cleanup

This lab's script is read-only and the API calls it makes are free. The Cost Explorer console is free, but each Cost Explorer API request is charged (roughly one cent per request — check the pricing page), so be careful calling it in loops. Cost Anomaly Detection is free. Basic budget tracking is generally free, while budget actions beyond a free allowance are charged per day. Data Exports are free but you pay for S3 storage and Athena queries. Compute Optimizer's default recommendations are free; enhanced infrastructure metrics are paid. Gateway VPC endpoints are free.

After the lab, delete the test budget and the anomaly subscription and monitor. Keep the gateway endpoint, log retention and lifecycle rule — they save money.

Clean up when you are done

cleanup.sh
aws budgets delete-budget --account-id 111122223333 --budget-name monthly-total
aws ce delete-anomaly-subscription --subscription-arn "$SUB_ARN"
aws ce delete-anomaly-monitor --monitor-arn "$MONITOR_ARN"

Mini challenge

The hidden storage cost of stopped instances

Stopped EC2 instances do not pay for compute, but their attached EBS volumes are still billed. Write a function that finds each stopped instance's EBS storage and estimates its monthly cost.

  • Find only stopped instances with the instance-state-name filter (use a paginator)
  • Sum the GiB of the volumes attached to each instance
  • Estimate the monthly cost with the GB_MONTH price table from the example
  • Print the instance's Name tag

Expected: For a stopped instance 'legacy-reporting' with an 8 GiB gp2 root volume and a 300 GiB gp3 data volume it prints 'stopped instance legacy-reporting: 308 GiB EBS, ~24.80 USD/month', and running instances are not listed.

Show hint

describe_volumes with the attachment.instance-id filter returns one instance's volumes. Do not forget the root volume — it is an EBS volume too.

Show solution
stopped_storage.py
import boto3

GB_MONTH = {"gp2": 0.10, "gp3": 0.08}  # approximate us-east-1 USD
ec2 = boto3.client("ec2", region_name="us-east-1")


def name_of(resource):
    for tag in resource.get("Tags", []):
        if tag["Key"] == "Name":
            return tag["Value"]
    return "(no Name tag)"


def monthly_cost(volumes):
    return sum(v["Size"] * GB_MONTH.get(v["VolumeType"], 0.10) for v in volumes)


def stopped_instance_storage():
    results = []
    pages = ec2.get_paginator("describe_instances").paginate(
        Filters=[{"Name": "instance-state-name", "Values": ["stopped"]}]
    )
    for page in pages:
        for reservation in page["Reservations"]:
            for inst in reservation["Instances"]:
                iid = inst["InstanceId"]
                attached = {"Name": "attachment.instance-id", "Values": [iid]}
                volumes = ec2.describe_volumes(Filters=[attached])["Volumes"]
                gib = sum(v["Size"] for v in volumes)
                results.append((name_of(inst), gib, monthly_cost(volumes)))
    return sorted(results)


if __name__ == "__main__":
    for name, gib, cost in stopped_instance_storage():
        print(f"stopped instance {name}: {gib} GiB EBS, ~{cost:.2f} USD/month")

Quick quiz 1 / 3

What is the right order for reducing EC2 cost?

Quick quiz 2 / 3

Jobs in private subnets read terabytes from S3 each month and NAT Gateway cost is high. What is the best fix?

Quick quiz 3 / 3

Which workload is the best fit for Spot?

What to remember

  • See it: activate cost allocation tags and use Cost Explorer and Data Exports
  • Guard it: forecast budget alerts and Cost Anomaly Detection warn you before the bill arrives
  • In order: remove waste → right-size/Graviton → then commit Savings Plans/RIs to the baseline
  • Spot is only for work that tolerates interruption, spread across many instance types
  • NAT data processing, cross-AZ/inter-Region transfer, unattached EBS and log retention are the classic traps

AWS Cost Management User Guide — AWS Documentation

Savings Plans User Guide — AWS Documentation

AWS Compute Optimizer User Guide — AWS Documentation

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Cost Optimization: See It, Guard It, Reduce It | Thuta Learning