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.
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 andPUTs, 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.
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.
The classic cost traps
- 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.
- 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.
- Data egress: serving large files straight from S3 or EC2 to the internet. CloudFront usually lowers it, and its own free allowance helps.
- Cross-AZ chatter: services in different AZs calling each other heavily pay per GB in each direction.
- Logs with no retention: CloudWatch log groups default to "never expire".
- Overprovisioning:
m7i.2xlargerunning at 4% CPU. AWS Compute Optimizer suggests right-sizing. - Dev environments running at night and on weekends: about 70% of the hours in a week are outside working hours.
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.
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=checkoutandenv=devlet 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.
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");The bill doubled this month. Order your investigation.
- Tap the steps below in the right order.
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:
- Default tags in IaC. CDK's
Tags.of(app)(above) or Terraform's providerdefault_tagsadd tags to everything the code creates. This covers most resources with no effort. - Tag policies in AWS Organizations standardize keys and allowed values, for example
envmust be one ofdev,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. - An SCP that denies creation without the tag. This is the hard stop.
{
"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.
project must be one of five values. A developer still launches an EC2 instance with no tags at all, and it succeeds. Why?Saving money on purpose
| Lever | Typical saving | Good for |
|---|---|---|
| Turn off or delete idle things | 100% of that resource | Dev, test, forgotten experiments |
| Right-size instances and tasks | 20-50% | Anything at low utilization |
| Graviton (ARM) instances | about 20% | Most Linux workloads |
| Savings Plans | up to about 70% | Steady compute you will keep running |
| Spot / Fargate Spot | up to about 90% | Interruptible batch and workers |
| S3 lifecycle rules, Intelligent-Tiering | large for old data | Logs, backups, archives |
| Gateway endpoints, CloudFront | NAT and egress fees | Data-heavy apps |
| Serverless for spiky traffic | pay only per use | Low or bursty workloads |
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.
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.
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:
- 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
aarch64build. - Build multi-architecture images so one tag runs on both. Multi-Architecture Images (in the Docker course) covers the build.
- 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.
- 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.
Operational excellence: can you deploy safely and often, and do you know when it breaks?
Match each practice to its Well-Architected pillar.
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.
| Business | Unit | Why it works |
|---|---|---|
| E-commerce | Cost per 1,000 orders | Grows with revenue, comparable month to month |
| B2B SaaS | Cost per active customer (or seat) | Lines up with how the company charges |
| API platform | Cost per million requests | Matches the product's own unit |
| Data pipeline | Cost per GB processed | Shows 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.
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):
| Item | Example 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 out | first 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)- 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=checkoutactivated 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.