EC2
07 / 08

Auto Scaling, Load Balancing & Cost Optimization

EC2: Auto Scaling, Load Balancing & Cost Optimization

Launch Templates

# Create launch template (replaces launch configurations)
aws ec2 create-launch-template \
  --launch-template-name my-app-lt \
  --version-description "v1" \
  --launch-template-data '{
    "ImageId": "ami-abc123",
    "InstanceType": "t3.medium",
    "IamInstanceProfile": {"Name": "my-app-role"},
    "SecurityGroupIds": ["sg-appserver"],
    "UserData": "'$(base64 -w 0 init.sh)'",
    "MetadataOptions": {"HttpTokens": "required"},
    "TagSpecifications": [{
      "ResourceType": "instance",
      "Tags": [{"Key": "Env", "Value": "prod"}]
    }]
  }'

Auto Scaling Groups (ASG)

# Create ASG
aws autoscaling create-auto-scaling-group \
  --auto-scaling-group-name my-app-asg \
  --launch-template LaunchTemplateName=my-app-lt,Version='$Latest' \
  --min-size 2 \
  --max-size 10 \
  --desired-capacity 3 \
  --vpc-zone-identifier "subnet-private-1a,subnet-private-1b,subnet-private-1c" \
  --target-group-arns arn:aws:elasticloadbalancing:...:targetgroup/my-tg/abc \
  --health-check-type ELB \
  --health-check-grace-period 120

# Target tracking scaling — keeps CPU at 50%
aws autoscaling put-scaling-policy \
  --auto-scaling-group-name my-app-asg \
  --policy-name cpu-target-tracking \
  --policy-type TargetTrackingScaling \
  --target-tracking-configuration '{
    "PredefinedMetricSpecification": {"PredefinedMetricType": "ASGAverageCPUUtilization"},
    "TargetValue": 50.0,
    "ScaleInCooldown": 300,
    "ScaleOutCooldown": 60
  }'

# Scheduled scaling (e.g., scale up before business hours)
aws autoscaling put-scheduled-update-group-action \
  --auto-scaling-group-name my-app-asg \
  --scheduled-action-name morning-scale-up \
  --recurrence "0 7 * * MON-FRI" \
  --desired-capacity 6 \
  --min-size 4

Application Load Balancer (ALB)

# Create ALB
aws elbv2 create-load-balancer \
  --name my-app-alb \
  --subnets subnet-public-1a subnet-public-1b \
  --security-groups sg-alb \
  --scheme internet-facing \
  --type application

# Create target group
aws elbv2 create-target-group \
  --name my-app-tg \
  --protocol HTTP --port 3000 \
  --vpc-id vpc-abc123 \
  --target-type instance \
  --health-check-path /health \
  --health-check-interval-seconds 30 \
  --healthy-threshold-count 2 \
  --unhealthy-threshold-count 3

# Create HTTPS listener with routing rules
aws elbv2 create-listener \
  --load-balancer-arn arn:aws:elasticloadbalancing:...:loadbalancer/app/my-app-alb/abc \
  --protocol HTTPS --port 443 \
  --certificates CertificateArn=arn:aws:acm:...:certificate/xyz \
  --default-actions Type=forward,TargetGroupArn=arn:...:targetgroup/my-app-tg/abc

Spot Instances

Spot Instances use spare EC2 capacity at up to 90% discount. AWS can reclaim them with 2-minute warning. Best for fault-tolerant workloads: batch jobs, CI/CD workers, ML training, video encoding.

# Launch Spot instance
aws ec2 run-instances \
  --instance-type c7g.xlarge \
  --instance-market-options '{"MarketType":"spot","SpotOptions":{"MaxPrice":"0.05","SpotInstanceType":"one-time"}}'

# Spot Fleet: mix of instance types for resilience
aws ec2 request-spot-fleet --spot-fleet-request-config '{
  "TargetCapacity": 10,
  "AllocationStrategy": "priceCapacityOptimized",
  "LaunchTemplateConfigs": [{
    "LaunchTemplateSpecification": {"LaunchTemplateName": "my-app-lt", "Version": "$Latest"},
    "Overrides": [
      {"InstanceType": "c7g.xlarge"},
      {"InstanceType": "c6g.xlarge"},
      {"InstanceType": "m7g.large"}
    ]
  }]
}'

Pricing Models

Model              | Discount | Commitment  | Use Case
-------------------|----------|-------------|------------------------------------
On-Demand          | 0%       | None        | Short-term, unpredictable workloads
Spot               | up to 90%| None        | Fault-tolerant batch/stateless
Reserved (1yr)     | ~40%     | 1 year      | Steady-state production servers
Reserved (3yr)     | ~60%     | 3 years     | Long-running stable workloads
Savings Plans      | ~40-66%  | 1 or 3 yr  | Flexible (any instance family)
Dedicated Host     | varies   | 1 or 3 yr  | License compliance (Oracle/Windows)

Keep your own version of these notes — editable, searchable, and organised by your stack.

Start free