Skip to content

Intermediate · Serverless, monitoring and cost control · topic 22 of 50 · 30 min

Cost control in practice

Explanation

In the cloud nothing stops you spending, and the bill arrives at the end of the month. Control it in three steps: see it (budgets with alerts, Cost Explorer, anomaly detection and tags), cut waste (rightsize, schedule dev servers, delete forgotten volumes, IPs and NAT gateways, add S3 lifecycle rules), and pay less for what stays (Savings Plans and Spot). FinOps makes this a shared, regular habit.

Why cloud bills surprise people

With pay-as-you-go pricing there is no purchase order to sign. Anyone with permission can start a large server in seconds, and it keeps charging until someone stops it. The bill arrives at the end of the month, long after the mistake. Most surprise bills are not from heavy use. They come from things people forgot: a test server, a NAT gateway, a disk left behind after an instance was terminated.

Step 1: see the money

AWS Budgets lets you set a monthly amount and get alerts. Use two kinds: actual (you have already spent 80%) and forecasted (at this rate you will spend more than 100% by month end). The forecast alert is the early warning. Alerts go to email or an SNS topic. Budget actions can even apply a restrictive IAM policy or stop EC2 and RDS instances when a limit is hit. Basic budgets are free; check the pricing page for budgets with actions.

json
{
  "BudgetName": "monthly-10-usd",
  "BudgetLimit": { "Amount": "10", "Unit": "USD" },
  "TimeUnit": "MONTHLY",
  "BudgetType": "COST"
}
budget.json. Create it with: aws budgets create-budget --account-id 111122223333 --budget file://budget.json --notifications-with-subscribers file://notifications.json
json
[
  {
    "Notification": {
      "NotificationType": "FORECASTED",
      "ComparisonOperator": "GREATER_THAN",
      "Threshold": 80,
      "ThresholdType": "PERCENTAGE"
    },
    "Subscribers": [{ "SubscriptionType": "EMAIL", "Address": "you@example.com" }]
  }
]
notifications.json: email when the forecast passes 80% of the budget.

Cost Explorer shows past spending and a forecast as graphs you can group by service, Region, account or tag. Cost Anomaly Detection uses machine learning to spot unusual jumps, such as a service that suddenly costs five times more than usual, and emails you a summary.

Tags: knowing whose cost it is

A tag is a key and value label on a resource, like Project=canteen-app. A good tagging strategy picks a few required tags and uses them everywhere: Project, Environment (dev, test, prod), Owner and CostCentre. In the Billing console you must activate them as cost allocation tags; only then can Cost Explorer and the bill be split by them. Enforce tags with infrastructure as code or tag policies in AWS Organizations, and review untagged resources every week.

Step 2: cut the waste

WasteWhy it costsFix
Oversized instancesAn m-size server running at 5% CPURightsize using AWS Compute Optimizer recommendations
Dev servers running 24×7168 hours a week paid, about 50 usedStop them out of office hours (Instance Scheduler or EventBridge Scheduler)
Unattached EBS volumesDisks keep charging after the instance is goneSnapshot if needed, then delete
Old snapshots and AMIsStorage adds up month after monthLifecycle policies (Amazon Data Lifecycle Manager)
Public IPv4 addressesCharged per hour, in use or idle, since February 2024Release unused Elastic IPs; use load balancers or IPv6 where you can
Idle NAT gatewaysAn hourly charge plus a per-GB processing charge, even with no trafficDelete after labs; use free gateway endpoints for S3 and DynamoDB
Old S3 dataEverything stays in the most expensive classS3 lifecycle rules, Intelligent-Tiering, abort incomplete multipart uploads
Logs kept foreverLog storage grows every monthSet log group retention

Scheduling dev servers is the easiest big win. A week has 24 × 7 = 168 hours. Office hours of 10 hours × 5 days are 50 hours. Running only in office hours saves 118 of 168 hours, about 70% of the compute cost. Remember that a stopped instance still pays for its EBS volumes and any public IPv4 address.

Step 3: pay less for what stays

  • Savings Plans: commit to a fixed spend per hour for 1 or 3 years. Compute Savings Plans also cover Fargate and Lambda. Discounts can be large (AWS quotes up to about 72% for some plans); check the current figures.
  • Reserved Instances: a similar commitment for services like RDS.
  • Spot Instances: spare capacity at up to 90% off, but AWS can take it back with a 2-minute warning. Good for batch jobs, CI builds and stateless workers.
  • Graviton (Arm) instances and Lambda on Arm: usually a lower price for the same work.

Data transfer and Trusted Advisor

Data coming into AWS is free, but data going out to the internet is charged after a free monthly amount, and traffic between Availability Zones is charged too. A chatty app that sends lots of data across zones, or a website serving big files without a CDN, can cost more in transfer than in servers. AWS Trusted Advisor checks your account for cost savings such as idle load balancers and low-use instances; the full set of checks needs a Business or higher support plan.

A student horror story

A final-year student follows a tutorial to build a VPC with private subnets. The tutorial adds a NAT gateway. After the project demo she terminates the EC2 instances and thinks she is done. The NAT gateway and its Elastic IP keep running. At roughly US$0.045 an hour in us-east-1 (prices differ by Region), that is over US$30 a month before any data, and the free tier does not cover it. Two months later her card has been charged several thousand rupees. Another classic: launching a large GPU instance "just to try" and forgetting it over a weekend.

How to avoid it: create a budget with a forecast alert on day one; build labs with infrastructure as code so one command deletes everything; after every lab, check the Billing console and the VPC, EC2 (volumes, Elastic IPs) and NAT gateway pages in every Region you used; and turn on Cost Anomaly Detection. If it happens anyway, delete the resources and contact AWS Support quickly and honestly.

The FinOps idea

FinOps (cloud financial operations) is a practice where engineers, finance and managers share responsibility for cloud cost. The FinOps Foundation describes it in three repeating phases: inform (everyone can see what they spend), optimise (rightsize, schedule, commit) and operate (make it a routine with owners, reviews and targets). Engineers see cost as a design trade-off, just like speed or reliability.

Careful: Common mistakes: (1) Only an "actual" budget alert at 100%: by then the money is spent. Add forecast alerts. (2) Terminating instances but leaving their volumes, snapshots and Elastic IPs. (3) Forgetting to activate cost allocation tags, so Cost Explorer cannot group by them. (4) Buying a 3-year Savings Plan for a workload that may move to serverless next quarter. Start with a small commitment.

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

Cost control in practice · 1/7

Cost control in practice

This lesson is about keeping your cloud bill under control, which every employer cares about.

Prefer a video by a teacher? Find free videos on “aws cost optimization budgets cost explorer beginners avoid surprise bill” on YouTube ↗

In real life: An edtech startup in Noida cuts 40% of its AWS bill

A 20-person edtech startup saw its bill grow every month. Tagging every resource with Project, Environment and Owner showed that dev and test were nearly half the cost. They scheduled dev servers to run 9 am to 7 pm on weekdays, deleted 60 unattached EBS volumes and 15 idle Elastic IPs left by old experiments, replaced a NAT gateway in a test VPC with a gateway endpoint for S3, and set 30-day log retention. Compute Optimizer showed the production database server was twice the size it needed. Finally they bought a modest Compute Savings Plan for the steady production load. The monthly bill fell by about 40%, and a forecast budget alert now reaches the team channel.

Practice (0/3 done)

Task 1 · Code · Python

Write weekly_savings(hourly_rate, servers, hours_per_day=10, days_per_week=5). Always-on servers run 24 × 7 = 168 hours a week. Scheduled servers run hours_per_day × days_per_week hours. Return the money saved per week by scheduling all the servers, rounded to 2 decimal places.

Task 2 · Code · Python

Write find_idle(resources) that returns the ids of idle resources, in the same order as the input. Each resource is a dict with "id" and "type". Rules: "ebs" is idle when "attached" is False; "eip" is idle when "associated" is False; "ec2" is idle when "state" is "running" and "avg_cpu" (average over 14 days) is below 5; "nat" is idle when "gb_processed" (last 30 days) is below 1; "snapshot" is idle when "age_days" is over 365. Anything else is not idle.

Task 3 · Practice

Make your own AWS account safe from surprise bills. Do it today and write down what you set.

Quick quiz

Question 1

1.Which budget alert warns you earliest that you are heading over budget?

Question 2

2.You tagged everything with Project, but Cost Explorer cannot group by it. What is missing?

Question 3

3.A dev server runs only 10 hours a day, 5 days a week instead of 24 × 7. Roughly how much compute cost is saved?

Question 4

4.Which workload suits Spot Instances best?

Question 5

5.After a VPC lab you terminated the EC2 instances. Which leftover is most likely still charging by the hour?

Read more (free)

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

Which budget alert warns you earliest that you are heading over budget?

Answer: A forecasted alert at 80% or 100%

A forecast alert fires when AWS predicts you will cross the limit, before the money is actually spent.

You tagged everything with Project, but Cost Explorer cannot group by it. What is missing?

Answer: The tags must be activated as cost allocation tags

User-defined tags must be activated in the Billing console before cost reports can use them.

A dev server runs only 10 hours a day, 5 days a week instead of 24 × 7. Roughly how much compute cost is saved?

Answer: About 70%

168 hours minus 50 hours is 118 hours saved, and 118 / 168 is about 70%.

Which workload suits Spot Instances best?

Answer: Nightly image processing that can retry if a server is taken away

Spot capacity can be reclaimed with a 2-minute warning, so it suits interruptible work like batch jobs.

After a VPC lab you terminated the EC2 instances. Which leftover is most likely still charging by the hour?

Answer: A NAT gateway

NAT gateways charge per hour plus per GB processed. VPCs, security groups and route tables have no hourly charge.

You stopped an EC2 instance. What can still cost money?Related

Answer: Its attached disk storage

Stopped instances do not pay for compute, but their EBS volumes are still billed.

From Pricing, billing and cost control

Which part of the three-tier project keeps charging every hour even with no traffic, so it must be torn down after practice?Related

Answer: The NAT gateway, load balancer and RDS instance

NAT gateways, load balancers and databases have hourly charges; IAM and security groups are free.

From Portfolio projects that get interviews

You stop (not terminate) an EBS-backed instance. What happens?Related

Answer: The root volume is kept and you still pay for it

Stopping ends the compute charge but the EBS volumes remain, and storage is still billed.

From EC2: virtual servers in the cloud

Your budget of ₹10,000 reaches 100%. What happens by default?Related

Answer: Alert notifications are sent, but spending is not stopped automatically

Budgets only alert. Capping spend needs your own automation through Pub/Sub notifications.

From Google Cloud structure: projects, billing and IAM

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. This is the last topic of “Serverless, monitoring and cost control”. The module exam comes next.
  2. Module 5 exam: Serverless, monitoring and cost control · 13 questions · 20 min, without help. 4 topics of this module still to finish first.
  3. Then the next module, Microsoft Azure essentials. 50 topics left in the course before the final exam.

← Previous: Monitoring with CloudWatch, CloudTrail and Config