Sub topic 15
Scaling a service with target tracking
This chapter shows how to scale an ECS service on Fargate automatically. It assumes you can already run a service (see the earlier chapters on services and load balancing) and that you are comfortable with the AWS CLI, JSON, and CloudWatch metrics.
How service auto scaling works
An ECS service keeps a fixed number of tasks, called the desired count. Service auto scaling changes that number for you. ECS does not do this itself. It uses Application Auto Scaling, a separate AWS service that can scale many resource types, including ECS services.
Three pieces work together:
- Scalable target: the service's desired count, registered with a minimum and maximum.
- Scaling policy: the rule that decides when to change the count.
- CloudWatch alarms: Application Auto Scaling creates and manages these for target tracking policies. They fire when the metric moves away from your target.
With target tracking, you pick a metric and a target value, such as "average CPU of 60 percent". Application Auto Scaling then adds or removes tasks to keep the metric near that value. It works like a thermostat. You set the temperature, and the system decides when to heat or cool.
Choosing a metric
ECS publishes two service metrics that target tracking can use directly, plus one for load balancers:
| Predefined metric | What it measures | Good fit |
|---|---|---|
| `ECSServiceAverageCPUUtilization` | Average CPU used across the service's tasks, as a percentage of the CPU reserved | CPU-bound services |
| `ECSServiceAverageMemoryUtilization` | Average memory used, as a percentage of the memory reserved | Services whose load shows up as memory use |
| `ALBRequestCountPerTarget` | Requests per task per minute from an Application Load Balancer | Web services where traffic drives load |
Pick the metric that best matches what limits your service. A web API that spends its time waiting on a database may show low CPU even when it is saturated. For that service, request count per target is a better signal. You can also use a custom CloudWatch metric, such as queue depth per task, through a customized metric specification.
Register the scalable target
First tell Application Auto Scaling which resource to manage and its limits.
aws application-autoscaling register-scalable-target \
--service-namespace ecs \
--scalable-dimension ecs:service:DesiredCount \
--resource-id service/demo/web \
--min-capacity 2 \
--max-capacity 10The resource ID has the form service/<cluster-name>/<service-name>. The minimum of 2 keeps the service available across two Availability Zones even at low load. The maximum of 10 caps cost and protects downstream systems such as databases from a sudden flood of connections.
Auto scaling never sets the count outside this range. If you set a desired count by hand outside the range, scaling brings it back inside the range on its next action.
Create the target tracking policy
The policy lives in a JSON file so that it is easy to review and keep in version control.
{
"TargetValue": 60.0,
"PredefinedMetricSpecification": {
"PredefinedMetricType": "ECSServiceAverageCPUUtilization"
},
"ScaleOutCooldown": 60,
"ScaleInCooldown": 120
}Save it as scaling-policy.json, then attach it.
aws application-autoscaling put-scaling-policy \
--policy-name cpu-target-60 \
--service-namespace ecs \
--scalable-dimension ecs:service:DesiredCount \
--resource-id service/demo/web \
--policy-type TargetTrackingScaling \
--target-tracking-scaling-policy-configuration file://scaling-policy.jsonThe command returns the policy ARN and the ARNs of the two alarms it created. You can see them in the CloudWatch console, with names that start with TargetTracking-. Do not edit or delete these alarms. Application Auto Scaling owns them and recreates or removes them as the policy changes.
What the cooldowns do
A cooldown is a waiting period after a scaling action. It stops the service from reacting again before the last change has had time to show up in the metrics.
ScaleOutCooldown: 60means that after adding tasks, the policy waits 60 seconds before it allows more scale-out from the same policy.ScaleInCooldown: 120means that after removing tasks, it waits 120 seconds before removing more.
Scale-out is short because slow reaction to rising load hurts users. Scale-in is longer because removing capacity too eagerly can cause a loop of removing and re-adding tasks. Target tracking is deliberately conservative about scale-in. It scales in only when the metric stays below the target long enough, so the service does not drop capacity on a brief dip.
Worked example: how the numbers move
Suppose the service has 2 tasks and average CPU rises to 90 percent against a 60 percent target. Target tracking estimates the capacity needed. Total load is about 2 × 90 = 180 CPU-percent units. To bring the average to 60, the service needs 180 / 60 = 3 tasks. The policy raises the desired count to 3.
When load falls so that the 3 tasks average 20 percent, the total is 60 units, which would fit in one task at 60 percent. Because the minimum is 2, the service stops at 2. The policy cannot go below the registered minimum.
Things to watch for
The metric has a delay
CloudWatch receives ECS metrics at one-minute intervals, and the alarm needs several data points to breach. A new task also needs time to pull its image, start, and pass health checks. In total, reacting to a spike can take several minutes. For sudden traffic, set a higher minimum or use a lower target value to leave headroom.
New tasks and health check grace period
A task that is still starting uses CPU while it boots. This can distort the average and trigger extra scale-out. Set a health check grace period on the service so the load balancer does not stop tasks that are still starting. The grace period is covered in the health checks chapter.
Deployments and scaling
During a rolling deployment, ECS temporarily runs more tasks than the desired count. Scaling continues to work during a deployment, but the extra tasks can skew the averages. A deployment that changes the task definition does not reset your policy or the registered range.
CPU measures reserved CPU
Utilization is measured against the CPU you reserved in the task definition. A task sized at 256 CPU units reaches 100 percent sooner than one sized at 1024 under the same work. If you change task sizing, revisit the target value.
Do not mix policies carelessly
You can attach several target tracking policies to one service, for example one for CPU and one for request count. Scale-out happens if any policy asks for it. Scale-in happens only when all policies agree. This is safe for availability, but it can keep the service larger than expected. Do not combine a target tracking policy with a hand-written step scaling policy on the same metric, because they can conflict.
Updating the desired count in your deployment tooling
If infrastructure code or a pipeline sets desiredCount on every deploy, it overrides auto scaling and resets the service to a fixed number. Leave the desired count unset after creation, or tell your tool to ignore changes to it.
Checking and removing scaling
Use these commands to see what scaling has done and why.
aws application-autoscaling describe-scaling-activities \
--service-namespace ecs \
--resource-id service/demo/web
aws application-autoscaling describe-scaling-policies \
--service-namespace ecs \
--resource-id service/demo/webEach activity shows the old and new desired count and a cause, such as an alarm breaching. To stop auto scaling, delete the policy and then deregister the target.
aws application-autoscaling delete-scaling-policy \
--policy-name cpu-target-60 \
--service-namespace ecs \
--scalable-dimension ecs:service:DesiredCount \
--resource-id service/demo/web
aws application-autoscaling deregister-scalable-target \
--service-namespace ecs \
--scalable-dimension ecs:service:DesiredCount \
--resource-id service/demo/webExercise
A service has 4 tasks averaging 30 percent CPU. The target is 60 percent, the minimum is 2, and the maximum is 10. Roughly how many tasks will target tracking settle on, and why might it take several minutes to get there?
Show answer
Total load is about 4 × 30 = 120 CPU-percent units. Dividing by the 60 percent target gives 2 tasks, which equals the minimum, so the service settles at 2. It takes several minutes because scale-in is conservative. The alarm needs the metric to stay below the target for a sustained period of one-minute data points, and the 120 second scale-in cooldown separates successive reductions.
Exercise
Your pipeline runs aws ecs update-service --desired-count 3 on every deploy, and the service keeps dropping back to 3 tasks after traffic spikes. What is happening, and how do you fix it?
Show answer
Each deploy overwrites the desired count that auto scaling set, so the service resets to 3 until the next scale-out. Remove the desired count from the deploy step, or configure the deployment tool to ignore changes to it, so Application Auto Scaling controls the count within the registered minimum and maximum.