December 1, 2026

AWS EC2 costs are the largest line item for most cloud budgets. A typical mid-sized company wastes 30-40% on idle, over-provisioned, or poorly purchased instances. This guide covers every optimization lever with real numbers from production environments.

The Cost Hierarchy

Right-sizing > Purchasing Model > Architecture > Configuration

Fix in order. A reserved t3.medium costs less than an on-demand t3.small.

Phase 1: Right-Sizing (Immediate 20-40% Savings)

The Metric That Matters: CPU Utilization

# Get utilization for all instances (last 14 days)
aws cloudwatch get-metric-statistics \
  --namespace AWS/EC2 \
  --metric-name CPUUtilization \
  --dimensions Name=InstanceId,Value=i-xxxxx \
  --start-time $(date -d '14 days ago' --iso-8601) \
  --end-time $(date --iso-8601) \
  --period 3600 \
  --statistics Average,Maximum \
  --output table

Right-Sizing Rules

Current Avg CPU Action
< 10% Downsize 2+ sizes
10-20% Downsize 1 size
20-40% Consider downsize
40-70% Optimal range
70-85% Monitor, consider upsize
> 85% Upsize immediately

Memory Utilization (Often Overlooked)

# Install CloudWatch agent for memory metrics
# Then check:
aws cloudwatch get-metric-statistics \
  --namespace CWAgent \
  --metric-name mem_used_percent \
  --dimensions Name=InstanceId,Value=i-xxxxx \
  --start-time $(date -d '14 days ago' --iso-8601) \
  --end-time $(date --iso-8601) \
  --period 3600 \
  --statistics Average,Maximum

Rule: If both CPU < 20% AND memory < 40% for 14 days → downsize.

Automated Right-Sizing Script

# scripts/rightsize.py
import boto3
import json
from datetime import datetime, timedelta

ec2 = boto3.client('ec2')
cw = boto3.client('cloudwatch')

def get_utilization(instance_id, days=14):
    cpu = cw.get_metric_statistics(
        Namespace='AWS/EC2',
        MetricName='CPUUtilization',
        Dimensions=[{'Name': 'InstanceId', 'Value': instance_id}],
        StartTime=datetime.utcnow() - timedelta(days=days),
        EndTime=datetime.utcnow(),
        Period=3600,
        Statistics=['Average', 'Maximum']
    )
    avg_cpu = sum(p['Average'] for p in cpu['Datapoints']) / len(cpu['Datapoints'])
    max_cpu = max(p['Maximum'] for p in cpu['Datapoints'])
    return avg_cpu, max_cpu

def recommend_instance(current_type, avg_cpu, max_cpu):
    # Instance family hierarchy (simplified)
    families = {
        't3': ['nano', 'micro', 'small', 'medium', 'large', 'xlarge', '2xlarge'],
        'm5': ['large', 'xlarge', '2xlarge', '4xlarge', '8xlarge', '12xlarge', '16xlarge', '24xlarge'],
        'c5': ['large', 'xlarge', '2xlarge', '4xlarge', '9xlarge', '12xlarge', '16xlarge', '24xlarge'],
        'r5': ['large', 'xlarge', '2xlarge', '4xlarge', '8xlarge', '12xlarge', '16xlarge', '24xlarge'],
    }

    family, size = current_type.split('.')
    idx = families[family].index(size)

    if avg_cpu < 10 and max_cpu < 40 and idx > 0:
        return f"{family}.{families[family][idx-1]}"
    elif avg_cpu < 20 and max_cpu < 60 and idx > 0:
        return f"{family}.{families[family][idx-1]}"
    elif avg_cpu > 85 or max_cpu > 95:
        if idx < len(families[family]) - 1:
            return f"{family}.{families[family][idx+1]}"
    return current_type

# Run for all running instances
instances = ec2.describe_instances(Filters=[{'Name': 'instance-state-name', 'Values': ['running']}])
for reservation in instances['Reservations']:
    for instance in reservation['Instances']:
        instance_id = instance['InstanceId']
        current_type = instance['InstanceType']
        avg_cpu, max_cpu = get_utilization(instance_id)
        recommended = recommend_instance(current_type, avg_cpu, max_cpu)
        if recommended != current_type:
            print(f"{instance_id}: {current_type} -> {recommended} (avg: {avg_cpu:.1f}%, max: {max_cpu:.1f}%)")

Phase 2: Purchasing Models (30-70% Savings)

Model Comparison (t3.medium, us-east-1, Linux, 2024 pricing)

Model Hourly Monthly (730h) Savings vs On-Demand Commitment
On-Demand $0.0416 $30.37 Baseline None
Savings Plan 1yr No Upfront $0.0287 $20.95 31% 1 year
Savings Plan 1yr Partial Upfront $0.0249 $18.18 40% 1 year + $
Savings Plan 1yr All Upfront $0.0221 $16.13 47% 1 year + $$
Savings Plan 3yr No Upfront $0.0198 $14.45 52% 3 years
Reserved Instance 1yr No Upfront $0.0287 $20.95 31% 1 year
Reserved Instance 1yr Partial $0.0249 $18.18 40% 1 year + $
Reserved Instance 3yr All Upfront $0.0143 $10.44 66% 3 years + $$$
Spot (current) ~$0.0125 ~$9.13 ~70% None (interruptible)

Savings Plans vs Reserved Instances

Use Savings Plans when:

  • You need flexibility across instance families/sizes
  • Workloads change (migrate from m5 to c5, etc.)
  • Multiple accounts in AWS Organization
  • You want automatic application

Use Reserved Instances when:

  • Specific instance type/family/region for 1-3 years
  • Need capacity reservation (zonal RI)
  • Want to sell on RI Marketplace
  • Simpler billing (per-instance)

Compute Savings Plan (Recommended for Most)

# Purchase via CLI
aws savingsplans create-savings-plan \
  --savings-plan-offering-id  \
  --commitment "0.50" \
  --purchase-time $(date --iso-8601)

# Find offering IDs
aws savingsplans describe-savings-plans-offerings \
  --plan-type Compute \
  --payment-option "No Upfront" \
  --duration-seconds 31536000 \
  --currency USD \
  --max-results 10

Compute Savings Plan: Applies to EC2, Fargate, Lambda. Most flexible.

EC2 Instance Savings Plan: Specific to instance family in region. Higher discount, less flexible.

Spot Instances (70%+ Savings)

Safe workloads for Spot:

  • Batch processing, CI/CD workers
  • Stateless web servers (ASG with mixed instances)
  • Container workloads (ECS/EKS with capacity providers)
  • Development/test environments
  • Spark/Hadoop workers

Unsafe for Spot:

  • Databases (unless multi-AZ with fast failover)
  • Single-instance production services
  • Workloads with >5 min checkpoint interval
  • Stateful applications

Spot Best Practices

# ASG MixedInstancesPolicy (CloudFormation)
AutoScalingGroup:
  Type: AWS::AutoScaling::AutoScalingGroup
  Properties:
    MixedInstancesPolicy:
      LaunchTemplate:
        LaunchTemplateSpecification:
          LaunchTemplateId: !Ref LaunchTemplate
          Version: '$Latest'
        Overrides:
          - InstanceType: m5.large
          - InstanceType: m5.xlarge
          - InstanceType: m5a.large
          - InstanceType: m5a.xlarge
          - InstanceType: m4.large
          - InstanceType: m4.xlarge
      InstancesDistribution:
        OnDemandBaseCapacity: 2
        OnDemandPercentageAboveBaseCapacity: 30
        SpotAllocationStrategy: capacity-optimized-prioritized
        SpotInstancePools: 4
        SpotMaxPrice: ""  # Don't set max price

Key settings:

  • capacity-optimized-prioritized – AWS picks pools with most capacity
  • SpotInstancePools: 4+ – Diversify across instance types
  • No SpotMaxPrice – Let AWS manage, prevents capacity loss

Spot Fleet / EC2 Fleet

# EC2 Fleet (replaces Spot Fleet)
aws ec2 create-fleet \
  --launch-template-configs file://fleet-config.json \
  --target-capacity-specification "TotalTargetCapacity=10,OnDemandTargetCapacity=3,DefaultTargetCapacityType=spot" \
  --spot-options "AllocationStrategy=capacity-optimized,InstancePoolsToUseCount=4"

# fleet-config.json
{
  "LaunchTemplateSpecification": {
    "LaunchTemplateId": "lt-xxxxx",
    "Version": "$Latest"
  },
  "Overrides": [
    {"InstanceType": "m5.large", "WeightedCapacity": 1},
    {"InstanceType": "m5.xlarge", "WeightedCapacity": 2},
    {"InstanceType": "m5a.large", "WeightedCapacity": 1},
    {"InstanceType": "m5a.xlarge", "WeightedCapacity": 2}
  ]
}

Phase 3: Architecture Optimization

Graviton (ARM) Migration

Workload x86 Instance Graviton Instance Savings Performance
Web/API t3.medium t4g.medium 20% Equal/better
Java apps m5.large m6g.large 20% Equal (JDK 11+)
Node.js/Python m5.large m6g.large 20% Better
Databases r5.large r6g.large 20% Better
CI/CD c5.large c6g.large 20% Better
Memory-heavy r5.xlarge r6g.xlarge 20% Better

Migration checklist:

  • [ ] Application compiles/runs on ARM64
  • [ ] Dependencies available for ARM64
  • [ ] Container images multi-arch (manifest lists)
  • [ ] Test in staging with full load
  • [ ] Monitor for 1 week before cutover

Instance Family Selection

Use Case Family Why
General purpose m5/m6g Balanced CPU/RAM
Compute heavy c5/c6g High CPU, less RAM
Memory heavy r5/r6g High RAM/CPU ratio
Storage heavy i3/i4g Local NVMe
GPU/ML g5/p4 GPU acceleration
Burstable t3/t4g Low baseline, burst credits
Cost optimized t3a/t4g AMD/ARM, 10% cheaper

Right Family = Bigger Savings Than Right Size

# Example: Java app with 2GB heap, 4GB container
# WRONG: c5.large (2 vCPU, 4GB RAM) - CPU starved
# WRONG: r5.large (2 vCPU, 16GB RAM) - RAM wasted
# RIGHT: m5.large (2 vCPU, 8GB RAM) - Balanced
# BETTER: m6g.large (2 vCPU, 8GB RAM) - 20% cheaper

Phase 4: Configuration Optimization

EBS Optimization

# Check current volumes
aws ec2 describe-volumes \
  --filters Name=status,Values=in-use \
  --query 'Volumes[*].[VolumeId,VolumeType,Size,State,Attachments[0].InstanceId]' \
  --output table

# gp3 vs gp2 pricing (us-east-1, 100GB)
# gp2: $0.10/GB/month = $10/month (includes 3000 IOPS baseline)
# gp3: $0.08/GB/month = $8/month + $0.005/provisioned IOPS over 3000
# For 3000 IOPS: gp3 = $8/month (20% cheaper)
# For 10000 IOPS: gp3 = $8 + $35 = $43 vs gp2 would need 1000GB = $100

# Convert gp2 to gp3 (no downtime)
aws ec2 modify-volume \
  --volume-id vol-xxxxx \
  --volume-type gp3 \
  --iops 3000 \
  --throughput 125

EBS Lifecycle

# Find unattached volumes (waste)
aws ec2 describe-volumes \
  --filters Name=status,Values=available \
  --query 'Volumes[*].[VolumeId,Size,VolumeType,CreateTime]' \
  --output table

# Find snapshots older than 90 days
aws ec2 describe-snapshots \
  --owner-ids self \
  --query "Snapshots[?StartTime<='$(date -d '90 days ago' --iso-8601)'].[SnapshotId,VolumeSize,StartTime,Description]" \
  --output table

# Delete old snapshots (automate with DLM)
aws dlm create-lifecycle-policy \
  --description "Daily snapshots, retain 30 days" \
  --state ENABLED \
  --execution-role-arn arn:aws:iam::account:role/AWSDataLifecycleManagerDefaultRole \
  --policy-details '{
    "ResourceTypes": ["VOLUME"],
    "TargetTags": [{"Key": "Backup", "Value": "true"}],
    "Schedules": [{
      "Name": "Daily",
      "CopyTags": true,
      "CreateRule": {"Interval": 24, "IntervalUnit": "HOURS", "Times": ["03:00"]},
      "RetainRule": {"Count": 30}
    }]
  }'

Network Costs

# Data transfer costs (us-east-1)
# Within AZ: Free
# Cross-AZ: $0.01/GB
# Cross-region: $0.02/GB
# To internet: $0.09/GB (first 10TB)

# Optimization:
# 1. Keep communicating services in same AZ
# 2. Use VPC endpoints for S3/DynamoDB (free)
# 3. CloudFront for internet egress ($0.085/GB)
# 4. Enable ENA Express for 25Gbps within AZ

# VPC Endpoint for S3 (free, saves NAT Gateway costs)
aws ec2 create-vpc-endpoint \
  --vpc-id vpc-xxxxx \
  --service-name com.amazonaws.us-east-1.s3 \
  --vpc-endpoint-type Gateway \
  --route-table-ids rtb-xxxxx

Idle Resource Detection

# Find instances with <5% CPU for 7 days
aws cloudwatch get-metric-statistics \
  --namespace AWS/EC2 \
  --metric-name CPUUtilization \
  --dimensions Name=InstanceId,Value=i-xxxxx \
  --start-time $(date -d '7 days ago' --iso-8601) \
  --end-time $(date --iso-8601) \
  --period 86400 \
  --statistics Average

# Automated with Trusted Advisor or Compute Optimizer
aws compute-optimizer get-ec2-instance-recommendations \
  --account-ids $(aws sts get-caller-identity --query Account --output text)

Automation: Complete Cost Optimization Pipeline

# .github/workflows/cost-optimization.yml
name: EC2 Cost Optimization
on:
  schedule:
    - cron: '0 6 * * 1'  # Weekly Monday 6AM
  workflow_dispatch:

jobs:
  analyze:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Configure AWS
        uses: aws-actions/configure-aws-credentials@v4
        with:
          aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
          aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
          aws-region: us-east-1

      - name: Run right-sizing analysis
        run: |
          python scripts/rightsize.py > recommendations.json

      - name: Run Compute Optimizer
        run: |
          aws compute-optimizer get-ec2-instance-recommendations \
            --output json > compute_optimizer.json

      - name: Check Savings Plans utilization
        run: |
          aws savingsplans describe-savings-plans \
            --state active \
            --output json > savings_plans.json

      - name: Check RI utilization
        run: |
          aws ce get-reservation-utilization \
            --time-period Start=$(date -d '30 days ago' +%F),End=$(date +%F) \
            --output json > ri_utilization.json

      - name: Generate report
        run: |
          python scripts/generate_cost_report.py \
            --rightsize recommendations.json \
            --optimizer compute_optimizer.json \
            --savings savings_plans.json \
            --ri ri_utilization.json \
            --output cost_report.html

      - name: Send to Slack
        uses: slackapi/[email protected]
        with:
          channel-id: ${{ secrets.SLACK_COST_CHANNEL }}
          payload: |
            {
              "text": "Weekly EC2 Cost Optimization Report",
              "blocks": [
                {"type": "section", "text": {"type": "mrkdwn", "text": "*Weekly EC2 Cost Report*\nPotential savings: ${{ env.POTENTIAL_SAVINGS }}/month"}},
                {"type": "actions", "elements": [{"type": "button", "text": {"type": "plain_text", "text": "View Report"}, "url": "${{ env.REPORT_URL }}", "action_id": "view_report"}]}
              ]
            }
        env:
          SLACK_BOT_TOKEN: ${{ secrets.SLACK_BOT_TOKEN }}

Monitoring Dashboard (CloudWatch)

{
  "widgets": [
    {
      "type": "metric",
      "properties": {
        "metrics": [
          ["AWS/EC2", "CPUUtilization", "AutoScalingGroupName", "prod-asg"],
          [".", "NetworkIn", ".", "."],
          [".", "NetworkOut", ".", "."]
        ],
        "period": 300,
        "stat": "Average",
        "region": "us-east-1",
        "title": "Production ASG Utilization"
      }
    },
    {
      "type": "metric",
      "properties": {
        "metrics": [
          ["AWS/Billing", "EstimatedCharges", "Currency", "USD", "ServiceName", "AmazonEC2"]
        ],
        "period": 86400,
        "stat": "Maximum",
        "region": "us-east-1",
        "title": "EC2 Monthly Spend"
      }
    },
    {
      "type": "metric",
      "properties": {
        "metrics": [
          ["AWS/SavingsPlans", "SavingsPlanUtilization", "SavingsPlanArn", "arn:aws:savingsplans:..."]
        ],
        "period": 86400,
        "stat": "Average",
        "region": "us-east-1",
        "title": "Savings Plan Utilization"
      }
    }
  ]
}

Quick Reference: Monthly Checklist

  • [ ] Run Compute Optimizer recommendations
  • [ ] Check Savings Plan utilization > 90%
  • [ ] Check RI utilization > 90%
  • [ ] Identify instances < 10% CPU for 14 days
  • [ ] Convert gp2 → gp3 volumes
  • [ ] Delete unattached EBS volumes
  • [ ] Delete snapshots > 90 days (unless compliance)
  • [ ] Review Spot interruption frequency
  • [ ] Verify VPC endpoints for S3/DynamoDB
  • [ ] Check cross-AZ data transfer costs
  • [ ] Review Graviton migration candidates
  • [ ] Update capacity reservations if needed

Savings Summary

Optimization Typical Savings Effort Risk
Right-sizing 20-40% Low Low
Savings Plans (1yr) 30-40% Low Low
Savings Plans (3yr) 50-66% Low Medium
Spot Instances 60-70% Medium Medium
Graviton Migration 20% Medium Low
gp2 → gp3 20% on storage Low None
Delete idle resources 5-15% Low None
VPC Endpoints $0.01/GB cross-AZ Low None

Start with right-sizing + Savings Plans. Those two alone typically save 40-50% with minimal risk and effort. Everything else is incremental.

Leave a Reply

Your email address will not be published. Required fields are marked *