AWS Builder Center

AWS: Zero to Hero — Week 14: Cost Optimization and the Well-Architected Framework

Week 14 of learning AWS from zero, with Claude as my research partner. The six Well-Architected pillars mapped to the whole series, how to spend deliberately instead of minimally, and a table of every cost trap from weeks 4 to 13. Hands-on: a read-only script that sweeps every region for zombie resources, Cost Explorer from the CLI, Cost Anomaly Detection, and a Well-Architected review.

Series: AWS: Zero to Hero (14 articles)

  1. …
  2. 14
    AWS: Zero to Hero — Week 14: Cost Optimization and the Well-Architected Framework This article

AWS: Zero to Hero — Week 14: Cost Optimization and the Well-Architected Framework

Every lab in this series ended with a cleanup section, and most of those sections started with a warning. That wasn't an accident. Looking back over the last thirteen weeks, almost every serious cost trap I ran into was the same shape: something that bills by the hour, left running, doing nothing. This week I wanted to step back, put those traps in one place, and learn the framework AWS itself uses to judge whether a system is built well, of which cost is only one part.



The Deep Dive

The Well-Architected Framework

The AWS Well-Architected Framework is AWS's collected set of best practices for building systems on its platform, organized as a set of questions you ask about a workload. It's not a certification and it isn't pass/fail; it's closer to a structured conversation that surfaces risks you haven't thought about. AWS offers a free Well-Architected Tool in the console for running those reviews, and lenses that extend the framework for particular kinds of workloads (serverless, machine learning, generative AI, and others).
It's organized into six pillars, and I was pleased to realize that each one maps onto something we've already covered:
  • Operational Excellence — running and monitoring systems well, and improving them continuously. This is Week 9 (infrastructure as code, small automated deployments) and Week 10 (observability).
  • Security — protecting data and systems. Week 3's identity and shared responsibility, Week 6's network layers, and Week 10's CloudTrail audit trail.
  • Reliability — recovering from failure and meeting demand. Week 2's Availability Zones and Week 4's Auto Scaling and load balancing.
  • Performance Efficiency — using the right resources and adapting as needs change. Week 4's instance families and Graviton, Week 5's storage classes, Week 7's serverless.
  • Cost Optimization — delivering value at the lowest price point you can. This week.
  • Sustainability — minimizing the environmental impact of your workloads, largely by using fewer resources more efficiently. It overlaps heavily with cost: idle capacity wastes both money and energy.
One thing worth understanding early is that the pillars pull against each other. Spreading across multiple AZs improves reliability and raises cost. A bigger instance can improve performance and hurt cost. The framework doesn't tell you which to favor; it makes the trade-off visible so you choose on purpose.

Cost optimization: spend deliberately, not minimally

"Cost optimization" is easy to misread as "spend as little as possible." That's not the goal. The goal is to spend deliberately: every dollar should be buying something you chose to buy. A few principles do most of the work:
  • Measure and attribute. You can't manage what you can't see. That means knowing which service and which project is generating cost, which depends on tagging resources consistently, plus Cost Explorer to analyze spend, Budgets to alert you (Week 11), and Cost Anomaly Detection to flag unusual jumps automatically.
  • Eliminate waste. The cheapest resource is the one you delete. Idle and orphaned resources are the single biggest source of avoidable cost for most beginners, and the lab below is built around finding them.
  • Right-size. Match instance sizes and storage to actual usage. A resource that's twice as big as it needs to be costs twice as much for no benefit. AWS Compute Optimizer analyzes usage and suggests better sizes.
  • Use the advisors. AWS Trusted Advisor checks your account against best-practice rules across cost optimization, security, fault tolerance, performance, and service limits, and flags things like idle or underused resources. One caveat to check before you rely on it: which checks you get can depend on your account type and AWS Support plan, and AWS changes those entitlements over time, so read the current Trusted Advisor documentation in the AWS Support User Guide instead of assuming.
  • Choose the right pricing model. Week 4's three options (On-Demand, Savings Plans, Spot) exist for a reason. A commitment discount only makes sense for a steady baseline, and Spot only for work that can be interrupted.
  • Pick architectures that cost nothing when idle. Serverless services that scale to zero (Week 7) and per-token APIs (Week 11) have no idle cost. Always-on infrastructure does.
  • Mind data transfer. Moving data between AZs, between regions, and out to the internet is billed, while moving data in is generally free. Architecture choices that chatter across boundaries quietly cost money.
  • Use lifecycle rules. Storage that nobody reads should move to cheaper tiers or expire (Week 5's S3 storage classes), and logs should have retention periods (Week 10).
The discipline that ties this together has a name, FinOps, and a simple rhythm: inform (make costs visible and attributable), optimize (act on what you see), and operate (make it continuous instead of a one-time cleanup).

The cost traps of this series, in one place

Here's the summary I wish I'd had at the start. Every item below is something we've already met, with the guardrail that prevents it. Prices are approximate, change over time, and vary by region, so check the current pricing pages:
Week
The trap
What it costs, roughly
The guardrail
4
Instances and load balancers left running
Hourly, per resource
Run cleanup in the same sitting
5
Orphaned EBS volumes and snapshots; idle RDS instances
Per GB-month; per hour
Delete volumes and snapshots separately from instances
6
NAT Gateway
~$0.045/hr plus per-GB, plus its IP (varies by region)
Delete it first, release its Elastic IP, and check no route still points at it; use VPC endpoints
6
Public IPv4 addresses, even idle
~$0.005/hr each
Release unused; prefer private subnets
8
EKS cluster, and its extended-support jump
~$0.10/hr, then ~$0.60/hr
Prefer ECS on Fargate; keep versions current
10
Log groups that never expire
Grows forever
Set a retention period at creation
11
SageMaker real-time endpoints
Per instance-hour, always
Delete endpoints when done
12
OpenSearch Serverless behind a Knowledge Base
~$350/month, idle
Evaluate S3 Vectors where it meets your needs; verify nothing is left
13
GPU instances
~$55/hr for a P5
Don't launch; check quotas and use Capacity Blocks deliberately
Nearly every row is the same story, which is the point: cost surprises on AWS are mostly resources that are quietly on. The habit that beats them isn't cleverness, it's a regular, boring sweep. That's the first lab.



Cost Reality Check for This Week

This is the cheapest week of the series. The resource-finding script only makes read-only  describe  and  list  calls, which are free, and it deletes nothing. The Well-Architected Tool and Cost Anomaly Detection are free. The one thing that can cost something is Cost Explorer: its console is free, but API requests made through the CLI are chargeable (historically around a cent per request, so check the current pricing), so Part 2 is a handful of calls costing a few cents at most.
One setup note: Cost Explorer has to be enabled before it returns data, which you do once in the Billing console, and it can take up to a day to populate on a new account. If Part 2 returns an error about data not being available, that's why. Its data also lags real usage by up to a day or so, so it won't line up exactly with your invoice.

Hands-On

Part 1 — Hunt for zombie resources

This script walks every region in your account and reports resources that commonly bill while doing nothing. It's read-only. Save it and run it:
cat > zombie_hunt.sh <<'SH'
#!/usr/bin/env bash
# Read-only sweep for resources that commonly bill while idle.
# Usage: ./zombie_hunt.sh (all enabled regions)
# REGIONS="ap-south-1" ./zombie_hunt.sh (just one)
# VERBOSE=1 ./zombie_hunt.sh (also print every check that failed)

# Refuse to run on bad credentials: otherwise every check would fail and look like "nothing found".
if ! aws sts get-caller-identity >/dev/null 2>&1; then
echo "Could not authenticate with AWS. Fix your credentials first; a sweep without them proves nothing." >&2
exit 1
fi

if [[ -z "$REGIONS" ]]; then
REGIONS=$(aws ec2 describe-regions --query 'Regions[].RegionName' --output text) || {
echo "Could not list regions." >&2
exit 1
}
fi

PERM_FAILS=()
OTHER_FAILS=0
FINDINGS=0

check () { # check <label> <aws command...>
local label="$1"; shift
local errfile out msg
errfile=$(mktemp) || { echo "Could not create a temporary file; aborting." >&2; exit 1; }
if out=$("$@" 2>"$errfile"); then
if [[ -n "$out" && "$out" != "None" ]]; then
echo "[$REGION] $label: $out"
FINDINGS=$((FINDINGS + 1))
fi
else
msg=$(head -c 200 "$errfile" | tr '\n' ' ')
if echo "$msg" | grep -qiE 'AccessDenied|UnauthorizedOperation|UnauthorizedAccess|not authorized to perform|ExpiredToken|AuthFailure|InvalidClientTokenId|UnrecognizedClientException|InvalidSignatureException'; then
PERM_FAILS+=("[$REGION] $label")
else
OTHER_FAILS=$((OTHER_FAILS + 1))
fi
if [[ -n "$VERBOSE" ]]; then
echo "[$REGION] could not check $label: $msg" >&2
fi
fi
rm -f "$errfile"
}

for REGION in $REGIONS; do
check "unattached EBS volumes (id, GiB)" \
aws ec2 describe-volumes --region "$REGION" --filters Name=status,Values=available \
--query 'Volumes[].[VolumeId,Size]' --output text
check "EBS snapshots you own (id, GiB, created)" \
aws ec2 describe-snapshots --region "$REGION" --owner-ids self \
--query 'Snapshots[].[SnapshotId,VolumeSize,StartTime]' --output text
check "AMIs you own (id, name)" \
aws ec2 describe-images --region "$REGION" --owners self \
--query 'Images[].[ImageId,Name]' --output text
check "Elastic IPs not in use" \
aws ec2 describe-addresses --region "$REGION" \
--query 'Addresses[?AssociationId==null].PublicIp' --output text
check "NAT gateways" \
aws ec2 describe-nat-gateways --region "$REGION" --filter Name=state,Values=available \
--query 'NatGateways[].NatGatewayId' --output text
check "interface VPC endpoints" \
aws ec2 describe-vpc-endpoints --region "$REGION" --filters Name=vpc-endpoint-type,Values=Interface \
--query 'VpcEndpoints[].VpcEndpointId' --output text
check "EC2 instances running or stopped" \
aws ec2 describe-instances --region "$REGION" --filters Name=instance-state-name,Values=running,stopped \
--query 'Reservations[].Instances[].[InstanceId,InstanceType,State.Name]' --output text
check "load balancers" \
aws elbv2 describe-load-balancers --region "$REGION" \
--query 'LoadBalancers[].LoadBalancerName' --output text
check "RDS instances" \
aws rds describe-db-instances --region "$REGION" \
--query 'DBInstances[].[DBInstanceIdentifier,DBInstanceClass]' --output text
check "EKS clusters" \
aws eks list-clusters --region "$REGION" --query 'clusters' --output text
check "ECS clusters" \
aws ecs list-clusters --region "$REGION" --query 'clusterArns' --output text
check "SageMaker endpoints" \
aws sagemaker list-endpoints --region "$REGION" --query 'Endpoints[].EndpointName' --output text
check "SageMaker notebook instances in service" \
aws sagemaker list-notebook-instances --region "$REGION" \
--query 'NotebookInstances[?NotebookInstanceStatus==`InService`].NotebookInstanceName' --output text
check "OpenSearch Serverless collections" \
aws opensearchserverless list-collections --region "$REGION" \
--query 'collectionSummaries[].name' --output text
check "CloudFormation stacks not deleted (name, status)" \
aws cloudformation describe-stacks --region "$REGION" \
--query 'Stacks[].[StackName,StackStatus]' --output text
check "log groups with no retention set" \
aws logs describe-log-groups --region "$REGION" \
--query 'logGroups[?retentionInDays==null].logGroupName' --output text
done

REGION=global
check "S3 buckets" aws s3api list-buckets --query 'Buckets[].Name' --output text
check "Route 53 hosted zones" aws route53 list-hosted-zones --query 'HostedZones[].Name' --output text
check "CloudFront distributions" \
aws cloudfront list-distributions --query 'DistributionList.Items[].DomainName' --output text

echo
echo "Sweep complete: $FINDINGS item(s) found."
if [[ $FINDINGS -eq 0 && ${#PERM_FAILS[@]} -eq 0 && $OTHER_FAILS -eq 0 ]]; then
echo "Nothing found in the services this script checks. That is not the same as an empty bill."
fi
if [[ ${#PERM_FAILS[@]} -gt 0 ]]; then
echo "WARNING: ${#PERM_FAILS[@]} check(s) were blocked by permissions. Their silence means NOTHING:"
printf ' %s\n' "${PERM_FAILS[@]}"
fi
if [[ $OTHER_FAILS -gt 0 ]]; then
echo "$OTHER_FAILS check(s) could not run, usually because a service isn't offered in that region."
echo "Re-run with VERBOSE=1 to see each one."
fi
SH

chmod +x zombie_hunt.sh
./zombie_hunt.sh
Read the results the way you'd read a receipt. Anything on the list should be something you can explain. The usual suspects, and what each one really costs:
  • A stopped EC2 instance. Stopping ends the instance-hour charges, which is why people assume a stopped instance is free. But its EBS volumes keep billing. An Elastic IP associated with it keeps billing too (since February 2024 every public IPv4 address is charged, in use or not), whereas an ordinary auto-assigned public address is released when you stop the instance. The disk is the part that surprises people.
  • EBS snapshots and AMIs. Deleting an instance or a volume doesn't delete the snapshots made from it, and an AMI keeps its snapshots alive. They bill by the GB-month, quietly, until someone removes them. The sweep lists the ones you own. Review their age and whether anything still depends on them before deleting, and consider Amazon Data Lifecycle Manager to expire old ones automatically.
  • An Elastic IP or public IPv4 address left behind by a deleted instance (Week 6's hourly charge).
  • An old CloudFormation stack. The sweep lists every stack that hasn't been deleted, along with its status. Pay particular attention to  DELETE_FAILED  (some resources are still there and still billing),  ROLLBACK_COMPLETE  (a failed create that was rolled back; normally only the stack itself is left to delete, though resources marked to be retained can survive), and  ROLLBACK_FAILED  (the rollback itself failed, so resources may be left behind).
  • A log group with no retention set (Week 10).
  • An S3 bucket. An empty bucket costs nothing, so buckets look harmless, but storage accumulates, especially with versioning (every old version is kept and billed), incomplete multipart uploads (invisible partial files), replication, and large datasets nobody revisited. Treat a bucket you can't explain as worth a look, not as free.
Two honest notes about this script. First, it's built not to fool you. It refuses to run at all if your credentials don't work, it counts every check that failed, and it lists any check blocked by permissions as a warning, because for those checks silence means nothing. Checks that fail for ordinary reasons, usually a service that isn't offered in a region, are counted and summarized, and  VERBOSE=1  shows each one. Even so, an all-clear means only "nothing found in the services this script checks." Think of it as an inventory tool, not a billing auditor: it tells you what exists, and Part 2's Cost Explorer tells you what is actually costing money. Second, it covers only the services this series used. A real account has many more, which is where the Billing console's per-service view in Part 2 picks up the slack.
If it finds leftovers from earlier weeks, delete them using the cleanup steps from those weeks, and then re-run the script until it's quiet. That loop (sweep, delete, re-sweep) is the habit worth keeping.

Part 2 — Where did the money actually go?

Ask Cost Explorer for spend across the last 30 days, grouped by service and aggregated across calendar months, and rank it:
START=$(python3 -c "from datetime import date,timedelta;print((date.today()-timedelta(days=30)).isoformat())")
END=$(python3 -c "from datetime import date;print(date.today().isoformat())")

aws ce get-cost-and-usage \
--time-period Start=$START,End=$END \
--granularity MONTHLY \
--metrics UnblendedCost \
--group-by Type=DIMENSION,Key=SERVICE \
--query 'ResultsByTime[].Groups[].[Keys[0],Metrics.UnblendedCost.Amount]' \
--output text \
| awk -F'\t' '{a[$1]+=$2} END{for(k in a) printf "%.4f\t%s\n", a[k], k}' \
| sort -rn | head -10
Because the query uses monthly granularity, Cost Explorer returns one row per service per calendar month, so a 30-day window usually comes back as two partial months. The awk step adds them together, and the sort ranks the biggest first. Two cautions on reading the numbers: Cost Explorer's data lags real usage by up to a day or so, and it won't match your invoice exactly. And if you're on promotional credits, how they're counted depends on how the query is filtered (Cost Explorer can group or filter by record type, such as credits), so check that before concluding anything from a total that looks too high or too low. Get in the habit of reading this list top to bottom: it's the fastest way to learn that something unexpected is spending money.

Part 3 — Get warned automatically with Cost Anomaly Detection

Budgets (Week 11) alert you when you cross a threshold you chose. Cost Anomaly Detection watches for spending that's unusual for you, even when it's under any threshold, and it's free. Set up a monitor on all services and a daily email:
MONITOR_ARN=$(aws ce create-anomaly-monitor \
--anomaly-monitor '{"MonitorName":"zth-services","MonitorType":"DIMENSIONAL","MonitorDimension":"SERVICE"}' \
--query MonitorArn --output text)

aws ce create-anomaly-subscription --anomaly-subscription "{
\"SubscriptionName\": \"zth-daily\",
\"MonitorArnList\": [\"$MONITOR_ARN\"],
\"Subscribers\": [{\"Address\": \"<your-email-address>\", \"Type\": \"EMAIL\"}],
\"Frequency\": \"DAILY\",
\"ThresholdExpression\": {\"Dimensions\": {\"Key\": \"ANOMALY_TOTAL_IMPACT_ABSOLUTE\", \"MatchOptions\": [\"GREATER_THAN_OR_EQUAL\"], \"Values\": [\"1\"]}}
}"
This alerts you when an anomaly's estimated impact is at least $1, which is a sensible sensitivity for a learning account. Newer accounts may already have a default service monitor, so a duplicate is harmless. Between a budget, anomaly detection, and a regular sweep, you now have three independent ways to catch a runaway resource. One thing this is not is a real-time kill switch: detection runs on billing data that lags usage, and with a daily email you may hear about a problem many hours after it starts. It's an early-warning net, not a brake, which is why it complements the sweep and the budget instead of replacing them.

Part 4 — A real Well-Architected review, from the CLI

Create a workload in the Well-Architected Tool and list the framework's cost optimization questions. Using the tool is free:
WORKLOAD_ID=$(aws wellarchitected create-workload \
--workload-name zth-demo \
--description "Week 14 lab: practicing a Well-Architected review" \
--environment PREPRODUCTION \
--lenses wellarchitected \
--aws-regions $(aws configure get region) \
--query WorkloadId --output text)

aws wellarchitected list-answers \
--workload-id $WORKLOAD_ID --lens-alias wellarchitected \
--pillar-id costOptimization \
--query 'AnswerSummaries[].[QuestionTitle]' --output table
Read the questions. Notice they're not "did you do X," they're things like how you govern usage, how you monitor cost, and how you decide when to commit to pricing. Pick one of your own earlier labs and try answering each honestly. The questions you can't answer are your real to-do list. Answering them in the console is easier than the CLI, because each question presents its choices and explains the best practice behind it. The other pillars work the same way; just change  --pillar-id  to  security ,  reliability ,  performance ,  operationalExcellence , or  sustainability .

Cleanup

A note before the first command: deleting the workload also deletes the review answers and progress you recorded in it. The Well-Architected Tool is free, so there's no cost reason to delete it. Skip that line if you want to keep your review.
aws wellarchitected delete-workload --workload-id $WORKLOAD_ID

aws ce delete-anomaly-subscription --subscription-arn <arn-returned-when-you-created-it>
aws ce delete-anomaly-monitor --monitor-arn $MONITOR_ARN
Keep  zombie_hunt.sh  and the Week 11 budget. Those two are the parts of this series that are worth running for as long as you have an AWS account.



My Take

This week tied everything together. The biggest lesson for me is that AWS cost optimization isn't about choosing the cheapest services; it's about understanding what you're paying for and avoiding waste. The zombie hunt script and Cost Explorer made me realize how easily small, forgotten resources can quietly add up. Going forward, I want to make regular cost checks and cleanup a habit rather than something I do only at the end of a lab.



Next week — Part 15: AWS vs. Azure vs. Google Cloud, honestly — where AWS genuinely leads, where competitors have real advantages, and how companies actually choose.

Series: AWS: Zero to Hero (14 articles)

  1. …
  2. 14
    AWS: Zero to Hero — Week 14: Cost Optimization and the Well-Architected Framework This article
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article