Sub topic 14
Budgets, anomaly detection, and tagging
This chapter assumes you can read a Cost Explorer report by usage type and run AWS CLI commands. It also assumes you know the transfer categories from earlier chapters: internet egress, inter-AZ, cross-region, and NAT gateway data processing. Those chapters cover finding and fixing transfer costs. This one covers keeping them from coming back.
Why transfer spend needs guardrails
Data transfer charges are usage-based and have no cap. A misconfigured job, a new service that routes through a NAT gateway, or a cache that stops working can multiply a line item within hours. Nobody notices until the monthly invoice, because transfer charges rarely show up in a capacity dashboard.
Three AWS tools cover this. Each answers a different question.
| Tool | Question it answers | Trigger | Typical lag |
|---|---|---|---|
| AWS Budgets | Will we exceed a number we chose? | A fixed or forecast threshold | Hours (billing data refreshes a few times a day) |
| Cost Anomaly Detection | Is spend unusual compared with history? | A machine-learning baseline | Up to about a day |
| Cost allocation tags | Which team or workload caused it? | None. They are attribution metadata. | Up to about a day after activation |
Budgets and anomaly detection tell you that something is wrong. Tags tell you whose it is.
Budgets scoped to transfer
A budget for the whole account is too coarse to catch transfer problems. A 5% rise in EC2 compute hides a 300% rise in NAT gateway bytes. Scope budgets to the usage types you studied earlier.
AWS Budgets can filter cost budgets by service, usage type, linked account, region, and tag. Useful transfer-focused budgets include:
- NAT gateway bytes. Filter on the
NatGateway-Bytesusage type. - Inter-AZ transfer. Filter on
DataTransfer-Regional-Bytes. - Internet egress. Filter on
DataTransfer-Out-Bytes.
Usage types carry a region prefix. In us-east-1 the prefix is USE1-, so the NAT usage type is USE1-NatGateway-Bytes. Check the exact strings in your own Cost Explorer usage type list before you write the filter, because a typo creates a budget that never matches anything and never alerts.
The following commands create a monthly budget for NAT gateway data processing in us-east-1. It sends an email when actual spend reaches 80% of the limit and when forecast spend exceeds 100%.
ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)
cat > budget.json <<'EOF'
{
"BudgetName": "nat-gateway-bytes-monthly",
"BudgetType": "COST",
"TimeUnit": "MONTHLY",
"BudgetLimit": { "Amount": "500", "Unit": "USD" },
"CostFilters": { "UsageType": ["USE1-NatGateway-Bytes"] }
}
EOF
cat > notifications.json <<'EOF'
[
{
"Notification": {
"NotificationType": "ACTUAL",
"ComparisonOperator": "GREATER_THAN",
"Threshold": 80,
"ThresholdType": "PERCENTAGE"
},
"Subscribers": [
{ "SubscriptionType": "EMAIL", "Address": "[email protected]" }
]
},
{
"Notification": {
"NotificationType": "FORECASTED",
"ComparisonOperator": "GREATER_THAN",
"Threshold": 100,
"ThresholdType": "PERCENTAGE"
},
"Subscribers": [
{ "SubscriptionType": "EMAIL", "Address": "[email protected]" }
]
}
]
EOF
aws budgets create-budget \
--account-id "$ACCOUNT_ID" \
--budget file://budget.json \
--notifications-with-subscribers file://notifications.jsonChoosing thresholds
Set the limit from your measured baseline, not from a guess. Take last month's cost for the usage type from the Cost Explorer query in the earlier chapter, then add headroom for expected growth. If the limit is too low, the alert fires every month and people learn to ignore it. If it is too high, it fires only after the damage is done.
The forecast alert is the most useful for transfer costs. It fires when the projected month-end total crosses the limit, which can be days before actual spend does. Early in a month the forecast is unreliable, because a few busy days extrapolate badly, so expect some noise on day one through five.
What budgets cannot do
- They are not real time. Budgets evaluate against billing data that refreshes a few times a day. A runaway job can cost several hours of spend before the first alert.
- They do not stop traffic. Budget actions can attach an IAM policy or a service control policy, or stop certain instances. None of these cuts a NAT gateway's traffic. Treat budgets as notification, and handle remediation with a runbook.
- They alert per budget. One budget per usage type and region means several budgets. Keep them in infrastructure-as-code so they stay consistent.
Anomaly detection
A budget needs a number from you. Cost Anomaly Detection learns each monitored segment's normal pattern and flags deviations, so it catches spikes that stay under your budget limit. A transfer spike on a Tuesday can be unusual even when the month total looks fine.
Setup has two parts:
- A monitor defines what to watch. Options include each AWS service, linked accounts, cost categories, or a cost allocation tag.
- A subscription defines who gets alerted, how often, and how large an anomaly must be.
The following commands create a per-service monitor and a daily email subscription for anomalies with a total impact of at least 100 USD.
MONITOR_ARN=$(aws ce create-anomaly-monitor \
--anomaly-monitor '{"MonitorName":"by-service","MonitorType":"DIMENSIONAL","MonitorDimension":"SERVICE"}' \
--query MonitorArn --output text)
aws ce create-anomaly-subscription \
--anomaly-subscription "{
\"SubscriptionName\": \"transfer-anomalies-daily\",
\"MonitorArnList\": [\"$MONITOR_ARN\"],
\"Subscribers\": [{\"Type\": \"EMAIL\", \"Address\": \"[email protected]\"}],
\"Frequency\": \"DAILY\",
\"ThresholdExpression\": {
\"Dimensions\": {
\"Key\": \"ANOMALY_TOTAL_IMPACT_ABSOLUTE\",
\"MatchOptions\": [\"GREATER_THAN_OR_EQUAL\"],
\"Values\": [\"100\"]
}
}
}"Gotchas
- Immediate alerts need SNS. The
IMMEDIATEfrequency works only with an SNS topic subscriber. Email subscribers useDAILYorWEEKLY. Route the SNS topic to chat or a pager if transfer spikes warrant a fast response. - Service-level monitors hide the cause. An anomaly in Amazon EC2 could be compute or NAT gateway bytes. The anomaly details include a root cause analysis with the usage type and region, so open it before you search elsewhere.
- Detection needs history. A new account or a new service has no baseline, and early results are weak.
- Absolute and percentage thresholds trade off. A percentage-only threshold fires on small line items that doubled. An absolute-only threshold ignores a rise from 10 USD to 90 USD. Pick the absolute impact that matches money you care about.
Tagging for attribution
Once an alert fires, the next question is who owns the traffic. Cost allocation tags answer it, but they have specific rules:
- Apply tags such as
team,application, andenvironmentto the resources that generate the charge. For transfer, the key resources are NAT gateways, load balancers, CloudFront distributions, and the instances sending traffic. - Activate each tag key as a cost allocation tag in the Billing console. A tag that exists on a resource but is not activated does not appear in Cost Explorer.
- Wait for the tag to appear, which can take up to about a day. Activation applies to cost data going forward, so check the console for the option to backfill earlier months.
- Group or filter by that tag in Cost Explorer, Budgets, and anomaly monitors.
Some transfer charges still appear under "No tag key". Shared infrastructure, such as one NAT gateway serving five teams, produces one charge with one tag value. Tags cannot split it. For shared resources you have two options. You can allocate the cost by a rule, such as each team's share of bytes measured in VPC Flow Logs, or you can give each team its own NAT gateway or VPC endpoint. The second option costs more in fixed hourly fees but gives clean attribution.
Tag governance matters as much as tagging. Enforce required tag keys with AWS Organizations tag policies or an infrastructure-as-code check, and report untagged spend as its own line each month. If the untagged share grows, attribution gets worse without any visible error.
Putting it together
A workable minimum for most accounts:
- One budget per major transfer usage type (NAT bytes, inter-AZ, internet egress), with an actual alert at 80% and a forecast alert at 100%.
- One service-level anomaly monitor with a daily subscription, plus an SNS-backed immediate subscription for a high absolute threshold.
- Three activated tag keys, with a monthly report on untagged spend.
- Alert recipients who can act. An alert sent to a shared finance mailbox is read late.
When an alert fires, follow the same sequence each time: open the anomaly or budget, identify the usage type, group by tag to find the owner, and use Flow Logs to find the specific flow.
Exercise
Your NAT gateway budget has a 500 USD limit and has never fired, yet the NAT line item on the invoice reached 900 USD last month. Give two likely causes related to how the budget was set up.
Show answer
First, the usage type filter may be wrong. A missing or incorrect region prefix, such as NatGateway-Bytes instead of USE1-NatGateway-Bytes, matches no cost, so the budget shows zero actual spend and never crosses a threshold. Second, the notification may be missing or misconfigured. For example, there may be no subscriber, or only an actual-spend alert was set and the month ended before billing data caught up. A forecast alert would likely have fired earlier. Checking the budget's current actual-spend figure against Cost Explorer shows which cause applies.
Exercise
A team's tag team=payments is on every EC2 instance, but Cost Explorer still shows no team values. What step was most likely skipped, and what happens to charges from a NAT gateway shared by several teams?
Show answer
The team tag key was probably never activated as a cost allocation tag in the Billing console. Tags on resources are not visible in cost data until activated. A shared NAT gateway produces one charge carrying one tag value (or none), so tags cannot split it among teams. Allocate it by a rule, such as each team's share of bytes from VPC Flow Logs, or give each team its own NAT gateway.