Business Challenge
Eight posts in this series have been about when Auto Scaling replaces an instance and which instances it is allowed to touch. This one is about the remaining question: given that it has to terminate something, which one does it pick.
The answer is a termination policy, and the predefined names are confident —
OldestInstance, NewestInstance, OldestLaunchTemplate. Each
describes an ordering over the group. Neither the ordering nor the group is what actually gets
evaluated.
“When Amazon EC2 Auto Scaling terminates instances, it tries to maintain balance across the Availability Zones that are enabled for your Auto Scaling group. Maintaining Zonal balance takes precedence over the termination policy.”
Which would be unremarkable, except the documentation then states the consequence rather than leaving you to infer it:
“Amazon EC2 Auto Scaling always balances instances across Availability Zones first, regardless of which termination policy is used. As a result, you might encounter situations in which some newer instances are terminated before older instances.”
So OldestInstance does not terminate the oldest instance in the group. It terminates
the oldest instance in the zone Auto Scaling picked, and the zone is picked by instance
count. The two named causes are a recently added Availability Zone, and one zone simply holding
more instances than the others.
That reframes every policy name on the page. They are not orderings over a group; they are tie-breaks within a zone.
“Amazon EC2 Auto Scaling applies termination policies only to instances that are not considered unhealthy by the Auto Scaling group. As a result, instances marked as unhealthy by Auto Scaling health checks will bypass termination policy evaluation.”
This is the same boundary the previous post found for scale-in protection, drawn in the same place. Health is not a criterion the policy weighs; it is a gate in front of the policy. An unhealthy instance is terminated because it is unhealthy, and no policy and no protection changes that.
Put together with challenge 1, the policy's actual input is: healthy, unprotected instances, in one Availability Zone. The zone selection says so explicitly — “it first identifies which Availability Zone (or Zones) has the most instances and at least one instance that is not protected from scale in” — so a zone with nothing terminable in it is not even a candidate.
“The maximum run time for your Lambda function is two seconds (2000 milliseconds). As a best practice, you should set the timeout value of your Lambda function based on your expected run time. Lambda functions have a default timeout of three seconds, but this can be decreased.”
One sentence states a budget of two seconds and the next states that the platform's default is three. A function created with the defaults is configured to be allowed to run a second longer than Auto Scaling will wait for it.
And the overrun does not fail closed in the usual sense: “If your runtime exceeds the 2-second limit, any scale in action will be on hold until the runtime falls below this threshold.”
Not an error, not a fallback to the default policy. Scale in stops happening, and keeps not happening, until the function gets faster. For a group under a scaling policy that is a cost problem that reports itself only as capacity that never comes down.
Architecture
What the default policy evaluates, in order
Once the zone is chosen, the default policy looks for outdated configuration first, in a fixed sequence:
| Step | Looks for |
|---|---|
| 1 | Instances launched with a launch configuration |
| 2 | Instances launched using a different launch template than the current one |
| 3 | Instances using the oldest version of the current launch template |
| 4 | Instances closest to the next billing hour |
Steps 1 to 3 are a single criterion with internal priority, not three criteria. The ordering is sensible: a launch configuration is the most outdated thing an instance can have been built from, a foreign launch template is next, and an old version of the right template is last.
Step 4 is the interesting one, because AWS undercuts it in the same paragraph: “However, most EC2 usage is now billed per second, so this optimization provides less benefit.” The default policy's final tie-break optimises for a billing model most usage has left behind, and it is kept because changing a default changes behaviour for every group that never chose it.
Below that there is no further criterion: “If multiple instances are equally close, terminate one at random.” Randomness is the floor, which is the right answer — an arbitrary but documented tie-break beats an undocumented one that people start depending on.
A mixed instances group evaluates two things first
The default policy is not one algorithm. On a mixed instances group, two steps are inserted ahead of everything above.
First the purchase option: “it first identifies which purchase option (Spot or On-Demand) should be terminated based on the settings of the group”, so the group trends toward its specified Spot and On-Demand ratio over time. Then the zone, as before. Then, within the identified purchase option and zone, alignment with the allocation strategy is checked before outdated configuration.
So the full chain on a mixed group is: purchase option, then zone, then allocation strategy, then outdated configuration, then billing hour, then random. Six levels, of which the policy you named governs the fourth onwards.
The seven predefined policies
| Policy | What it is for |
|---|---|
Default | The chain above |
AllocationStrategy | Rebalancing onto your current allocation strategy after preferred instance types change |
OldestLaunchTemplate | Phasing out a previous configuration: noncurrent templates first, then the oldest version of the current one |
OldestLaunchConfiguration | The same, for groups still on launch configurations |
ClosestToNextInstanceHour | Maximising hourly-billed instances |
NewestInstance | Testing a new configuration without keeping it |
OldestInstance | Gradually moving to a new instance type |
NewestInstance has the most specific documented purpose of the seven:
“Terminate the newest instance in the group. This policy is useful when you're testing a
new launch configuration but don't want to keep it in production.” It is a policy for a
situation rather than a standing preference, which is worth remembering before leaving it set.
Lists have ordering rules
Policies combine into a list, evaluated in sequence, with two hard constraints:
“If you use the Default policy, it must be the last policy in the list.” And a
custom Lambda policy must be first. Both make sense — Default is a complete chain
ending in randomness, so nothing after it could ever run, and a custom policy is meant to narrow the
candidate set that the remaining policies then order.
One more console-versus-API divergence, which this series has now found in five separate features: “You can't change the termination policy when you initially create an Auto Scaling group in the Amazon EC2 Auto Scaling console. The default termination policy is used automatically.”
What a custom policy actually receives
The Lambda gets a payload naming the group, a CapacityToTerminate breakdown per zone
and purchase option, an Instances list that Auto Scaling suggests, and a
Cause of SCALE_IN, INSTANCE_REFRESH,
MAX_INSTANCE_LIFETIME or REBALANCE.
That cause list is worth pausing on. The same function is consulted for the instance refresh of post #124 and the maximum instance lifetime of post #126 — so a custom termination policy is a hook into every replacement path in this series, not only into scale in.
It returns a list of instance IDs, and may return a different set than it was offered, or an empty list. The important limits on what that achieves:
- “Returning an instance first in the response data does not guarantee its termination.” Return more than are needed and the remaining policies in the list break the tie.
- “If your Lambda function returns no instances, this does not automatically prevent all termination. Amazon EC2 Auto Scaling will still terminate instances that are considered unhealthy by the Auto Scaling health checks, regardless of termination policies.”
-
“The number of instances provided in the input data is limited to 30,000
instances.” Beyond that the payload carries
"HasMoreInstances": true.
The retry behaviour is the part to design for
Returning an empty list is a legitimate answer meaning not yet, and the retry policy differs by cause. For scale in, Auto Scaling keeps trying as long as desired capacity is below current capacity — indefinitely, in other words. For an instance refresh: “For instance refresh-based terminations, it keeps trying for an hour. After that, if it continues to fail to terminate any instances, the instance refresh operation fails.”
Which produces the warning the page gives in as many words: “Because your function is retried repeatedly, make sure to test and fix any permanent errors in your code before using a Lambda function as a custom termination policy.” A bug here is not one failed invocation; it is an invocation loop for as long as the group wants to shrink.
Two limits that will fail a deployment
“You cannot use a qualified ARN with the” $LATEST suffix —
attempting it is an error, not a warning. Use an unqualified ARN, or a version or alias. And
“Cross-account Lambda functions aren't supported. The Lambda function used as a custom
termination policy must be in the same AWS account as the Auto Scaling group.” Both are
the kind of thing discovered at terraform apply rather than at design time.
Why This Architecture Holds Up
Zonal balance outranking the policy is the correct priority
A group that honoured OldestInstance strictly would drift into zonal imbalance, and
zonal imbalance is an availability risk while terminating a slightly newer instance is not. AWS chose
the property that protects the workload over the property the operator named, and then documented
that it had done so. The design is right; the policy names are what mislead, because each one
describes its tie-break as though it were the whole decision.
Health as a gate rather than a criterion
Folding health into the policy would make it weighable — and therefore overridable by a policy or a protection setting. Keeping it in front means an unhealthy instance is always terminable, which is the one behaviour you never want configurable. It costs you the ability to say keep this broken instance for debugging, and that is the right thing to lose.
Putting scale in on hold rather than falling back
When a custom policy overruns its two seconds, Auto Scaling could ignore it and apply the default policy. Holding instead is the safer reading of intent: the function exists because the group's owner has a rule about what may be terminated, and silently terminating by a different rule would break the thing the function was written to guarantee. It is the right call and it is a failure mode that needs an alarm, because its symptom is an absence.
Key Architecture Decisions
| Decision | Take | Why |
|---|---|---|
Relying on OldestInstance to retire the oldest instance |
Do not, across zones | Zonal balance is evaluated first and can pick a newer one |
| Keeping a broken instance for investigation | Detach it from the group | Unhealthy instances bypass policies and protection alike |
| A custom Lambda policy's timeout | Set it under 2 seconds explicitly | Lambda's own default is 3, which is longer than the budget |
| A group whose capacity stops coming down | Check the custom policy's duration first | An overrun holds scale in rather than erroring |
A policy list including Default |
Put it last; nothing after it runs | It is a complete chain ending in a random choice |
| Referencing the Lambda | Unqualified ARN, or a version or alias | A qualified ARN with $LATEST is rejected |
| Mixed instances groups | Reason about purchase option before anything else | Spot versus On-Demand is chosen before the zone |
| Setting a policy at group creation | Use the API, or edit afterwards | The console cannot set one at creation time |
The audit worth running
- Every group with a non-default termination policy, against its zonal distribution — an imbalanced group is one where the policy is not deciding much.
- Every custom termination policy Lambda, for a configured timeout above two seconds.
- Every group with a custom policy, for a scaling policy that has been asking for scale in without getting it.
-
Every policy list, for a
Defaultentry that is not last and therefore makes everything after it unreachable.
Closing Thought
That is nine posts on Amazon EC2 Auto Scaling, and the same shape has appeared in every one. A
setting has a name that states an outcome; the documentation describes a mechanism that produces
that outcome under conditions; and the gap between them is where the operational surprises live. The
health check grace period defaults differently by door. Rollback is unavailable on
$Latest. A maintenance policy's floor has three exceptions. A maximum lifetime does not
apply to a protected instance. Scale-in protection does not protect what is already running. And a
termination policy does not order the group.
None of those is a defect. Every one is a documented, defensible design decision, and in most cases AWS states the consequence itself — this post's central finding is a sentence AWS wrote, not one I inferred. What they have in common is that the name is a summary and the behaviour is in the page, and a design reasoned from the name will be wrong in a way nothing reports.
The finding I would act on is zonal balance. It is the only one in the series that silently inverts
the thing you asked for: you select OldestInstance to retire old instances, and in an
imbalanced group it will terminate newer ones. Check the distribution before trusting the policy.
Official AWS Reference
- Configure termination policies for Amazon EC2 Auto Scaling — that zonal balance takes precedence over the termination policy and that newer instances may therefore be terminated before older ones, that unhealthy instances bypass policy evaluation, how the zone is selected and that it must contain at least one unprotected instance, the default policy's outdated-configuration sequence and billing-hour tie-break, the note that per-second billing makes that tie-break less beneficial, the random choice among equals, the extra purchase-option and allocation-strategy steps for mixed instances groups, and the definitions of all seven predefined policies
- Create a custom termination policy with Lambda — the input payload and its
CapacityToTerminate,InstancesandCausefields, the response shape and the empty-list case, that returning an instance first does not guarantee its termination, that returning nothing does not prevent unhealthy instances being terminated, the retry behaviour per cause and the one-hour instance refresh limit, the warning that the function is retried repeatedly, the two-second maximum run time against Lambda's three-second default and that an overrun holds scale in, the 30,000-instance input cap andHasMoreInstances, the single-function and first-in-list rules, the$LATESTrejection, and that cross-account functions are unsupported - Change the termination policy for an Auto Scaling group — that the console cannot set a termination policy at group creation, that policies can be combined into an ordered list, and the two ordering rules:
Defaultlast, a custom policy first - Allocation strategies for Amazon EC2 Auto Scaling — further reading on the strategy the
AllocationStrategypolicy rebalances toward; no claims in this post are drawn from it - Use instance scale-in protection to control instance termination — further reading, covered in the previous post, on the protection that removes an instance from the candidate set; no claims in this post are drawn from it
Comments