Sub topic 9
Handling Spot interruptions
A Spot Instance costs less than On-Demand because it runs on spare EC2 capacity. AWS can take that capacity back, and you have to design for that. This chapter covers what an interruption is, what you get before it happens, and how to build a workload that survives it.
This chapter assumes you have launched EC2 instances from the console or CLI and know what the instance metadata service is. It also assumes you know what an Auto Scaling group does. Choosing between instance types for diversification comes in the next chapter.
What an interruption is
An interruption happens when EC2 reclaims a Spot Instance because it needs the capacity for other uses. Spot prices no longer drive this. You don't bid, and you pay the current Spot price. The cause is capacity: when a pool of spare capacity (one instance type in one Availability Zone) runs short, EC2 reclaims instances from it.
Three facts shape the design:
- Interruptions are per capacity pool. Instances in different pools are rarely reclaimed at the same moment.
- Frequency varies by pool. The Spot Instance Advisor reports interruption frequency in bands: under 5%, 5-10%, 10-15%, 15-20%, and over 20%. These are historical figures and give no guarantee.
- You get a warning, but it is short and best effort.
The signals you receive
EC2 gives you two signals. They differ in how early they arrive and how certain they are.
| Signal | Meaning | Lead time | Certainty |
|---|---|---|---|
| Rebalance recommendation | The instance is at elevated risk of interruption | Can arrive before the interruption notice, with no guaranteed lead time | Advisory only. The instance may never be interrupted |
| Interruption notice | EC2 will stop or terminate the instance | Two minutes | The action will happen |
Both signals reach you in two ways:
- Instance metadata. The paths
spot/rebalance-recommendationandspot/instance-actionreturn HTTP 404 until a signal exists. Poll them from inside the instance. - Amazon EventBridge. EC2 emits the events
EC2 Spot Instance Interruption WarningandEC2 Instance Rebalance Recommendation. Use these when something outside the instance, such as a Lambda function, should react.
Reading the notice from the instance
The two-minute notice appears at spot/instance-action. The response is JSON with the action and the time it will happen, for example {"action": "terminate", "time": "2026-11-26T18:20:00Z"}. Before the notice, the path returns 404.
The CLI example in the topic plan fetches an IMDSv2 token and then reads the path once. A real handler has to poll, because you don't know when the notice will arrive. Metadata tokens expire, so the loop below requests a fresh one on each pass. Polling every five seconds leaves most of the two minutes for cleanup.
#!/bin/bash
# spot-watcher.sh - run on the Spot Instance (as a systemd service or background job)
METADATA="http://169.254.169.254/latest"
while true; do
TOKEN=$(curl -s -X PUT "$METADATA/api/token" \
-H "X-aws-ec2-metadata-token-ttl-seconds: 60")
STATUS=$(curl -s -o /dev/null -w "%{http_code}" \
-H "X-aws-ec2-metadata-token: $TOKEN" \
"$METADATA/meta-data/spot/instance-action")
if [ "$STATUS" = "200" ]; then
echo "Interruption notice received at $(date -u +%FT%TZ)"
# Replace with your own drain logic:
/usr/local/bin/drain-and-checkpoint.sh
break
fi
sleep 5
doneThe drain-and-checkpoint.sh script is your own code. Keep it well inside two minutes, and make it safe to run when the instance dies halfway through.
What happens after the notice
When the notice expires, EC2 applies the interruption behavior you chose when you made the request. There are three behaviors.
| Behavior | What happens | Requirement |
|---|---|---|
| terminate | The instance is terminated. This is the default | Works for all request types |
| stop | The instance is stopped, and its EBS volumes persist | Persistent request, EBS-backed instance |
| hibernate | Memory is saved to the root volume, and the instance resumes later | Persistent request, hibernation-enabled instance |
The run-instances example in the topic plan uses "SpotInstanceType":"one-time". A one-time request is fulfilled once and then ends. If the instance is interrupted, nothing relaunches it. A persistent request is resubmitted after an interruption, so EC2 can start the instance again when capacity returns. Stop and hibernate are available only with persistent requests.
Stop and hibernate suit a single stateful machine, such as a developer workstation. Most production designs use terminate and replace the instance, because a stopped instance waits for capacity in the same pool that just ran short.
Design patterns that survive interruptions
The goal is to make losing an instance a routine event. Four practices cover most workloads.
Keep state off the instance
Anything that must outlive the instance belongs elsewhere. Put results in Amazon S3, a database, or a queue. Local disks hold only scratch data that can be rebuilt. If you use EBS volumes, remember that a terminated instance deletes volumes marked "delete on termination".
Make work resumable and idempotent
Idempotent means that running a task twice has the same effect as running it once. A queue consumer on Spot should:
- Take a message from the queue.
- Process it.
- Delete the message only after the result is stored.
If the instance dies in step 2, the message becomes visible again after its visibility timeout, and another worker picks it up. For long jobs, write checkpoints to S3 on a schedule, and have the drain script write a final one when the notice arrives.
Drain traffic on the notice
For web or API tiers, the drain script should deregister the instance from its load balancer target group. In-flight requests can then finish, and no new ones arrive. Set the target group's deregistration delay to a value under 120 seconds so it fits in the notice window.
Replace capacity automatically
Don't rely on a person to launch a replacement. Use an Auto Scaling group with a mixed instances policy, like the one in the topic plan. Two settings do the most work here:
- Capacity Rebalancing. When the group sees a rebalance recommendation, it launches a replacement Spot Instance first, then terminates the at-risk one after the replacement is healthy. This can avoid a capacity dip. It also means you may replace instances that would never have been interrupted, which costs some extra churn.
- A diversified instance list. The
Overrideslist in the policy gives EC2 several pools to draw from. When one pool runs short, the group can launch into another.
The following fragment adds Capacity Rebalancing when you create the group with the CLI. Set this on the group, not inside the mixed instances policy:
aws autoscaling create-auto-scaling-group \
--auto-scaling-group-name web-asg \
--min-size 2 --max-size 10 \
--vpc-zone-identifier "subnet-0aaa1111,subnet-0bbb2222,subnet-0ccc3333" \
--capacity-rebalance \
--mixed-instances-policy file://mixed-policy.jsonHere mixed-policy.json holds the policy from the topic plan: two On-Demand base instances, the rest Spot, and three instance types with price-capacity-optimized allocation. The subnet IDs are placeholders. Use subnets in different Availability Zones so the group spreads across more pools.
Gotchas and failure modes
- The notice is not guaranteed. In rare cases an instance can be reclaimed with no warning. Your design must cope with abrupt loss, so checkpoints during normal operation matter more than a perfect drain script.
- Two minutes is short. Don't start a 10-minute upload on notice. Do the expensive work continuously and use the notice only to finalize.
- IMDSv2 token handling. If your instances require IMDSv2, a poller that skips the token gets a 401 response, not a 404. A watcher that only checks for 200 will never fire, and you won't see an error. Test it.
- Correlated interruptions. Ten instances of the same type in the same Availability Zone sit in one pool. They can all be reclaimed together. Spread across types and zones.
- Hibernate and stop do not mean "free of interruption". A stopped Spot Instance is not running, so your service has lost that capacity until EC2 restarts it.
- Commitments don't cover Spot. Savings Plans and Reserved Instances apply to On-Demand usage. A Spot Instance is billed at the Spot price, so don't count it toward a commitment. This is why the policy above keeps the baseline On-Demand.
A checklist before production
- State lives in S3, a database, or a queue, never only on the instance.
- Tasks are idempotent and are retried automatically when a worker disappears.
- A poller or EventBridge rule reacts to the interruption notice.
- Load balancer deregistration delay fits inside two minutes.
- The Auto Scaling group uses several instance types and several Availability Zones, with Capacity Rebalancing on.
- You have run a fault-injection test and watched the replacement come up.
Exercise
Your queue-based image processor runs on Spot Instances. A worker receives an interruption notice while it is halfway through resizing an image. Which two design choices let the job complete without a person intervening, and why does deleting the queue message last matter?
Show answer
First, the work must be idempotent, so a second worker can redo the resize and get the same result. Second, the group must replace capacity automatically (an Auto Scaling group with several instance types and Capacity Rebalancing), so a worker exists to take the job. Deleting the message only after the result is stored means that if the instance dies midway, the message reappears after its visibility timeout and another worker processes it. Deleting it first would lose the job.
Exercise
A teammate's watcher script polls spot/instance-action without fetching an IMDSv2 token, and the instances require IMDSv2. It runs for weeks and never triggers a drain, even though some instances were interrupted. What is the likely cause, and how do you fix it?
Show answer
Without a token, the metadata service returns HTTP 401 instead of 404 or 200. The script only checks for 200, so it never sees the notice and never reports an error. Fix it by first requesting a token with a PUT to /latest/api/token and sending it in the X-aws-ec2-metadata-token header, as in the watcher script above. Then confirm it works by sending a test interruption with AWS Fault Injection Service.