Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 4 of 6 · Worked example · 20 min · revision 3

Cost as an engineering signal: tags, budgets, rightsizing and teardown

A worked example: make the cost of a staging environment visible with tags, watch it with a filtered budget, understand why a budget alerts but does not stop spending, cut waste with rightsizing, pricing models and network choices, and tear environments down reliably with one command and a check that nothing was left behind.

Contentsand lesson path

What you will learn

  • Keep costs visible and bounded with resource tags, budgets and alerts, and tear environments down reliably.

Prerequisites: Networking Basics

01. The problem

A team runs a staging environment and creates a preview environment for every pull request. Last month the bill doubled. Nobody can say which environment or team caused it, and a clean-up found load balancers and disks from branches merged weeks ago. The goal is to make spend visible (who and what costs how much), bounded (you hear about overspend early and can stop it), and temporary environments really temporary.

In the cloud anyone with the right permissions can start costly resources in seconds, so cost behaves like any other production signal: a change that doubles spend without more traffic is a regression to investigate, just like a jump in latency.

02. Step 1: Make cost attributable with tags

You can only split a bill along dimensions you recorded. Agree a small set of tags and put them on everything:

  • Environment: production, staging, preview or ephemeral;
  • Service: the application or component, such as billing-api;
  • Owner: the team to ask, such as team-payments;
  • ExpiresAt on temporary resources: the UTC time after which they may be deleted;
  • PR on preview environments: the pull request number, so CI can find exactly what one pull request created.

Set them once with the provider's default_tags, as lab 3 does, so no resource is forgotten. Then activate them as cost allocation tags in the Billing console. A new tag key can take up to 24 hours to appear on that page and up to another 24 hours to activate, so do it on the first day, not the day finance asks.

To enforce tags across many accounts, an organisation can attach SCPs that deny create calls missing a required tag (a Null condition on aws:RequestTag/Environment). That only works for actions that support tagging on create, and SCPs never apply to the organisation's management account. Tag policies standardise allowed values. Neither covers everything, so also scan regularly for untagged resources, for example with AWS Resource Explorer and the query tag:none.

03. Step 2: A budget for the environment, and what it does not do

A budget compares spend with a limit and notifies people. The cost_filter is what makes this a staging budget: without it, a budget named "staging" silently tracks the whole account. The filter value combines the tag key, with the user: prefix for user-defined tags, and the value, separated by $. Two notifications cover two speeds: actual spend past 80% of the limit, and forecast spend past 100%, which warns mid-month that the current rate will overshoot. For the lab account in this skill, drop the filter and set the limit to about US$10.

HCL · budget.tf
variable "alert_email" {
  type = string
}

resource "aws_budgets_budget" "staging" {
  name         = "staging-monthly"
  budget_type  = "COST"
  limit_amount = "500"
  limit_unit   = "USD"
  time_unit    = "MONTHLY"

  # Only costs tagged Environment=staging (an activated cost allocation tag).
  cost_filter {
    name   = "TagKeyValue"
    values = ["user:Environment$staging"]
  }

  notification {
    comparison_operator        = "GREATER_THAN"
    threshold                  = 80
    threshold_type             = "PERCENTAGE"
    notification_type          = "ACTUAL"
    subscriber_email_addresses = [var.alert_email]
  }

  notification {
    comparison_operator        = "GREATER_THAN"
    threshold                  = 100
    threshold_type             = "PERCENTAGE"
    notification_type          = "FORECASTED"
    subscriber_email_addresses = [var.alert_email]
  }
}

04. Step 3: Pay less for what has to run

Once cost is visible, these levers usually matter most:

  1. Rightsizing. Look at at least two weeks of CPU and memory use, at the 95th percentile rather than the average, and move over-sized instances to a smaller size or family. An instance whose CPU peaks at 15%, with memory and network to spare as well, is paying for capacity it does not use. Re-check after the change: latency, not just utilisation, decides whether it worked.
  2. Pricing models. On-demand has no commitment. Spot capacity is heavily discounted, but the provider can reclaim it at short notice: two minutes on AWS and about 30 seconds on Google Cloud and Azure. Use it for stateless, retryable work such as CI runners and batch jobs. Savings Plans or reserved capacity give a discount for committing to a level of use for one or three years; cover the steady baseline with them and leave peaks on demand or spot.
  3. Schedules. A staging environment used 10 hours a day on weekdays runs 50 of 168 weekly hours. Stopping its instances outside those hours removes about 70% of their compute hours, but disks, Elastic IPs, NAT gateways and load balancers keep billing while stopped, so delete what you do not need.
  4. Storage classes. Lifecycle rules move or expire objects you no longer read. S3 Intelligent-Tiering moves an object that has not been accessed for 30 days to its Infrequent Access tier and, after 90 days, to Archive Instant Access, without retrieval delays.
  5. Network paths. Data processed by a NAT gateway is charged per GB. Traffic from private subnets to S3 or DynamoDB can go through a gateway VPC endpoint instead, which has no charge. Interface endpoints (PrivateLink) cost per hour and per GB, so compare them with the NAT cost before switching. Traffic between availability zones is also charged per GB in each direction, so keep chatty services in the same zone where resilience allows.

05. Step 4: Tear down reliably and prove it

Teardown is reliable when the code that created an environment also removes it, triggered by the event that ends the environment rather than by someone remembering. Give each preview environment its own state (an OpenTofu workspace or a state key per pull request), create it from CI when the pull request opens, and destroy it from CI when the pull request closes.

Know what commonly survives or blocks a destroy:

  • Deletion protection on a database: set it to false and apply before destroying.
  • Non-empty buckets: deleting a bucket that still holds objects or versions fails unless force_destroy = true, which deletes every version and is only right for temporary data.
  • Final snapshots: with skip_final_snapshot = false, RDS keeps a snapshot after deletion, which you keep paying for.
  • Resources outside the state: anything made in the console or CLI (such as the restored database in lab 7) or by a controller, such as a load balancer created by Kubernetes. OpenTofu does not know about them, and they can also stop it deleting subnets and security groups.

Then prove that nothing is left. The tagging API lists every resource in a region that carries a tag; the small script below turns its output into a count per service and a non-zero exit code, so CI can fail the teardown job when something survives. It only sees tagged resources in one region, so pair it with the untagged scan from step 1 and, the next day, Cost Explorer grouped by the Environment tag.

Bash · CI job on "pull request closed" (PR number in $PR)
tofu workspace select "pr-$PR"
tofu destroy -auto-approve
tofu workspace select default && tofu workspace delete "pr-$PR"
aws resourcegroupstaggingapi get-resources \
  --tag-filters "Key=Environment,Values=preview" "Key=PR,Values=$PR" \
  > leftovers.json
python3 check_leftovers.py < leftovers.json
Python · check_leftovers.py
"""Fail when the tagging API still lists resources.

Usage: aws resourcegroupstaggingapi get-resources ... | python3 check_leftovers.py
"""
import json
import sys
from collections import Counter

arns = [r["ResourceARN"] for r in json.load(sys.stdin)["ResourceTagMappingList"]]
for service, n in sorted(Counter(a.split(":")[2] for a in arns).items()):
    print(f"{service:<8} {n}")
for arn in sorted(arns):
    print(f"  {arn}")
print(f"leftovers: {len(arns)}")
sys.exit(1 if arns else 0)
Terminal: try the check without an AWS account
echo '{"ResourceTagMappingList": []}' | python3 check_leftovers.py; echo "exit=$?"
cat > sample.json <<'EOF'
{"ResourceTagMappingList": [
  {"ResourceARN": "arn:aws:rds:ap-southeast-1:123456789012:db:lab-orders-restored"},
  {"ResourceARN": "arn:aws:ec2:ap-southeast-1:123456789012:volume/vol-0abc"}
]}
EOF
python3 check_leftovers.py < sample.json; echo "exit=$?"
Expected output
leftovers: 0
exit=0
ec2      1
rds      1
  arn:aws:ec2:ap-southeast-1:123456789012:volume/vol-0abc
  arn:aws:rds:ap-southeast-1:123456789012:db:lab-orders-restored
leftovers: 2
exit=1

06. Check your understanding

Practice check · 3 questions

Cost visibility and teardown check

Diagnose three cost problems.

Q1. A budget called `staging-monthly` alerts at 80% in the first week, yet the staging resources cost little. Its definition has a limit, a time unit and two notifications. What is the most likely cause?
Q2. After `tofu destroy` reports success, the tagging API still lists an RDS instance named `lab-orders-restored`. Why did destroy leave it?
Q3. A team spreads its API servers and their cache cluster across three availability zones, so that one zone can fail without an outage. The number and size of the instances stay the same, but the next bill shows a data-transfer charge that grows with traffic. What is the most likely cause?
Practice only: not graded, not saved, not evidence.

07. Apply it

For the skill practice:

  • Tag every resource through default_tags and activate Environment, Service and Owner as cost allocation tags.
  • Create a budget for the practice environment with actual and forecast notifications, and write down which control would stop spend if the alert fired at night.
  • Destroy everything with one command, run the leftover check, and keep its output (with leftovers: 0) as evidence.
  • The next day, open Cost Explorer grouped by Environment and record what the practice cost.

08. Review prompt

Without looking back, list the tags you would require and why each one exists, explain why a budget alone cannot bound spend and name two controls that can, and give three things that commonly survive or block a tofu destroy. Then describe how you would prove that a teardown left nothing behind.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check