Sub topic 13
Using spot and preemptible capacity
This chapter assumes you know how on-demand and committed pricing work from the earlier chapters. It also assumes you can launch EC2 instances and use an Auto Scaling group (ASG), run AWS CLI commands, and read JSON. The examples use AWS. Google Cloud and Azure offer the same idea under other names.
What spot capacity is
Cloud providers keep spare compute capacity so they can absorb demand peaks. They sell that spare capacity at a steep discount, often 60 to 90 percent below on-demand. The catch is that the provider can take the capacity back when it needs it. Taking it back is called an interruption.
The same idea has different names across providers:
| Provider | Product | Warning before reclaim | Notes |
|---|---|---|---|
| AWS | EC2 Spot Instances | 2 minutes | No maximum lifetime |
| Google Cloud | Spot VMs (older: preemptible VMs) | About 30 seconds | Preemptible VMs ended after 24 hours. Spot VMs have no fixed limit. |
| Azure | Spot Virtual Machines | 30 seconds | Eviction policy is deallocate or delete |
Check each provider's current documentation before you design around these numbers, because warning times and rules change.
How the pricing and reclaim model works
Spot prices on AWS are not auctions. You no longer place bids. AWS sets a price per instance type and Availability Zone (AZ), and it changes slowly based on supply and demand. You pay the current spot price for as long as the instance runs. You can optionally set a maximum price. Leaving it unset, which caps you at the on-demand price, is the usual advice, because a low cap only causes extra interruptions.
Each instance type in each AZ is a separate capacity pool. Interruptions happen when a pool runs short, not when the price rises. This is the core design fact. If your fleet depends on one instance type in one AZ, one shortage stops your whole fleet. If it spreads across many pools, a shortage in one pool affects only a fraction of it.
The following sequence shows what a well-behaved workload sees during an interruption.
Which workloads fit
Spot works when your workload tolerates losing a node with little warning. Good fits:
- Batch jobs, data processing, and rendering that can restart or resume from checkpoints.
- CI/CD build agents, where a failed build is simply retried.
- Stateless web or API tiers behind a load balancer, mixed with some on-demand capacity.
- Containers on Kubernetes or Amazon ECS with several replicas.
- Training and hyperparameter search jobs that checkpoint regularly.
Poor fits:
- Single-instance databases and other stateful systems with no replica.
- Long jobs that cannot checkpoint and lose hours of work when interrupted.
- Anything with a strict availability target that depends on one node.
- Licensed software that is tied to specific hardware or instances.
A quick test: if losing any one node at a random moment is an inconvenience rather than an incident, spot is a candidate.
Step 1: Check prices and interruption risk
You can read recent spot prices for several instance types at once. Comparing across types and AZs shows which pools are cheap and stable.
aws ec2 describe-spot-price-history \
--instance-types m5.large m5a.large m6i.large \
--product-descriptions "Linux/UNIX" \
--start-time 2026-11-26T00:00:00Z \
--query 'SpotPriceHistory[].{Type:InstanceType,AZ:AvailabilityZone,Price:SpotPrice,Time:Timestamp}' \
--output tablePrice alone is a weak signal. The Spot Instance Advisor in the console shows an interruption frequency band for each type, such as "less than 5 percent" or "5 to 10 percent" per month. The Spot placement score API estimates how likely a request of a given size is to succeed in a Region. Use these to pick candidate pools, then diversify across them.
Step 2: Diversify across many pools
The most common mistake is asking for one instance type. Instead, list many interchangeable types and spread across all AZs in your VPC. Choose types with the same vCPU and memory, such as m5.large, m5a.large, m6i.large and m5n.large. Use the price-capacity-optimized allocation strategy. It picks pools that are both cheap and unlikely to be interrupted, and AWS recommends it for most workloads.
This Auto Scaling group configuration keeps one on-demand instance as a stable base and fills the rest with spot. Save it as asg.json. It assumes a launch template named batch-worker already exists, and you must replace the subnet IDs with your own.
{
"AutoScalingGroupName": "batch-workers",
"MinSize": 0,
"MaxSize": 20,
"DesiredCapacity": 4,
"VPCZoneIdentifier": "subnet-aaa111,subnet-bbb222,subnet-ccc333",
"CapacityRebalance": true,
"MixedInstancesPolicy": {
"LaunchTemplate": {
"LaunchTemplateSpecification": {
"LaunchTemplateName": "batch-worker",
"Version": "$Latest"
},
"Overrides": [
{ "InstanceType": "m5.large" },
{ "InstanceType": "m5a.large" },
{ "InstanceType": "m6i.large" },
{ "InstanceType": "m5n.large" }
]
},
"InstancesDistribution": {
"OnDemandBaseCapacity": 1,
"OnDemandPercentageAboveBaseCapacity": 0,
"SpotAllocationStrategy": "price-capacity-optimized"
}
}
}Create the group from the file:
aws autoscaling create-auto-scaling-group --cli-input-json file://asg.jsonTwo settings matter here. OnDemandBaseCapacity keeps a floor of reliable capacity, so a bad spot day degrades throughput instead of stopping the service. CapacityRebalance makes the group launch a replacement as soon as AWS signals that a running spot instance is at elevated risk. It then terminates the old one after the replacement is healthy, so you usually get a handover instead of a gap.
Step 3: Handle the interruption notice
Diversification reduces how often interruptions hit you. Handling the notice decides what each one costs. Your instance can read the notice from the instance metadata service. The endpoint returns HTTP 404 until an interruption is scheduled.
This Python script polls the metadata service every five seconds, using IMDSv2 session tokens, and calls a drain function when a notice appears. It uses only the standard library.
import json
import time
import urllib.error
import urllib.request
BASE = "http://169.254.169.254/latest"
def get_token() -> str:
req = urllib.request.Request(
f"{BASE}/api/token",
method="PUT",
headers={"X-aws-ec2-metadata-token-ttl-seconds": "300"},
)
with urllib.request.urlopen(req, timeout=2) as resp:
return resp.read().decode()
def interruption_notice(token: str):
req = urllib.request.Request(
f"{BASE}/meta-data/spot/instance-action",
headers={"X-aws-ec2-metadata-token": token},
)
try:
with urllib.request.urlopen(req, timeout=2) as resp:
return json.loads(resp.read().decode())
except urllib.error.HTTPError as err:
if err.code == 404:
return None # no interruption scheduled
raise
def drain() -> None:
# Replace with real work: deregister from the load balancer,
# stop taking jobs, and write a checkpoint to S3 or a database.
print("Draining and checkpointing")
while True:
notice = interruption_notice(get_token())
if notice:
print(f"Interruption scheduled: {notice}")
drain()
break
time.sleep(5)In production, many teams skip custom polling and use a managed handler instead. The AWS Node Termination Handler does this for Kubernetes, ECS has built-in spot draining, and an EventBridge rule on the "EC2 Spot Instance Interruption Warning" event can trigger a Lambda function. Whichever route you take, the checkpoint must go to storage outside the instance, because the local disk is lost on termination.
Common errors
- One instance type, one AZ. A single pool shortage takes down the whole fleet. Use at least four or five types across all AZs.
- No on-demand floor for critical paths. Keep a base of on-demand or committed capacity for components that must stay up.
- Treating two minutes as enough for everything. Drain, deregister, and checkpoint steps must finish well inside the window. Test with the AWS Fault Injection Service, which can trigger spot interruptions on purpose.
- Checkpointing too rarely. If a job checkpoints once an hour, an interruption can waste almost an hour. Pick an interval where lost work costs less than the checkpoint overhead.
- Expecting commitment discounts to apply. Savings Plans and Reserved Instances do not discount spot usage. Size your commitments for the stable baseline only, and run the variable layer on spot.
- Low maximum prices. A price cap below on-demand adds interruptions without a real saving, because you already pay the market price.
- Ignoring hidden costs. Replacement instances, repeated data downloads, and cross-AZ traffic during failover can eat part of the saving. Measure the cost per completed job, not just the hourly rate.
Where spot fits with other levers
Combine the pricing options by layer. Cover the steady baseline with commitment discounts, serve the predictable base and critical components with on-demand, and run elastic or fault-tolerant work on spot. Rightsizing and autoscaling still apply: a spot instance that is too large or sits idle wastes money at a discounted rate.
Exercise
A team runs 40 worker nodes of a single instance type, c5.xlarge, in one AZ, all as spot. They see occasional outages where nearly all workers disappear at once, even though the average interruption rate for the type is low. What is the cause, and what two changes would you make?
Show answer
The fleet depends on one capacity pool (one instance type in one AZ). When that pool runs short, AWS reclaims many instances at the same time, so a low average interruption rate does not help. Change 1: diversify by adding several interchangeable instance types (for example c5a.xlarge, c6i.xlarge, c5n.xlarge) and spreading across all AZs, using the price-capacity-optimized allocation strategy. Change 2: add an on-demand base capacity (OnDemandBaseCapacity) and enable Capacity Rebalancing so the group launches replacements early. Handling the two-minute notice with draining and checkpointing is a further improvement.
Exercise
You have a nightly job that runs for 3 hours and has no checkpointing. Spot would cut its compute bill sharply. Is it a good candidate as written, and what would you change first?
Show answer
Not as written. An interruption late in the run would throw away hours of work, and the repeated reruns could cost more than the discount saves. First add checkpointing to durable storage such as S3 (or split the job into smaller idempotent tasks), so a restart resumes instead of starting over. After that, run it on a diversified spot fleet.