Search code examples
amazon-web-servicesamazon-ec2amazon-ecs

How to make ECS ASG scale down to 0 after a task finishes?


I have an ECS cluster with an EC2 ASG, min size 0, max size 1. When I run a task, ECS spins up a new EC2 instance to run the task, then it just leaves the EC2 instance running indefinitely. When I look under Infrastructure Capacity providers, I see the desired size remains at 1. Even if I terminate the EC2 instance, it spins up another EC2 instance that runs idle.

How can I make the ASG scale down to 0 after my task finishes?


Solution

  • It turns out the default policy that AWS applies is to scale up after 1 minute of current size < needed size and scale down after 15 minutes of needed size < current size. So the EC2 instances were not left running indefinitely as initially suspected, but rather for 15 minutes. The default policy ECSManagedAutoScalingPolicy-* is not editable, and if you turn it off it seems to break ECS, however you can supplement it.

    In my case, an extra 15 minutes of t3.micro doesn't cost much, but if you had a much more expensive instance, you can define your own CloudWatch alarm tracking CapacityProviderReservation < 100 and scale down faster, e.g. within 1 minute, using a Simple scaling policy alongside the default policy.