Skip to content

Lesson 26 of 30Putting it together

Cost and the Well-Architected Framework

Read an AWS bill, avoid the classic cost traps, set up budgets, and review designs against the six Well-Architected pillars.

27 min read0/7 questions

You have built, secured, automated and shipped the pieces. This last unit steps back to judge the whole design. AWS makes it easy to build almost anything and just as easy to get a $3,000 surprise at the end of the month. Engineers who can say what a design will cost, and where the money leaks, are rare and valued. This lesson teaches you to read the bill and then gives you AWS's own checklist for judging whether a design is good: the Well-Architected Framework.

How AWS bills

Almost every charge is one of four kinds:

  • Compute time: per second or hour that something runs. EC2 instances, Fargate tasks, RDS instances, NAT gateways, load balancers. These bill whether or not anyone uses them.
  • Requests: per call. Lambda invocations, API Gateway requests, S3 GETs and PUTs, DynamoDB on-demand reads and writes.
  • Storage: per GB-month. S3, EBS volumes, snapshots, RDS storage, CloudWatch Logs.
  • Data transfer: per GB moved. Data into AWS from the internet is free. Data out to the internet (egress) costs money, and so does traffic between AZs and between Regions.
Pythonbill.py
# Example prices only (roughly us-east-1). Prices change; check the pricing pages.items = [ ("2x Fargate tasks (0.5 vCPU, 1 GB) 24/7", 2 * (0.5 * 0.04048 + 1 * 0.004445) * 730), ("ALB, 730 hours + light traffic", 0.0225 * 730 + 5.00), ("RDS db.t4g.micro, 20 GB, single-AZ", 0.016 * 730 + 20 * 0.115), ("NAT gateway, 730 hours + 50 GB", 0.045 * 730 + 50 * 0.045), ("S3, 50 GB Standard", 50 * 0.023), ("Data out, 150 GB (first 100 GB free)", (150 - 100) * 0.09), ("CloudWatch Logs, 10 GB ingested", 10 * 0.50),]total = 0for name, cost in items: total += cost print(f"{name:<42} ${cost:7.2f}")print(f"{'TOTAL':<42} ${total:7.2f}")
Output
Press Run (⌘ Enter) to see what happens.

Run it and look at the NAT gateway line: for a small app it can cost more than the servers. Notice too that most of the bill is things that run 24/7, not traffic.

Quick check
Your app has zero users this month. Which of these still costs money?
Need a nudge? A hint rules out a wrong answer.

The classic cost traps

  1. NAT gateways: hourly charge per gateway (often one per AZ) plus a per-GB processing fee. Traffic to S3 or DynamoDB through a NAT is pure waste; use the free gateway endpoints. Pulling big images through a NAT on every deploy adds up.
  2. Idle and forgotten resources: a test EC2 instance, an unattached EBS volume, old snapshots, an RDS instance someone "will use next week", a load balancer with no targets. Elastic IPs and all public IPv4 addresses now bill hourly too.
  3. Data egress: serving large files straight from S3 or EC2 to the internet. CloudFront usually lowers it, and its own free allowance helps.
  4. Cross-AZ chatter: services in different AZs calling each other heavily pay per GB in each direction.
  5. Logs with no retention: CloudWatch log groups default to "never expire".
  6. Overprovisioning: m7i.2xlarge running at 4% CPU. AWS Compute Optimizer suggests right-sizing.
  7. Dev environments running at night and on weekends: about 70% of the hours in a week are outside working hours.
Pythonnat_vs_endpoint.py
# Example prices. Moving 2 TB a month from private subnets to S3.gb = 2000nat_hourly, nat_per_gb = 0.045, 0.045 through_nat = 730 * nat_hourly + gb * nat_per_gbwith_gateway_endpoint = 730 * nat_hourly # NAT still exists for other traffic, S3 bytes skip it print(f"S3 traffic through NAT: ${through_nat:8.2f}/month")print(f"With S3 gateway endpoint: ${with_gateway_endpoint:8.2f}/month")print(f"Saved by a free route entry: ${through_nat - with_gateway_endpoint:8.2f}/month")
Output
Press Run (⌘ Enter) to see what happens.

A data transfer bill, worked through

Data transfer is the line nobody designs for, because it does not appear in any diagram. Advanced VPC Networking lists where bytes cost money; here you apply it to one realistic service and count the gigabytes each charge line meters. Multiply by the current rates from the pricing pages when you need the money figure. The shape is what matters.

The setup: an API runs as 18 Fargate tasks spread across three AZs in private subnets. One NAT gateway sits in the first AZ. Tasks read user uploads from S3, call a payments API on the internet, talk to a Postgres primary in one AZ, and the team deploys 30 times a month.

Pythontransfer_meter.py
# One month, in GB. No prices: count what each charge line will meter.image_layers_gb = 30 * 0.4 * 18 # 30 deploys, 0.4 GB image, 18 tasks pullings3_reads_gb = 1200 # tasks reading uploads from S3third_party_gb = 60 # calls to a payments API on the internetdb_traffic_gb = 900 # API <-> Postgres, both directions combinedinternet_out_gb = 400 # responses to users through the load balancerremote = 2 / 3 # share of tasks NOT in the same AZ as the target def meter(s3_endpoint: bool, nat_per_az: bool) -> dict: # ECR serves image layers from S3, so the S3 gateway endpoint carries them too. via_nat = third_party_gb + (0 if s3_endpoint else s3_reads_gb + image_layers_gb) cross_az = db_traffic_gb * remote + (0 if nat_per_az else via_nat * remote) return {"NAT processing": via_nat, "cross-AZ transfer": cross_az, "internet egress": internet_out_gb} for label, args in [("as built: one NAT, no endpoints", (False, False)), ("+ S3 gateway endpoint", (True, False)), ("+ one NAT per AZ", (True, True))]: print(label) for name, gb in meter(*args).items(): print(f" {name:<18} {gb:6.0f} GB")
Output
Press Run (⌘ Enter) to see what happens.

Read the three runs:

  • As built, almost everything goes through the NAT, and two thirds of it first crosses an AZ to reach the NAT. Those bytes are metered twice: once as cross-AZ transfer, once as NAT processing.
  • The S3 gateway endpoint removes the S3 reads and the image pulls, because ECR stores image layers in S3. That is why private subnets that pull from ECR need the S3 gateway endpoint even when they have interface endpoints for the ECR API. The endpoint itself is free.
  • A NAT per AZ removes the cross-AZ hop for what is left. With only the payments traffic remaining, the saving is small, which is the point: fix the big flow first, then decide whether the remaining one is worth another NAT's hourly charge.

The database traffic does not go away. Tasks in three AZs talking to a primary in one AZ cross an AZ on two thirds of their queries. That is the price of spreading compute for availability, and usually worth paying. If it grows large, the fix is fewer round trips (caching, batching queries), not moving everything into one AZ.

Tools: Cost Explorer, Budgets and tags

  • AWS Cost Explorer graphs your spend by service, account, Region, usage type and tag, and forecasts the month. When the bill jumps, group by usage type to see exactly what grew (NatGateway-Bytes, DataTransfer-Out-Bytes).
  • AWS Budgets alerts on actual or forecasted cost or usage, and budget actions can apply an IAM policy that blocks new resources when you cross a line.
  • Cost allocation tags like project=checkout and env=dev let you split the bill by team or environment. Activate them in the Billing console, then tag everything (IaC makes this automatic).
  • Cost Anomaly Detection uses machine learning to flag unusual spend and email you.
CDK: tag everything in a stack
import { Tags } from "aws-cdk-lib";
 
Tags.of(app).add("project", "checkout");
Tags.of(app).add("env", "dev");
Tags.of(app).add("owner", "team-payments");
Put it in order4 steps

The bill doubled this month. Order your investigation.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

Catching spend early: anomalies and enforced tags

A budget alert tells you the month went over. By then the waste is spent. Two controls shorten the gap.

Cost Anomaly Detection learns your normal spend and alerts on unusual jumps, usually within a day. Set it up as monitors (by AWS service, by linked account, by cost category or by cost allocation tag) and alert subscriptions that send either each anomaly as it happens or a daily or weekly summary, filtered by an impact threshold so a small wobble does not email anyone. A per-service monitor across the organization plus a per-team tag monitor is a sensible start. Route the immediate alerts to the team channel, not to one person's inbox.

Tags only split the bill if they are actually there. Activated cost allocation tags are not retroactive, and every untagged resource lands in a bucket called "no tag" that nobody owns. Teams enforce tagging in three layers:

  1. Default tags in IaC. CDK's Tags.of(app) (above) or Terraform's provider default_tags add tags to everything the code creates. This covers most resources with no effort.
  2. Tag policies in AWS Organizations standardize keys and allowed values, for example env must be one of dev, staging, prod, with the exact capitalization. They report non-compliant resources and can block non-compliant tagging operations, but on their own they do not force a tag to exist.
  3. An SCP that denies creation without the tag. This is the hard stop.
scp-require-project-tag.json
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "RequireProjectTagOnCreate",
      "Effect": "Deny",
      "Action": ["ec2:RunInstances", "ec2:CreateVolume", "rds:CreateDBInstance"],
      "Resource": "*",
      "Condition": { "Null": { "aws:RequestTag/project": "true" } }
    }
  ]
}

Null: true means "the request carries no project tag", so the create call is denied. It only works for actions that accept tags in the create request, and some services or resource types do not, so start with the expensive ones and test in a sandbox account first. Multiple Accounts, Organizations and SSO explains how SCPs attach to OUs and why they never grant anything.

Quick check
Your organization has a tag policy saying project must be one of five values. A developer still launches an EC2 instance with no tags at all, and it succeeds. Why?
Need a nudge? A hint rules out a wrong answer.

Saving money on purpose

LeverTypical savingGood for
Turn off or delete idle things100% of that resourceDev, test, forgotten experiments
Right-size instances and tasks20-50%Anything at low utilization
Graviton (ARM) instancesabout 20%Most Linux workloads
Savings Plansup to about 70%Steady compute you will keep running
Spot / Fargate Spotup to about 90%Interruptible batch and workers
S3 lifecycle rules, Intelligent-Tieringlarge for old dataLogs, backups, archives
Gateway endpoints, CloudFrontNAT and egress feesData-heavy apps
Serverless for spiky trafficpay only per useLow or bursty workloads
Quick check
A dev environment runs 4 Fargate tasks and an RDS instance 24/7, but the team works 9 to 6, Monday to Friday. Cheapest change with no code edits?
Need a nudge? A hint rules out a wrong answer.

Savings Plans and Reserved Instances: the maths

Commitments are the biggest single discount on steady compute, and the easiest way to waste money if you get the size wrong.

  • A Compute Savings Plan commits you to a fixed amount of spend per hour, at discounted rates, for one or three years. It applies across EC2 instance families, sizes and Regions, and to Fargate and Lambda. You can change everything about your compute and the discount follows.
  • An EC2 Instance Savings Plan gives a deeper discount but locks you to one instance family in one Region (any size, OS or AZ within it).
  • Reserved Instances are the older model. For EC2, Savings Plans have mostly replaced them. They still matter for services that Savings Plans did not traditionally cover, such as RDS, ElastiCache, OpenSearch and Redshift. AWS has been extending Savings Plans to more services, so check the current coverage before buying either.

The mechanics drive the decision. Every hour of the term you pay the commitment, used or not. Usage the commitment does not cover is charged at on-demand rates. So the question is not "what is our average usage?" but "what is the floor we will always run, every hour, for the whole term?".

Run this calculator. Usage is in normalized units (1.0 is one hour of compute at on-demand rates), so no prices are needed. The 30 percent discount is an example; real rates depend on plan type, term and payment option.

Pythonsavings_plan.py
# Normalized: 1.00 = one hour of compute at the on-demand rate.# The discount is an example; real rates depend on plan type, term and payment option.DISCOUNT = 0.30hourly_usage = [4] * 8 + [10] * 10 + [6] * 6 # one typical day, on-demand units per hour def daily_cost(commit: float) -> tuple[float, float]: total, wasted = 0.0, 0.0 covers = commit / (1 - DISCOUNT) # on-demand usage one hour of commitment pays for for used in hourly_usage: total += commit + max(used - covers, 0) # commitment is paid every hour, the rest on demand wasted += max(covers - used, 0) * (1 - DISCOUNT) return total, wasted on_demand = sum(hourly_usage)print(f"all on demand: {on_demand:.1f}")for commit in [0, 2.8, 4.2, 7.0]: cost, wasted = daily_cost(commit) print(f"commit {commit:>3}/h: pay {cost:5.1f}, wasted {wasted:4.1f}, saves {1 - cost / on_demand:4.0%}")
Output
Press Run (⌘ Enter) to see what happens.

The usage never drops below 4 units, and 4 units at a 30 percent discount is a commitment of 2.8 per hour. That commitment is fully used every hour and saves the most. Commit to more and the night hours waste part of it; commit to the peak and the waste cancels the discount entirely. Real teams look at the last few months of hourly usage in Cost Explorer's Savings Plans recommendations, commit to something close to the floor, and add more later as the floor rises. You can always buy another plan. You cannot shrink one.

Quick check
Compute usage over the last three months never fell below 40 units per hour, averaged 65, and peaked at 120. Growth is uncertain. What commitment is the safest starting point?
Need a nudge? A hint rules out a wrong answer.

Compute Optimizer and moving to Graviton

Right-sizing by hand means staring at graphs. AWS Compute Optimizer does it from your CloudWatch metrics and recommends sizes for EC2 instances, Auto Scaling groups, EBS volumes, Lambda memory and ECS services on Fargate, with support for more resource types added over time. Three things to know before you act on it:

  • It is blind to memory on EC2 unless the CloudWatch agent publishes memory metrics. Without them, it may recommend a smaller instance that then runs out of memory.
  • By default it looks at a couple of weeks of history. A monthly batch job may not be in that window. Longer lookback is available as a paid option.
  • It often recommends a Graviton (ARM) instance type. Treat that as a separate project, not a resize.

Moving to Graviton is usually worth it for Linux workloads: similar or better performance for less money and less energy. The work is in finding what does not run on ARM yet:

  1. Inventory native code. Pure Python, Node and Java usually just work. Python wheels with C extensions, Node native modules and anything that downloads a binary at build time need an aarch64 build.
  2. Build multi-architecture images so one tag runs on both. Multi-Architecture Images (in the Docker course) covers the build.
  3. Canary it. Run a share of tasks or one Auto Scaling group on Graviton, compare latency, error rate and cost per request, then shift the rest.
  4. For Lambda, it is one setting (arm64) plus native dependencies built for ARM.

Rollback is simply going back to the x86 instance type or task architecture, which is why a canary is cheap insurance.

The Well-Architected Framework

The AWS Well-Architected Framework is AWS's checklist for reviewing a design. It has six pillars, and the free Well-Architected Tool in the console walks you through questions for each one.

Six pillars
  1. Operational excellenceRun and improve it: IaC, small reversible changes, runbooks, observability
  2. SecurityLeast privilege, encryption, traceability, protect every layer
  3. ReliabilityMulti-AZ, auto recovery, backups, tested restores, scaling
  4. Performance efficiencyRight resource types, serverless where it fits, caching, measure
  5. Cost optimizationPay only for what you need, measure spend, right-size, commit wisely
  6. SustainabilityUse less: high utilization, efficient hardware like Graviton, delete what you do not need

Operational excellence: can you deploy safely and often, and do you know when it breaks?

1/4
Match the pairs0/6 matched

Match each practice to its Well-Architected pillar.

Choose an item, then its match on the other side.

Unit economics: the number seniors report

"We spent more this month" is not useful on its own. If traffic doubled and the bill rose by a third, the system got more efficient. Senior engineers and engineering managers report unit cost: spend divided by a business unit that the company cares about.

BusinessUnitWhy it works
E-commerceCost per 1,000 ordersGrows with revenue, comparable month to month
B2B SaaSCost per active customer (or seat)Lines up with how the company charges
API platformCost per million requestsMatches the product's own unit
Data pipelineCost per GB processedShows efficiency independent of volume

To make it real you need two things. First, the cost side split per product, which is what the tagging and cost categories above are for; shared costs such as networking and observability get allocated by a simple rule, such as by request share. Second, the unit count from your own metrics or database.

Then watch the trend. A rising unit cost is a design problem worth an engineer's time even when the total is small. A falling unit cost with a rising total is growth, and that conversation goes very differently with finance. In design reviews, estimate the unit cost of a new feature before building it: "this adds roughly one extra DynamoDB write and one Lambda call per order" is an answer finance can work with.

Quick check
Last quarter the AWS bill grew 25 percent while orders grew 60 percent. The CFO asks whether engineering has a cost problem. What is the best answer?
Need a nudge? A hint rules out a wrong answer.
ChallengeMedium

Estimate a monthly AWS bill

Estimate a small app's monthly bill from its usage. usage is an object with four numbers: instance_hours, storage_gb, nat_gb (data processed by a NAT gateway) and egress_gb (data transferred out to the internet). The month also needs a NAT gateway running all hours of it if nat_gb > 0.

Use these example prices (real ones vary by region and change):

ItemExample price
Instance$0.0416 per instance-hour
Storage$0.023 per GB-month
NAT gateway$0.045 per hour it exists, plus $0.045 per GB processed
Data outfirst 100 GB free, then $0.09 per GB

Write monthly_bill(usage, hours) returning the total in dollars.

usage = {"instance_hours": 1460, "storage_gb": 100, "nat_gb": 0, "egress_gb": 50}
monthly_bill(usage, 730)  →  about 63.036   (60.736 compute + 2.30 storage, no NAT, egress free)
def monthly_bill(usage: dict, hours: int) -> float: pass
Key terms
data egress
Data transferred out of AWS to the internet. Billed per GB; ingress is free.
Cost Explorer
AWS's tool for graphing and breaking down spend by service, usage type and tag.
cost allocation tag
A tag like project=checkout activated for billing, so spend can be split by owner.
Savings Plan
A 1 or 3 year commitment to an hourly compute spend in exchange for a large discount.
Well-Architected Framework
AWS's six-pillar checklist: operational excellence, security, reliability, performance efficiency, cost optimization, sustainability.
right-sizing
Matching instance or task size to actual usage instead of guessing high.
Cost Anomaly Detection
A billing service that learns normal spend and alerts on unusual jumps, per service, account or tag.
Compute Optimizer
An AWS service that recommends instance, task, volume and Lambda sizes from CloudWatch metrics.
unit cost
Spend divided by a business unit, such as cost per 1,000 orders, used to judge efficiency as the business grows.