AWS Pricing Models and Cost Management
In this lesson, we'll explore how AWS pricing works and learn practical strategies to manage your cloud costs effectively. Understanding AWS pricing is crucial for building cost-efficient applications and avoiding unexpected bills.
Learning Goals:
- Understand the fundamental AWS pricing models
- Learn to use AWS pricing calculator and cost management tools
- Implement cost optimization strategies
- Set up billing alerts and budgets
AWS Pricing Fundamentals
AWS operates on a pay-as-you-go model, meaning you only pay for what you use. There are three main pricing models:
On-Demand Instances
Pay for compute capacity by the hour or second with no long-term commitments.
# Example: t3.micro instance in us-east-1
# $0.0104 per hour × 720 hours (30 days) = $7.49 monthly
echo "scale=2; 0.0104 * 720" | bc
Reserved Instances
Commit to 1 or 3-year terms for significant discounts (up to 75%).
# Compare 1-year reserved vs on-demand pricing
on_demand_hourly = 0.10
reserved_hourly = 0.05
hours_per_year = 8760
savings = (on_demand_hourly - reserved_hourly) * hours_per_year
print(f"Annual savings: ${savings:.2f}")
Spot Instances
Bid for unused EC2 capacity at up to 90% discount, but instances can be terminated with short notice.
AWS Cost Management Tools
AWS Pricing Calculator
Always use the AWS Pricing Calculator before launching new services. It provides accurate cost estimates based on your specific configuration and region.
AWS Cost Explorer
Visualize and analyze your AWS spending patterns with interactive charts and reports.
{
"TimePeriod": {
"Start": "2024-01-01",
"End": "2024-01-31"
},
"Granularity": "MONTHLY",
"Metrics": ["BlendedCost", "UsageQuantity"],
"GroupBy": [
{
"Type": "DIMENSION",
"Key": "SERVICE"
}
]
}
Cost Optimization Strategies
Right-Sizing Resources
def analyze_instance_utilization(cpu_utilization, memory_utilization):
"""Determine if instance needs resizing"""
if cpu_utilization < 20 and memory_utilization < 30:
return "DOWNGRADE - Underutilized"
elif cpu_utilization > 80 or memory_utilization > 85:
return "UPGRADE - Overutilized"
else:
return "OPTIMAL - Well sized"
# Example usage
print(analyze_instance_utilization(15, 25)) # DOWNGRADE - Underutilized
print(analyze_instance_utilization(90, 60)) # UPGRADE - Overutilized
Implementing Auto Scaling
- AWS CLI
- CloudFormation
aws autoscaling create-auto-scaling-group \
--auto-scaling-group-name my-asg \
--launch-configuration-name my-launch-config \
--min-size 2 \
--max-size 10 \
--desired-capacity 2 \
--availability-zones us-east-1a us-east-1b
Resources:
WebServerGroup:
Type: AWS::AutoScaling::AutoScalingGroup
Properties:
MinSize: 2
MaxSize: 10
DesiredCapacity: 2
LaunchConfigurationName: !Ref WebServerLaunchConfig
AvailabilityZones:
- us-east-1a
- us-east-1b
Setting Up Billing Alerts
CloudWatch Billing Alarm
import boto3
def create_billing_alarm(alarm_name, threshold_amount, email_address):
cloudwatch = boto3.client('cloudwatch')
sns = boto3.client('sns')
# Create SNS topic for notifications
topic_arn = sns.create_topic(Name='BillingAlerts')['TopicArn']
sns.subscribe(
TopicArn=topic_arn,
Protocol='email',
Endpoint=email_address
)
# Create billing alarm
cloudwatch.put_metric_alarm(
AlarmName=alarm_name,
AlarmDescription='Monthly billing alarm',
MetricName='EstimatedCharges',
Namespace='AWS/Billing',
Statistic='Maximum',
Dimensions=[
{
'Name': 'Currency',
'Value': 'USD'
}
],
Period=21600, # 6 hours
EvaluationPeriods=1,
Threshold=threshold_amount,
ComparisonOperator='GreaterThanThreshold',
AlarmActions=[topic_arn]
)
# Usage
create_billing_alarm('MonthlyBudget', 100.0, 'admin@example.com')
AWS Budgets
Billing alarms have a delay of up to 24 hours. For real-time budget tracking, use AWS Budgets instead.
Storage Cost Optimization
S3 Storage Classes
def calculate_s3_costs(storage_gb, requests_per_month):
"""Compare S3 storage class costs"""
standard_cost = (storage_gb * 0.023) + (requests_per_month * 0.0004)
infrequent_cost = (storage_gb * 0.0125) + (requests_per_month * 0.001)
glacier_cost = (storage_gb * 0.004) + (requests_per_month * 0.05)
return {
'STANDARD': round(standard_cost, 2),
'STANDARD_IA': round(infrequent_cost, 2),
'GLACIER': round(glacier_cost, 2)
}
# Example: 100GB storage, 1000 requests
costs = calculate_s3_costs(100, 1000)
print(f"Monthly costs: {costs}")
Common Pitfalls
- Forgotten Resources: Leaving EC2 instances running overnight or unused EBS volumes
- Over-Provisioning: Using larger instance types than needed "just to be safe"
- Ignoring Data Transfer Costs: Not accounting for cross-region or internet data transfer fees
- Manual Scaling: Not leveraging Auto Scaling for variable workloads
- No Monitoring: Failing to set up billing alerts until receiving a large bill
- Wrong Storage Classes: Using Standard S3 for archival data instead of Glacier
Summary
AWS pricing follows a pay-as-you-go model with options for cost savings through Reserved and Spot Instances. Effective cost management requires using tools like Cost Explorer, setting up budgets and alerts, right-sizing resources, and choosing appropriate storage classes. Regular cost reviews and automated scaling help maintain cost efficiency as your applications evolve.
Quiz
AWS Cost Optimization & Billing Fundamentals
What is the main advantage of Reserved Instances over On-Demand Instances?