Sub topic 10
Scheduling and autoscaling
This chapter assumes you know the basics of EC2 instances, Auto Scaling groups (ASGs), IAM roles, and the AWS CLI. It also assumes you have read the earlier chapters on cost drivers, idle resources, and rightsizing. Rightsizing makes each resource the correct size. Scheduling and autoscaling make sure the resource exists only while you need it.
Why capacity should follow demand
Compute is billed for the time a resource exists, not for how much work it does. A fleet sized for peak load costs the peak price all day. Two techniques address this:
- Scheduling changes capacity at known times. Examples are a development environment that is only used on weekdays, or a batch cluster that runs after midnight.
- Autoscaling changes capacity in response to measured load, such as CPU use or request count.
Use scheduling when the pattern is predictable and a person or a calendar can state it. Use autoscaling when load varies in ways you cannot predict. Most production fleets use both.
Scheduling: the arithmetic
A weekday-only schedule from 08:00 to 20:00 runs 12 hours × 5 days = 60 hours per week. A week has 168 hours, so the instance runs 36% of the time and the compute bill drops by about 64%. Switching off nights and weekends is often the largest saving available for non-production environments, and it needs no change to the application.
Some charges continue while a resource is stopped:
- EBS volumes attached to a stopped EC2 instance are still billed for their provisioned storage.
- Elastic IP addresses are billed at the public IPv4 rate whether or not they are attached to a running instance.
- Snapshots, load balancers, and NAT gateways continue to bill.
So a schedule that stops instances does not reduce these costs to zero. Delete or snapshot-and-delete resources that stay idle for long periods.
Stopping instances on a schedule
Amazon EventBridge Scheduler can call the EC2 API directly through a "universal target", so you do not need a Lambda function. First create an IAM role that trusts scheduler.amazonaws.com and allows ec2:StopInstances and ec2:StartInstances. Then write the target definition:
{
"Arn": "arn:aws:scheduler:::aws-sdk:ec2:stopInstances",
"RoleArn": "arn:aws:iam::123456789012:role/scheduler-ec2-control",
"Input": "{\"InstanceIds\":[\"i-0123456789abcdef0\"]}"
}Save it as stop-target.json and create the schedule:
aws scheduler create-schedule \
--name stop-dev-instances \
--schedule-expression "cron(0 20 ? * MON-FRI *)" \
--schedule-expression-timezone "Europe/London" \
--flexible-time-window Mode=OFF \
--target file://stop-target.jsonCreate a matching schedule with the startInstances ARN and a morning time. The account ID and instance ID above are placeholders.
Setting --schedule-expression-timezone matters. Without it the cron expression is evaluated in UTC, and your environment will stop an hour early or late whenever daylight saving time changes.
Scheduling an Auto Scaling group
For instances in an ASG, do not stop them directly. The group sees a stopped instance as unhealthy and replaces it. Change the group's capacity instead:
aws autoscaling put-scheduled-update-group-action \
--auto-scaling-group-name dev-web-asg \
--scheduled-action-name night-off \
--recurrence "0 20 * * 1-5" \
--time-zone "Europe/London" \
--min-size 0 --max-size 0 --desired-capacity 0
aws autoscaling put-scheduled-update-group-action \
--auto-scaling-group-name dev-web-asg \
--scheduled-action-name morning-on \
--recurrence "0 8 * * 1-5" \
--time-zone "Europe/London" \
--min-size 1 --max-size 4 --desired-capacity 1The first action terminates all instances in the group at 20:00. The second launches one instance at 08:00 and lets the group grow to four. Terminated instances are replaced by new ones, so anything stored only on an instance disk is lost. Keep state in EBS-backed data stores, S3, or a database.
Managing many resources with tags
Hard-coding instance IDs does not scale. A common pattern is to tag resources with a schedule name, for example Schedule=office-hours, and have the scheduler find resources by tag. AWS provides the Instance Scheduler on AWS solution for this. It uses the tagging strategy from the allocation chapter, so the same discipline that identifies owners also drives shutdowns.
What cannot be treated the same way
- RDS: a stopped DB instance is started again automatically after seven days, so a long shutdown needs a schedule that stops it again. Storage and backups remain billed.
- Instance store data: data on instance store volumes is lost when an instance stops.
- Public IP addresses: an instance without an Elastic IP gets a new public address when it restarts. Clients that depend on the old address will break.
- Warm-up time: an environment that starts at 08:00 is not usable at 08:00. Start it 15 to 30 minutes early if people depend on it.
Autoscaling: the control loop
An autoscaling group compares a metric with a target and changes the number of instances. The group has three capacity numbers: minimum, maximum, and desired. Policies move the desired capacity between the minimum and the maximum.
Choosing a policy type
| Policy type | How it works | Best for |
|---|---|---|
| Target tracking | You set a target for a metric, and AWS computes the changes | Most workloads, and the best default |
| Step scaling | You define alarm thresholds and the size of each step | Load where the size of the response should depend on the size of the breach |
| Scheduled | You set capacity at specific times | Predictable peaks and troughs |
| Predictive | AWS forecasts load from history and scales ahead of it | Cyclical load with slow-starting instances |
Target tracking is the simplest to run. This target keeps average CPU across the group near 50%:
{
"PredefinedMetricSpecification": {
"PredefinedMetricType": "ASGAverageCPUUtilization"
},
"TargetValue": 50.0
}Save it as cpu-target.json and attach it:
aws autoscaling put-scaling-policy \
--auto-scaling-group-name web-asg \
--policy-name cpu-50 \
--policy-type TargetTrackingScaling \
--target-tracking-configuration file://cpu-target.jsonTarget tracking scales out quickly and scales in cautiously. This is deliberate. Removing capacity too early causes a latency spike, while holding extra capacity for a few minutes costs little.
Picking the metric
CPU is easy to use and often wrong. Choose a metric that rises when the service is under pressure and falls when instances are added:
- For web services behind an Application Load Balancer, use
ALBRequestCountPerTarget. It reflects the work directly. - For queue workers, scale on backlog per instance, which is queue depth divided by the number of workers. This needs a custom metric.
- For memory-bound services, publish memory use through the CloudWatch agent, because EC2 does not report memory by default.
A metric that does not fall after you add capacity, such as a shared database's latency, causes the group to scale to its maximum without helping.
Settings that control cost and stability
- Minimum size: this is your cost floor. A minimum of 10 on an ASG that usually needs 3 wastes seven instances around the clock. Review it against real traffic.
- Maximum size: this is your cost ceiling. Set it to the largest fleet you are willing to pay for if something goes wrong, such as a retry storm or an attack. Combine it with a budget alert.
- Instance warm-up: the time before a new instance's metrics count toward the group average. Too short and the group over-scales, because new instances look idle while they boot.
- Scale-in protection and termination policy: protect instances doing long jobs, and choose which instances are removed first.
Combining scheduled and dynamic scaling
Scheduled actions change the minimum and maximum, while target tracking moves the desired capacity inside that range. For a service with a known weekday peak, you can raise the minimum at 07:30 so capacity is ready, then let target tracking handle the rest. Lower the minimum at night, and the policy scales the group in on its own. This is cheaper and safer than setting a fixed desired capacity, because the group can still react to unusual load.
Autoscaling beyond EC2
The same idea applies across AWS:
- ECS and EKS: scale tasks or pods (the service or horizontal pod autoscaler) and the underlying nodes (capacity providers or a node autoscaler). Scaling only one layer leaves idle nodes or pending pods.
- DynamoDB: on-demand tables scale per request with no capacity to manage. Provisioned tables use Application Auto Scaling to follow utilization.
- Lambda: it scales by itself and bills per invocation, so the cost control is concurrency limits and function memory settings.
Connecting to spot capacity
Autoscaling groups can mix on-demand and Spot instances. A common design keeps a small on-demand base for the minimum and fills the rest with Spot. The later chapter on spot capacity covers the interruption handling that makes this safe.
Common mistakes
- Stopping ASG instances directly instead of changing the group's capacity.
- Using cron expressions without a time zone and being surprised after a clock change.
- Setting the minimum to peak size, which removes most of the benefit of autoscaling.
- Scaling on CPU for a service limited by I/O, memory, or a downstream dependency.
- Forgetting that stopped resources still bill for storage and addresses.
- Having no schedule owner. Tag every scheduled resource with its team so that "why is my environment off?" has an answer.
Exercise
A development ASG normally needs 2 instances from 08:00 to 20:00 on weekdays and none at other times. Each instance costs $0.10 per hour. Compared with running 2 instances all week (168 hours), how much do you save per week with a schedule, and which two settings must the nighttime scheduled action change so the group really reaches zero instances?
Show answer
Always on: 2 × 168 × $0.10 = $33.60. Scheduled: 2 × 60 × $0.10 = $12.00, so the saving is $21.60 per week (about 64%). The night action must set both the minimum size and the desired capacity to 0. The maximum size is usually set to 0 as well so no policy can add instances. If only desired capacity is changed, the minimum size would make the group launch instances again.
Exercise
A queue-processing ASG scales on average CPU at a 60% target, but jobs spend most of their time waiting on a remote API, so CPU stays near 15% while the queue grows. What goes wrong, and what would you scale on instead?
Show answer
The group sees low CPU, so it never scales out, and the queue backlog keeps growing. Scale on backlog per instance, which is the queue length divided by the number of running instances, published as a custom CloudWatch metric and used as a target tracking target. This metric rises with the work waiting and falls when more workers are added.