OnCallReadyStart learning

AWS Lesson 39.31 · AWS VI: Architecting on AWS & the exams · 15 min read

Cost-optimized design: purchase options, right-sizing and the shape of the bill

In plain words

Paying for cloud capacity is like paying for transport. A taxi when you need it is On-Demand: flexible and expensive. A yearly travel pass is a Savings Plan: cheaper if you really travel every day. Standby airline seats are Spot: very cheap, but you can be bumped. And before buying any pass, check that you are not taking a bus for one passenger every day - that is right-sizing.

Cost-optimized design: purchase options, right-sizing and the shape of the bill

AWS III read the bill (Cost Explorer, tags, budgets, the NAT gateway surprise). This lesson is the architect's side: designing so the bill is small by construction - paying less per hour for the capacity you always need, not paying for capacity you do not use, putting data in the right storage class, keeping bytes off the expensive paths, and picking compute whose cost shape matches the traffic. Cost optimization is a Well-Architected pillar and 20% of the SAA-C03 exam.

Need to know: EC2 (and Fargate, and Lambda) capacity can be bought five ways. On-Demand: per second, no commitment, the most expensive. Savings Plans: a commitment of $ per hour for 1 or 3 years for a discount - Compute Savings Plans apply to any EC2 family, Region, OS, Fargate and Lambda (up to 66% off); EC2 Instance Savings Plans to one family in one Region (up to 72%). Reserved Instances: the older commitment to an instance type (Standard, or Convertible to change it), Regional or zonal (a zonal RI also reserves capacity). Spot: spare capacity at up to 90% off that AWS takes back with a two-minute warning. Dedicated Hosts: a physical server for per-socket / per-core licences (BYOL) and compliance; On-Demand Capacity Reservations guarantee capacity in an AZ without a discount.

Where the money goes

Start every cost review with the bill grouped by service, this month so far:

$ aws ce get-cost-and-usage --time-period Start=$(date -u +%Y-%m-01),End=$(date -u +%F) --granularity MONTHLY --metrics UnblendedCost --group-by Type=DIMENSION,Key=SERVICE --query 'ResultsByTime[0].Groups[].[Keys[0],Metrics.UnblendedCost.Amount]' --output text | sort -t$'\t' -k2 -rn | head -6
Amazon Elastic Compute Cloud - Compute	96.4656
AWS Lambda	90.6778483117
Amazon Elastic Container Service	57.23424
$ aws ce get-cost-and-usage --time-period Start=$(date -u -d '-7 days' +%F),End=$(date -u +%F) --granularity DAILY --metrics UsageQuantity --filter '{"Dimensions":{"Key":"USAGE_TYPE","Values":["EUC1-Fargate-vCPU-Hours:perCPU"]}}' --query 'ResultsByTime[].[TimePeriod.Start,Total.UsageQuantity.Amount]' --output text
2026-09-15	48
2026-09-16	48
2026-09-17	48
2026-09-18	48
2026-09-19	48
2026-09-20	48
2026-09-21	48

The Fargate service runs 48 vCPU-hours every day: 2 vCPU around the clock. That steady baseline is exactly what a Savings Plan is for: commit to it, and pay On-Demand only for what goes above. A commitment is in dollars per hour at the Savings Plan rate, so size it from the On-Demand spend of the baseline, and commit to the floor, not the average - an unused commitment is lost money.

Right-sizing first

A discount on a server that is four times too big is still waste. Compute Optimizer reads 14 days of CloudWatch metrics and recommends instance types (also for ASGs, EBS volumes, Lambda memory and ECS services on Fargate):

$ aws compute-optimizer get-enrollment-status --query status --output text
Active
$ aws compute-optimizer get-ec2-instance-recommendations --query 'instanceRecommendations[].[instanceName,currentInstanceType,finding,recommendationOptions[0].instanceType]' --output text
try-batch-1	m7g.xlarge	Overprovisioned	m7g.large
$ aws cloudwatch get-metric-statistics --namespace AWS/EC2 --metric-name CPUUtilization --dimensions Name=InstanceId,Value=$(aws ec2 describe-instances --filters Name=tag:Name,Values=try-batch-1 --query 'Reservations[0].Instances[0].InstanceId' --output text) --start-time $(date -u -d '-14 days' +%FT%TZ) --end-time $(date -u +%FT%TZ) --period 1209600 --statistics Average Maximum --query 'Datapoints[0].[Average,Maximum]' --output text
6.08217	6.08217

The order that works: turn off what nobody uses (dev at night - Instance Scheduler or an EventBridge Scheduler schedule), right-size what is left, then commit (Savings Plans) to the new baseline, and run interruptible work on Spot. Graviton (arm64) types are typically cheaper for the same work - the g in m7g.

Spot for interruptible work

Batch jobs, CI runners, rendering, queue workers whose messages come back if the worker dies: Spot. Design for the two-minute notice - checkpoint work, keep tasks short, let the queue redeliver

  • and diversify (several instance types and AZs, the capacity-optimized allocation strategy in

an Auto Scaling group with a mixed instances policy) so one pool running dry does not stop you. On ECS the same lever is Fargate Spot, a capacity provider:

$ aws ecs create-cluster --cluster-name try-batch --capacity-providers FARGATE FARGATE_SPOT --default-capacity-provider-strategy capacityProvider=FARGATE,base=1,weight=1 capacityProvider=FARGATE_SPOT,weight=3 --query 'cluster.[capacityProviders,defaultCapacityProviderStrategy]' --output json
[
    [
        "FARGATE",
        "FARGATE_SPOT"
    ],
    [
        {
            "capacityProvider": "FARGATE",
            "weight": 1,
            "base": 1
        },
        {
            "capacityProvider": "FARGATE_SPOT",
            "weight": 3,
            "base": 0
        }
    ]
]

base=1 keeps one task on regular Fargate; of every four tasks beyond it, three run on Spot. An interrupted Fargate Spot task gets SIGTERM with two minutes to stop (stopCode SpotInterruption) and the service starts a replacement.

The shape of the bill: Lambda vs containers

Lambda bills per request and per GB-second - zero at zero traffic, linear with traffic. A container bills per hour it runs - a floor, flat until it must scale. The crossover depends on traffic:

$ cd ~/oncall-lab/labs/aws/try6
$ cat cost.awk
# monthly cost in USD (eu-central-1 list prices, rounded; simulator lab numbers):
# a 512 MB function taking 120 ms per request, vs Fargate tasks of 0.5 vCPU + 1 GB running all month
BEGIN {
  gbs = req * 0.120 * 0.5
  lambda = gbs * 0.0000166667 + req / 1000000 * 0.20
  tasks = 2; if (req > 100000000) tasks = int(req / 50000000) + 1
  fargate = tasks * 730 * (0.5 * 0.04656 + 1 * 0.00511)
  printf "%4d M requests/month: Lambda $%8.2f   Fargate (%d tasks) $%7.2f\n", req / 1000000, lambda, tasks, fargate
}
$ for m in 1 10 100 300; do awk -v req=${m}000000 -f cost.awk; done
   1 M requests/month: Lambda $    1.20   Fargate (2 tasks) $  41.45
  10 M requests/month: Lambda $   12.00   Fargate (2 tasks) $  41.45
 100 M requests/month: Lambda $  120.00   Fargate (2 tasks) $  41.45
 300 M requests/month: Lambda $  360.00   Fargate (7 tasks) $ 145.07

Low or spiky traffic: Lambda wins (and scales to zero). High, steady traffic: containers win, and a Savings Plan on them widens the gap. Then add what the arithmetic leaves out - the ALB in front of the containers, the NAT gateway they pull through, and the engineering time of running either.

Storage and data transfer

  • Storage classes (AWS V): S3 Standard for hot data, Intelligent-Tiering when access is unknown, Standard-IA / One Zone-IA for infrequent access (retrieval fees, 30-day minimum), Glacier Instant / Flexible / Deep Archive for archives (minutes to hours to restore, 90 / 180-day minimums) - moved by lifecycle rules, which also expire old versions and incomplete multipart uploads. Requester Pays buckets bill the downloader. EBS: gp3 over gp2 (cheaper, IOPS independent of size), delete unattached volumes and old snapshots.
  • Data transfer: in is free, out to the internet costs (CloudFront is cheaper per GB and caches), between AZs costs both ways, NAT gateways charge per GB processed - S3 and DynamoDB gateway endpoints are free and take that traffic off the NAT (AWS II-III).
  • Databases (AWS V): Aurora Serverless v2 or DynamoDB on-demand for spiky load, provisioned capacity with auto scaling and reserved capacity for steady load, read replicas instead of a bigger primary.

Guard rails

Budgets with alerts (AWS III), Cost Anomaly Detection, cost allocation tags per team and environment, the AWS Pricing Calculator before you build, Trusted Advisor and Compute Optimizer checks after, and Savings Plans / RI utilization and coverage reports so a commitment does not quietly go unused. With Organizations, consolidated billing pools usage across accounts, so volume tiers and Savings Plans benefit all of them.

On the exam (SAA-C03 4.1-4.4; SOA-C03 1.3; CLF-C02 4.1): Spot for fault-tolerant / interruptible work, Savings Plans or RIs for steady 1-3 year usage (Compute SP = most flexible), On-Demand for short, unpredictable work, Dedicated Hosts for per-socket licences, Capacity Reservations for a guaranteed launch; right-size with Compute Optimizer; S3 class by access pattern + lifecycle; gateway endpoints and CloudFront to cut transfer costs; Lambda vs Fargate vs EC2 by traffic shape.

In an interview: "Our AWS bill doubled. Where do you start?" - "Cost Explorer grouped by service, then by usage type and tag, day by day, to find when and what - a NAT gateway's bytes, inter-AZ traffic, a forgotten cluster. Fix waste first: turn off idle things, right-size with Compute Optimizer, lifecycle old data, move S3 traffic to a gateway endpoint. Then commit with a Savings Plan to the new baseline, move interruptible work to Spot, and add budgets and anomaly detection so we hear about it next time before the invoice."

You can now: choose between On-Demand, Savings Plans (Compute vs EC2 Instance), Reserved Instances, Spot, Dedicated Hosts and Capacity Reservations, size a commitment from the baseline, right-size with Compute Optimizer before committing, run interruptible work on Spot and Fargate Spot, compare the cost shape of Lambda and containers, pick storage classes and lifecycle rules, cut data transfer and NAT costs, and set the guard rails.

Why it helps

Cost optimization is a fifth of the Solutions Architect exam and a constant pressure in real teams. The order matters: remove waste, right-size, then commit to the steady baseline and move interruptible work to Spot. Understanding how Lambda and containers bill, which storage class fits an access pattern, and where data transfer and NAT gateways hide costs turns a bill from a surprise into a design property.

Commands in this lesson

aws cd cat

FAQ

Compute Savings Plan or EC2 Instance Savings Plan?

A Compute Savings Plan applies to any instance family, size, Region and operating system, and to Fargate and Lambda, with discounts up to about 66%. An EC2 Instance Savings Plan is tied to one instance family in one Region and gives deeper discounts, up to about 72%. Choose the flexible one when your platform may change.

How should a Savings Plan be sized?

To the steady floor of usage that runs all the time, after waste has been removed and instances right-sized, expressed in dollars per hour at the Savings Plan rate. Committing to the average or the peak leaves part of the commitment unused in quiet hours, and unused commitment is money spent for nothing.

What happens when a Spot Instance is interrupted?

AWS gives a two-minute warning and then stops or terminates the instance when it needs the capacity back. Workloads should checkpoint, keep tasks short and let queues redeliver unfinished work. Diversifying across instance types and Availability Zones reduces how often all capacity disappears at once.

When is Lambda cheaper than containers?

At low or spiky traffic: Lambda bills per request and per GB-second and costs nothing when idle, while containers bill per hour they run. At high, steady traffic, containers - especially with a Savings Plan - usually win. The crossover depends on request volume, duration and memory, so calculate it for your workload.

Where do hidden network costs come from?

NAT gateways charge per gigabyte processed, traffic between Availability Zones is billed in both directions, and internet egress is charged per gigabyte. Gateway endpoints for S3 and DynamoDB are free and take that traffic off the NAT gateway, and CloudFront reduces egress cost for content served to users.

In an interview Mid

Our AWS bill doubled last month. Where do you start?

Cost Explorer grouped by service, then usage type, tag and day, to find when and what changed - often NAT gateway bytes, inter-AZ traffic or a forgotten cluster. Then remove waste: turn off idle resources, right-size with Compute Optimizer, add lifecycle rules for old data, move S3 traffic to a gateway endpoint. After that, commit to the new baseline with a Savings Plan, move interruptible work to Spot, and add budgets and anomaly detection so the next jump is caught early.

Also asked: When would you use Spot Instances? · How do Reserved Instances differ from Savings Plans? · How would you choose an S3 storage class?

Practise this lesson in the terminal Free, in your browser - a real Ubuntu terminal to try it in, with missions that check your work.