StackPractices
intermediate By Mathias Paulenko

Complete Guide to AWS Cost Optimization

Reduce AWS spend 30-50% with EC2 right-sizing, Spot, Reserved Instances, Savings Plans, S3 lifecycle, RDS, networking and cost monitoring.

Introduction

AWS bills grow silently — unused resources, over-provisioned instances, and unmanaged data transfer can inflate costs by 40% or more over what the same workload should cost. This guide walks through the tactics that actually move the number: EC2 right-sizing, Spot Instances, Reserved Instances, Savings Plans, S3 lifecycle policies, RDS optimization, networking costs, and automated cost monitoring.

All commands use the AWS CLI v2 and assume credentials with billing, EC2, and CloudWatch permissions. Prices are illustrative us-east-1 on-demand figures — check the AWS Pricing pages for current rates in your region.

When to Use This Guide

Use it when you run real workloads on AWS and the bill is higher than it should be:

  • You inherited an AWS account and need a first-pass cost audit.
  • Your EC2 bill grows every month but traffic doesn’t.
  • You’re about to buy Reserved Instances and want to avoid locking into the wrong family.
  • Finance asks why the cloud budget keeps slipping.

If your problem is broader — allocating spend across teams, multi-cloud FinOps, or building a chargeback model — start with the Cloud Cost Optimization guide instead, which covers strategy rather than AWS-specific tactics.

One warning before anything else: don’t buy commitments first. Clean up waste (idle instances, unattached volumes, forgotten snapshots) before committing to Reserved Instances or Savings Plans — commitments bought on a bloated baseline just lock the waste in for one to three years.

Start With Visibility: Cost Explorer, Budgets, and the CUR

You can’t optimize what you can’t see. Three tools cover most needs: Cost Explorer for interactive analysis, Budgets for alerts, and the Cost and Usage Report (CUR) for deep dives.

Analyzing spending

# Install AWS CLI
pip install awscli

# Get cost breakdown by service
aws ce get-cost-and-usage \
  --time-period Start=2026-01-01,End=2026-02-01 \
  --granularity MONTHLY \
  --metrics BlendedCost \
  --group-by Type=SERVICE

# Get cost by tag
aws ce get-cost-and-usage \
  --time-period Start=2026-01-01,End=2026-02-01 \
  --granularity MONTHLY \
  --metrics BlendedCost \
  --group-by Type=TAG Key=Environment

Group by SERVICE first, then by TAG (Environment, Team, Project) once cost allocation tags are enabled in the Billing console. The first run almost always surfaces surprises: a forgotten NAT Gateway, a dev RDS running 24/7, an S3 bucket holding years of logs.

Setting up budgets

# Create a monthly budget alert
aws budgets create-budget \
  --account-id 123456789012 \
  --budget '{
    "BudgetName": "MonthlyBudget",
    "BudgetLimit": {"Amount": "5000", "Unit": "USD"},
    "TimeUnit": "MONTHLY",
    "BudgetType": "COST"
  }' \
  --notifications-with-subscribers '[
    {
      "Notification": {
        "NotificationType": "ACTUAL",
        "ComparisonOperator": "GREATER_THAN",
        "Threshold": 80
      },
      "Subscribers": [{
        "SubscriptionType": "EMAIL",
        "Address": "ops@example.com"
      }]
    }
  ]'

The first two budgets per account are free; additional ones cost about $0.02/day each. Set thresholds at 80% and 100% of expected spend, and add a forecasted-spend notification so you’re warned before the month ends, not after.

The Cost and Usage Report for deep dives

Cost Explorer keeps ~13 months of daily data. When you need per-resource granularity — which specific instance, bucket, or Lambda drove a spike — export the CUR to S3 and query it with Athena:

# Export daily CUR with resource IDs to S3 (Parquet)
aws cur put-report-definition --report-definition '{
  "ReportName": "monthly-cur",
  "TimeUnit": "DAILY",
  "Format": "Parquet",
  "Compression": "Parquet",
  "S3Bucket": "my-cur-bucket",
  "S3Prefix": "cur",
  "S3Region": "us-east-1",
  "ReportVersioning": "OVERWRITE_REPORT",
  "AdditionalSchemaElements": ["RESOURCES"]
}'

The RESOURCES schema element is what adds per-resource line items — without it you get service-level aggregates only. Pair it with the AWS CLI scripts recipe for reusable cost-reporting commands.

EC2 Right-Sizing

Right-sizing means matching instance size to actual load. It’s the single largest source of savings in most accounts: AWS’s own analyses and Compute Optimizer data routinely flag 20-40% of instances as over-provisioned.

Finding underutilized instances

# List CPU utilization for all EC2 instances
aws cloudwatch get-metric-statistics \
  --namespace AWS/EC2 \
  --metric-name CPUUtilization \
  --dimensions Name=InstanceId,Value=i-1234567890abcdef0 \
  --start-time 2026-01-01T00:00:00Z \
  --end-time 2026-02-01T00:00:00Z \
  --period 86400 \
  --statistics Average \
  --output table

CPU under 10-15% on average with low peaks is the classic downsize signal. Check memory too — CloudWatch doesn’t collect it by default, so install the CloudWatch agent before concluding an instance is idle; plenty of “5% CPU” boxes are memory-bound.

Right-sizing with AWS Compute Optimizer

# Enable Compute Optimizer
aws compute-optimizer enable-compute-optimizer

# Get recommendations
aws compute-optimizer get-ec2-instance-recommendations \
  --filters name=finding,values=Underprovisioned,Overprovisioned

Compute Optimizer is free and also covers EBS volumes, Lambda memory, and ECS services. It needs roughly 30 hours of CloudWatch metrics before producing recommendations, so enable it and check back the next day rather than expecting instant results.

Typical right-sizing actions

Illustrative monthly savings at us-east-1 on-demand prices:

CurrentRecommendationMonthly Savings
m5.2xlarge (avg 5% CPU)t3.large~$200
c5.4xlarge (avg 10% CPU)c5.xlarge~$250
r5.xlarge (avg 15% CPU)t3.medium~$150

Two cautions. First, downsize during a maintenance window — changing instance type requires a stop/start on EBS-backed instances and a brief outage. Second, watch burst credits on t3/t4g families: a right-sized workload that occasionally spikes can end up slower and more expensive in unlimited mode than the original oversized instance.

Spot Instances

Spot Instances sell spare EC2 capacity at up to 90% off on-demand, in exchange for the possibility of a two-minute interruption notice. They’re the right default for anything stateless and restartable: batch jobs, CI runners, data processing, stateless web tiers behind a load balancer.

EC2 Fleet and ASG mixed instances

Spot Fleet is the legacy API; AWS recommends EC2 Fleet or an Auto Scaling group with a mixed instances policy instead. An EC2 Fleet with the capacity-optimized strategy picks pools least likely to be interrupted — better than chasing the cheapest pool, which is also the one most likely to disappear:

aws ec2 create-fleet --cli-input-json '{
  "TargetCapacitySpecification": {
    "TotalTargetCapacity": 10,
    "DefaultTargetCapacityType": "spot"
  },
  "LaunchTemplateConfigs": [{
    "LaunchTemplateSpecification": {
      "LaunchTemplateId": "lt-0123456789abcdef0",
      "Version": "$Latest"
    },
    "Overrides": [
      {"InstanceType": "t3.medium", "SubnetId": "subnet-12345678"},
      {"InstanceType": "t3.large",  "SubnetId": "subnet-87654321"},
      {"InstanceType": "t3a.medium", "SubnetId": "subnet-12345678"}
    ]
  }],
  "SpotOptions": {
    "AllocationStrategy": "capacity-optimized"
  }
}'

Don’t set a maximum Spot price (SpotPrice cap). Spot pricing no longer spikes the way it did years ago; a cap adds interruption risk without saving money. Diversify across at least 3-4 instance types so a single constrained pool can’t drain your capacity.

Spot with auto-scaling groups

# Terraform — mixed on-demand + Spot ASG
resource "aws_autoscaling_group" "spot" {
  mixed_instances_policy {
    instances_distribution {
      on_demand_base_capacity                  = 1
      on_demand_percentage_above_base_capacity = 0
      spot_allocation_strategy                 = "capacity-optimized"
    }

    launch_template {
      launch_template_specification {
        launch_template_id = aws_launch_template.app.id
        version            = "$Latest"
      }

      override {
        instance_type = "t3.medium"
      }
      override {
        instance_type = "t3.large"
      }
    }
  }

  min_size         = 2
  max_size         = 10
  desired_capacity = 4
}

on_demand_base_capacity = 1 keeps a stable floor so a mass Spot interruption can’t take the whole tier down. Enable capacity rebalancing on the ASG to replace instances before they’re interrupted rather than after. If you manage this stack with Terraform modules, see the Terraform modules guide for structuring the launch template and overrides.

Spot interruption handling

Spot gives you a two-minute warning via instance metadata. Poll it with IMDSv2 (token-required) and drain the node when a notice appears:

import json
import urllib.error
import urllib.request

def _imds(path):
    token = urllib.request.urlopen(
        urllib.request.Request(
            "http://169.254.169.254/latest/api/token",
            method="PUT",
            headers={"X-aws-ec2-metadata-token-ttl-seconds": "21600"},
        )
    ).read()
    req = urllib.request.Request(
        f"http://169.254.169.254/latest/meta-data/{path}",
        headers={"X-aws-ec2-metadata-token": token},
    )
    return urllib.request.urlopen(req, timeout=1).read()

def check_spot_interruption():
    try:
        action = json.loads(_imds("spot/instance-action"))
    except urllib.error.HTTPError as e:
        if e.code != 404:  # 404 = no interruption scheduled
            raise
        return
    if action["action"] == "terminate":
        graceful_shutdown()  # drain connections, persist state

A bare except: here would hide real failures (network issues, IMDS disabled) — only swallow the expected 404. For most workloads, ASG capacity rebalancing makes manual polling unnecessary; handle it yourself only for long-running jobs that need checkpointing.

Reserved Instances and Savings Plans

Once the baseline is clean, commit to capacity for what’s left. Both RIs and Savings Plans trade flexibility for discounts of up to 72%.

TypeCommitmentDiscountBest For
Standard RI1 or 3 yearUp to 72%Steady-state workloads
Convertible RI1 or 3 yearUp to 54%Workloads that may change
Scheduled RI1 yearVariablePredictable time windows
flowchart diagram: Workload

Savings Plans

Purchases happen in the console (or via Cost Explorer recommendations), but you can inspect offerings and your existing coverage from the CLI:

# Ask AWS what commitment it would recommend
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

# List purchased plans
aws savingsplans describe-savings-plans

The commitment unit is $/hour of spend, not instance count — a --commitment "0.50" means “I’ll spend at least $0.50/hour on covered compute”, not fifty dollars. Start with the recommendation output, then under-commit: buy for 60-70% of steady-state usage and let the remainder float on-demand. If usage drops, an under-commitment wastes nothing; an over-commitment bills you for capacity nobody used.

When to use which

  • Steady-state EC2 — Standard Reserved Instances (highest discount)
  • Flexible workloads — Compute Savings Plans (apply to any instance family, region)
  • Fargate/Lambda — Compute Savings Plans (the only option that covers them)
  • S3, DynamoDB — No RIs available; optimize with lifecycle policies and capacity modes instead

S3 Cost Optimization

S3 looks cheap per GB and quietly becomes a top-3 line item. The fixes are lifecycle policies and picking the right storage class — but watch retrieval fees, which punish data you thought was cold and wasn’t.

Lifecycle policies

{
  "Rules": [
    {
      "ID": "MoveToIAAfter30Days",
      "Status": "Enabled",
      "Filter": { "Prefix": "logs/" },
      "Transitions": [
        { "Days": 30, "StorageClass": "STANDARD_IA" },
        { "Days": 90, "StorageClass": "GLACIER" },
        { "Days": 365, "StorageClass": "DEEP_ARCHIVE" }
      ]
    },
    {
      "ID": "DeleteTempFiles",
      "Status": "Enabled",
      "Filter": { "Prefix": "temp/" },
      "Expiration": { "Days": 7 }
    }
  ]
}

Mind the minimum storage durations: STANDARD_IA bills for 30 days minimum, GLACIER for 90, DEEP_ARCHIVE for 180. Transitioning an object at day 30 and deleting it at day 45 still costs the full minimum — for short-lived objects it’s often cheaper to expire from STANDARD directly.

S3 storage classes

Relative storage cost (us-east-1, storage only — retrieval fees not included):

ClassCost vs StandardUse Case
STANDARD1xFrequently accessed
STANDARD_IA0.5xInfrequently accessed (30+ days)
ONEZONE_IA0.4xInfrequently accessed, non-critical
GLACIER0.17xArchive (90+ days)
DEEP_ARCHIVE0.04xLong-term archive (365+ days)
INTELLIGENT_TIERINGVariableUnknown access patterns

Intelligent-Tiering

aws s3api put-bucket-intelligent-tiering-configuration \
  --bucket my-bucket \
  --id MoveToArchive \
  --intelligent-tiering-configuration '{
    "Status": "Enabled",
    "Tierings": [
      { "Days": 90, "AccessTier": "ARCHIVE_ACCESS" },
      { "Days": 180, "AccessTier": "DEEP_ARCHIVE_ACCESS" }
    ]
  }'

Intelligent-Tiering charges a monitoring fee (~$0.0025 per 1,000 objects/month) and no retrieval fees. It’s the right answer when access patterns are unknown; for millions of tiny objects the monitoring fee can outweigh the storage savings, so run the math on your object count first.

RDS Optimization

RDS is usually the second-largest line after EC2, and it’s almost always oversized because it was provisioned “for growth” that never came.

# Check DB instance CPU
aws cloudwatch get-metric-statistics \
  --namespace AWS/RDS \
  --metric-name CPUUtilization \
  --dimensions Name=DBInstanceIdentifier,Value=mydb \
  --start-time 2026-01-01T00:00:00Z \
  --end-time 2026-02-01T00:00:00Z \
  --period 86400 \
  --statistics Average,Maximum

RDS cost reduction strategies

  • Downsize instances — db.t4g instead of db.m5 if CPU stays under 20%
  • Reserved Instances — up to 69% discount on a 3-year commitment
  • Stop non-prod at night — RDS stops for up to 7 days, then auto-starts
  • Aurora Serverless v2 — scales down to 0 ACU and pauses for intermittent workloads
  • Delete unused snapshots — old snapshots accumulate silently
  • Use read replicas wisely — each replica costs the same as the primary; drop replicas that serve no read traffic

Graviton-based instances (db.t4g, db.r6g, db.r7g) give roughly 20% better price-performance than their x86 equivalents and need no application changes for most engines — an easy win before touching instance size.

Automated snapshot cleanup

Delete only manual snapshots — delete_db_snapshot fails on automated backups, which disappear with their retention period anyway:

import boto3
from datetime import datetime, timedelta, timezone

rds = boto3.client("rds")

def cleanup_old_snapshots(days=30):
    cutoff = datetime.now(timezone.utc) - timedelta(days=days)
    paginator = rds.get_paginator("describe_db_snapshots")

    for page in paginator.paginate(SnapshotType="manual"):
        for snap in page["DBSnapshots"]:
            if snap["SnapshotCreateTime"] >= cutoff:
                continue
            try:
                rds.delete_db_snapshot(
                    DBSnapshotIdentifier=snap["DBSnapshotIdentifier"]
                )
                print(f"Deleted: {snap['DBSnapshotIdentifier']}")
            except rds.exceptions.InvalidDBSnapshotStateException:
                continue  # snapshot in use or being copied

Filter on SnapshotType="manual" server-side rather than inspecting attributes client-side, and compare timestamps as timezone-aware values — describe_db_snapshots returns aware datetimes, so a naive datetime.now() raises on comparison.

Graviton, EBS, and Elastic IPs

Three quiet levers that rarely make the headline tactics:

  • Graviton (m7g, c7g, r7g, t4g): ~20% better price-performance than equivalent x86 instances. Migration is usually an AMI swap for Linux workloads; check for architecture-specific dependencies first.
  • EBS gp3 over gp2: gp3 is ~20% cheaper per GB with baseline performance included. aws ec2 modify-volume --volume-id vol-0123 --volume-type gp3 migrates in place, no downtime.
  • Unattached volumes and IPs: volumes in available state and unassociated Elastic IPs bill for doing nothing.
# Unattached EBS volumes
aws ec2 describe-volumes \
  --filters Name=status,Values=available \
  --query 'Volumes[*].VolumeId' --output text

# Unused Elastic IPs (billed ~$0.005/hr each)
aws ec2 describe-addresses \
  --query 'Addresses[?AssociationId==`null`].AllocationId' --output text

Networking Costs

Data transfer is the most underestimated AWS charge — it’s invisible until it’s large.

ScenarioCost
Inbound data transferFree
Same AZ data transferFree (private IPs)
Cross-AZ data transfer$0.01/GB each direction
Cross-region data transfer$0.02-0.09/GB
Internet egress~$0.09/GB
NAT Gateway~$0.045/hr + $0.045/GB processed

A NAT Gateway at 1 TB/month costs $45 in processing alone — more than many EC2 instances. Two fixes: put a gateway VPC endpoint for S3 and DynamoDB in front of traffic that would cross the NAT (they’re free), and add interface endpoints for the AWS services you hit hardest ($0.01/hr each).

# Terraform — Gateway endpoint for S3 (free)
resource "aws_vpc_endpoint" "s3" {
  vpc_id          = aws_vpc.main.id
  service_name    = "com.amazonaws.us-east-1.s3"
  route_table_ids = [aws_route_table.private.id]
}

# Interface endpoint (~$0.01/hr) for frequently called services
resource "aws_vpc_endpoint" "dynamodb" {
  vpc_id            = aws_vpc.main.id
  service_name      = "com.amazonaws.us-east-1.dynamodb"
  vpc_endpoint_type = "Interface"
  subnet_ids        = aws_subnet.private[*].id
}
flowchart diagram: Private subnets

Beyond endpoints: co-locate dependent services in the same AZ (cross-AZ charges apply to both directions), put CloudFront in front of egress-heavy origins (edge data transfer is cheaper than direct egress and caching eliminates origin hits), and compress responses — less data is less egress, period.

Automated Cost Monitoring

Manual reviews drift. Two automations catch regressions early: Cost Anomaly Detection for sudden spikes and a scheduled Lambda for recurring reports.

AWS Cost Anomaly Detection

# Enable cost anomaly detection (free)
aws ce create-anomaly-monitor \
  --anomaly-monitor '{
    "MonitorName": "DailyAnomaly",
    "MonitorType": "DIMENSIONAL",
    "MonitorSpecification": "{\"Dimension\":\"SERVICE\"}"
  }'

The dimensional monitor watches per-service spend and learns seasonality, so a Monday batch spike doesn’t page you while a runaway Lambda does. Pair each monitor with an alert subscription (SNS topic → email/Slack) — the monitor alone detects but doesn’t notify.

Cost reports with Lambda

import boto3

ce = boto3.client("ce")

def lambda_handler(event, context):
    response = ce.get_cost_and_usage(
        TimePeriod={"Start": "2026-06-01", "End": "2026-07-01"},
        Granularity="MONTHLY",
        Metrics=["UnblendedCost"],
        GroupBy=[{"Type": "SERVICE", "Key": "Service"}],
    )

    costs = []
    for group in response["ResultsByTime"][0]["Groups"]:
        service = group["Keys"][0]
        amount = float(group["Metrics"]["UnblendedCost"]["Amount"])
        if amount > 100:
            costs.append(f"{service}: ${amount:.2f}")

    if costs:
        send_slack_notification("\n".join(costs))  # your webhook helper

    return {"statusCode": 200}

Schedule it with EventBridge on the first of the month. For dashboards beyond reports, the Grafana observability guide covers wiring CloudWatch metrics into a monitoring stack.

Best Practices

  • Enable Cost Explorer — visibility is the first step to optimization
  • Set up budget alerts — catch overruns before they happen
  • Right-size every 3 months — workloads change, instances should too
  • Use Spot for 70%+ of non-critical workloads — up to 90% discount
  • Commit to RIs/Savings Plans for baseline — cover 60-70% of steady-state, not all of it
  • Use S3 lifecycle policies — move old data to cheaper tiers automatically
  • Stop non-prod at night — roughly 65% of non-prod hours are idle
  • Delete unused EBS volumes — they cost money even when unattached
  • Release unused Elastic IPs — ~$0.005/hr each when not attached
  • Use VPC endpoints — avoid NAT Gateway data processing charges
  • Prefer Graviton and gp3 — ~20% savings for a config change
  • Tag everything — enable cost allocation by team/project
  • Review monthly — costs creep without regular review

Common Mistakes

  • Buying RIs before cleaning waste — you commit to a bloated baseline for 1-3 years
  • Leaving EC2 instances running 24/7 in dev — use auto-stop schedules
  • Using S3 Standard for archive data — lifecycle to Glacier/Deep Archive
  • Ignoring retrieval fees and minimum durations — cold storage isn’t free to thaw
  • Over-provisioning RDS — downsize based on actual CPU/memory
  • Ignoring NAT Gateway costs — use VPC endpoints for AWS service traffic
  • Not using Spot for batch/cron jobs — 90% savings for interruptible workloads
  • Setting a Spot price cap — capacity-optimized allocation beats price caps
  • Forgetting to delete old snapshots — they accumulate silently over months
  • Not tagging resources — no visibility into team/project costs
  • Using CloudWatch Logs with no retention — log volumes grow unbounded
  • Ignoring data transfer costs — cross-AZ and cross-region add up fast

See Also

Frequently Asked Questions

How much can I save with AWS cost optimization?

Organizations optimizing for the first time typically cut 30-50% of spend. The biggest wins come from right-sizing (15-20%), Spot instances on eligible workloads (10-15%), and RI/Savings Plans on steady state (10-15%). S3 lifecycle and networking fixes add another 5-10%.

Should I use Reserved Instances or Savings Plans?

Standard RIs fit stable EC2 workloads pinned to one instance family and reach up to 72% off. Compute Savings Plans trade a few points of discount for flexibility across families, regions, Fargate and Lambda — AWS recommends them for most new commitments. When in doubt, Savings Plans.

How do I track costs by team or project?

Tag every resource with Team, Project, and Environment, then activate those tags as Cost Allocation Tags in the Billing console. Cost Explorer and the CUR can then filter and group by them. Tags only apply to cost data from the moment they're activated — they don't backfill.

Are Spot Instances safe for production?

For stateless tiers behind a load balancer, yes — keep an on-demand base in the ASG and enable capacity rebalancing. For stateful or singleton workloads, no: a two-minute eviction notice is not a graceful failure mode. Batch and CI workloads are the safest starting point.

Does migrating to Graviton require code changes?

Usually not for Linux workloads on managed runtimes (Python, Node, Java, Go). Compiled C extensions or x86-specific binaries need ARM rebuilds. Test on a t4g burstable instance first — they're the cheapest way to verify compatibility.

What does a NAT Gateway really cost?

About $0.045/hr (~$33/month) per gateway, plus $0.045/GB processed. One gateway handling 1 TB/month adds ~$45 in processing charges. Gateway VPC endpoints for S3 and DynamoDB are free and remove most of that traffic.