AWS Cost Budgets & Anomaly Detection — Complete Guide
In this tutorial, you'll learn about AWS Cost Budgets & Anomaly Detection. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
AWS cost budgets and anomaly detection are the guardrails that prevent bill shock — setting budget thresholds, detecting unexpected spend spikes, and automating remediation before costs spiral out of control.
What You'll Learn
You'll create AWS Budgets with multi-level alerts, configure Cost Anomaly Detection monitors, build automated remediation with Lambda and SNS, and implement a cost governance framework that catches overruns in real time.
Why It Matters
A single misconfigured resource — an expensive GPU instance left running, a data transfer spike from a DDoS attack, or an orphaned EBS volume — can add tens of thousands of dollars to a monthly bill before anyone notices. Budget alerts and anomaly detection catch these within minutes. DodaTech's Durga Antivirus Pro uses automated anomaly alerts to detect crypto-mining attempts on build infrastructure within 15 minutes of deviation.
flowchart LR
A[Cost Explorer] --> B[Budgets]
A --> C[Anomaly Detection]
B --> D[50% / 80% / 90% / 100% Alerts]
C --> E[ML-Based Spend Monitors]
D --> F[SNS Notification]
E --> F
F --> G[Lambda Remediation]
G --> H[Auto-Stop / Tag / Notify]
style H fill:#ef4444,color:#fff
1. AWS Budgets
AWS Budgets let you set custom spending limits and receive alerts when you approach or exceed them.
# Create a monthly cost budget for EC2 with alerts
aws budgets create-budget \
--account-id 123456789012 \
--budget '{
"BudgetName": "ec2-monthly",
"BudgetLimit": {"Amount": 15000, "Unit": "USD"},
"TimeUnit": "MONTHLY",
"BudgetType": "COST",
"CostFilters": {"Service": ["AmazonEC2"]},
"CostTypes": {"IncludeTax": false, "IncludeSubscription": true}
}' \
--notifications-with-subscribers '[
{
"Notification": {"NotificationType": "ACTUAL", "ComparisonOperator": "GREATER_THAN", "Threshold": 50, "ThresholdType": "PERCENTAGE"},
"Subscribers": [{"SubscriptionType": "EMAIL", "Address": "team-lead"@example".com"}]
},
{
"Notification": {"NotificationType": "ACTUAL", "ComparisonOperator": "GREATER_THAN", "Threshold": 80, "ThresholdType": "PERCENTAGE"},
"Subscribers": [{"SubscriptionType": "EMAIL", "Address": "finops"@example".com"}]
},
{
"Notification": {"NotificationType": "ACTUAL", "ComparisonOperator": "GREATER_THAN", "Threshold": 100, "ThresholdType": "PERCENTAGE"},
"Subscribers": [{"SubscriptionType": "EMAIL", "Address": "cto"@example".com"}]
}
]'
# List all budgets
aws budgets describe-budgets --account-id 123456789012
Expected output (abbreviated):
{
"Budgets": [
{
"BudgetName": "ec2-monthly",
"BudgetLimit": {"Amount": 15000, "Unit": "USD"},
"CalculatedSpend": {"ActualSpend": {"Amount": 12340, "Unit": "USD"}},
"TimeUnit": "MONTHLY]
}
]
}
Budget Types
| Type | Scope | Use Case |
|---|---|---|
| Cost Budget | Total or filtered spend | Overall monthly cost cap |
| Usage Budget | Resource usage (GB, hours) | Prevent runaway data transfer |
| RI Utilization Budget | Reserved Instance usage % | Ensure RIs are fully used |
| Savings Plans Utilization | Savings Plan usage % | Track SP coverage |
2. AWS Cost Anomaly Detection
AWS Cost Anomaly Detection uses Machine Learning to detect unusual spend patterns without manual threshold setting.
# Create an anomaly detection monitor
aws ce create-anomaly-monitor \
--monitor-name "production-account" \
--monitor-type "CUSTOM" \
--monitor-specification '{
"MonitorArn": "",
"MonitorName": "production-account",
"MonitorType": "CUSTOM",
"MonitorDimension": "SERVICE"
}'
# Create an anomaly subscription
aws ce create-anomaly-subscription \
--subscription-name "finops-alerts" \
--frequency "DAILY" \
--monitor-arn-list '["arn:aws:ce::123456789012:anomalymonitor/production-account"]' \
--subscribers '[{"Type": "EMAIL", "Address": "finops"@example".com"}]' \
--threshold-expression '{
"Or": [
{"Dimension": {"Key": "ANOMALY_TOTAL_IMPACT_ABSOLUTE", "Values": ["100"]}},
{"Dimension": {"Key": "ANOMALY_TOTAL_IMPACT_PERCENTAGE", "Values": ["20"]}}
]
}'
# List detected anomalies
aws ce get-anomalies \
--date-interval Start=2026-06-01,End=2026-06-20 \
--max-results 10
Expected output:
{
"Anomalies": [
{
"AnomalyId": "a-123456",
"RootCauses": [{"Service": "AmazonEC2", "Region": "us-east-1"}],
"Impact": {"TotalImpact": 450.00, "TotalPercentage": 35.2},
"AnomalyScore": {"MaxScore": 85.3}
}
]
}
3. Automated Remediation with Lambda
Combine budgets, anomaly detection, and Lambda to auto-remediate cost spikes.
import boto3
import json
import os
ec2 = boto3.client('ec2')
sns = boto3.client('sns')
cloudwatch = boto3.client('cloudwatch')
def lambda_handler(event, context):
"""Auto-stop instances that triggered a budget breach."""
sns_topic = os.environ['SNS_TOPIC_ARN']
exempt_tags = os.environ.get('EXEMPT_TAGS', 'Production,Critical').split(',')
# Get all running instances
instances = ec2.describe_instances(
Filters=[{'Name': 'instance-state-name', 'Values': ['running']}]
)
stopped = []
for reservation in instances['Reservations']:
for instance in reservation['Instances']:
instance_id = instance['InstanceId']
# Skip exempt instances
tags = {t['Key']: t['Value'] for t in instance.get('Tags', [])}
if any(tag in exempt_tags for tag in tags.get('Environment', '').split(',')):
continue
# Check if instance has low utilization
metric = cloudwatch.get_metric_statistics(
Namespace='AWS/EC2',
MetricName='CPUUtilization',
Dimensions=[{'Name': 'InstanceId', 'Value': instance_id}],
StartTime=event['time'] - 86400,
EndTime=event['time'],
Period=3600,
Statistics=['Average']
)
avg_cpu = sum(p['Average'] for p in metric['Datapoints']) / max(len(metric['Datapoints']), 1)
if avg_cpu < 10:
ec2.stop_instances(InstanceIds=[instance_id])
stopped.append(instance_id)
if stopped:
sns.publish(
TopicArn=sns_topic,
Subject=f'Auto-stopped {len(stopped)} instances due to budget breach',
Message=json.dumps({'stopped_instances': stopped, 'budget_event': event})
)
return {'stopped': stopped}
Expected output:
{"stopped": ["i-0abcd1234", "i-0efgh5678"]}
4. Multi-Account Budget Strategy
For organizations with multiple AWS accounts, use AWS Organizations to enforce budgets centrally.
# Enable budget management from management account
aws organizations enable-aws-service-access \
--service-principal "budgets.amazonaws.com"
# Create a budget that applies to all member accounts
aws budgets create-budget \
--account-id 123456789012 \
--budget '{
"BudgetName": "organization-monthly",
"BudgetLimit": {"Amount": 100000, "Unit": "USD"},
"TimeUnit": "MONTHLY",
"BudgetType": "COST"
}' \
--notifications-with-subscribers '[
{
"Notification": {"NotificationType": "ACTUAL", "ComparisonOperator": "GREATER_THAN", "Threshold": 80, "ThresholdType": "PERCENTAGE"},
"Subscribers": [{"SubscriptionType": "EMAIL", "Address": "cloud-team"@example".com"}]
}
]'
Use AWS Cost Categories to group costs by department, project, or environment for per-team budget tracking.
Common Mistakes
Setting only a single alert threshold: One alert at 100% gives no time to react. Always set multiple thresholds at 50/80/90/100%.
No anomaly detection on data transfer: Data transfer costs can spike 10x overnight. Always create an anomaly monitor for Data Transfer service.
Budget without remediation: Alerts that go to an ignored email are useless. Pair every alert with an automated or manual remediation action.
Not budgeting by service: An overall $50k budget won't catch a single service running $20k over. Set per-service or per-account budgets.
Ignoring RI utilization budgets: Buying RIs is useless if you don't track utilization. Set utilization budgets to ensure you're using what you paid for.
Practice Questions
What is the difference between AWS Budgets and Cost Anomaly Detection? Answer: Budgets are threshold-based alerts you define manually. Anomaly Detection uses ML to automatically detect unusual spend patterns without predefined thresholds.
How do you implement multi-level alerting with AWS Budgets? Answer: Create a single budget with multiple notification subscribers at different thresholds — typically 50%, 80%, 90%, and 100% — each going to a different distribution list.
What Lambda remediation actions can reduce cost spikes automatically? Answer: Stop underutilized EC2 instances, delete orphaned EBS volumes, scale down RDS instances, disable non-production Auto Scaling groups, or tag resources for manual review.
Challenge
Design a cost governance system for a 10-account AWS organization: create per-account budgets at $10k with alerts at 50/80/90/100%, set up anomaly detection monitors for EC2 and Data Transfer, build a Lambda function that stops low-utilization instances during budget breaches, and configure an SNS notification hierarchy that escalates from team lead to CTO within 24 hours.
FAQ
What's Next
| Topic | Description |
|---|---|
| {{< card link="../aws-cost-optimization" title="AWS Cost Optimization" icon="currency-dollar" >}} | Full AWS cost optimization guide |
| {{< card link="../cost-anomaly-detection" title="Cost Anomaly Detection" icon="chart-bar" >}} | Deep dive into anomaly detection patterns |
Related topics: Cloud Cost Optimization, AWS, DevOps
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro