Sub topic 13
Using spot and preemptible capacity
This chapter assumes you know how on-demand pricing works, how to run AWS CLI commands, and how autoscaling groups are structured. Spot capacity is the deepest discount available for compute, and the price is that the provider can take the capacity back.
What spot capacity is
Cloud providers keep spare compute capacity so they can absorb demand spikes. They sell part of it at a steep discount, often 60 to 90 percent below on-demand. AWS calls this Spot Instances. Google Cloud calls it Spot VMs (formerly preemptible VMs), and Azure calls it Spot VMs.
The trade-off is interruption. When the provider needs the capacity back, it reclaims your instance. On AWS you get a two-minute warning. Google Cloud gives about 30 seconds. Spot is therefore a good fit for work that can be stopped and restarted, and a poor fit for work that cannot.
Which workloads fit
| Good fit | Poor fit |
|---|---|
| Batch processing and data pipelines | Single-instance databases |
| CI/CD build workers | Stateful services without replication |
| Stateless web tiers behind a load balancer | Jobs that cannot checkpoint and run for hours |
| Containers on a cluster with spare replicas | Anything with a hard availability guarantee on one node |
A useful test: if losing one instance at a random moment only costs you a few minutes of rework, the workload can use spot.
How interruption works
Your instance can read the notice from the instance metadata service. This command checks for a pending interruption. It returns a 404 response while none is scheduled.
TOKEN=$(curl -s -X PUT "http://169.254.169.254/latest/api/token" \
-H "X-aws-ec2-metadata-token-ttl-seconds: 60")
curl -s -H "X-aws-ec2-metadata-token: $TOKEN" \
http://169.254.169.254/latest/meta-data/spot/instance-actionA real handler would poll this every few seconds, then finish in-flight work, push a checkpoint to durable storage such as S3, and deregister from the load balancer.
Diversify across capacity pools
A capacity pool is one instance type in one Availability Zone. Each pool has its own spare supply and its own interruption rate. If you request only one type in one zone, a single shortage can interrupt everything.
Spread the request across many pools instead. An Auto Scaling group with a mixed instances policy does this. The file below keeps a small on-demand base and fills the rest with spot, using several similar instance types.
{
"AutoScalingGroupName": "web-workers",
"MinSize": 2,
"MaxSize": 20,
"VPCZoneIdentifier": "subnet-aaaa1111,subnet-bbbb2222",
"MixedInstancesPolicy": {
"LaunchTemplate": {
"LaunchTemplateSpecification": {
"LaunchTemplateName": "web-workers",
"Version": "$Latest"
},
"Overrides": [
{ "InstanceType": "m5.large" },
{ "InstanceType": "m5a.large" },
{ "InstanceType": "m6i.large" },
{ "InstanceType": "c5.large" }
]
},
"InstancesDistribution": {
"OnDemandBaseCapacity": 2,
"OnDemandPercentageAboveBaseCapacity": 0,
"SpotAllocationStrategy": "price-capacity-optimized"
}
}
}Create the group with aws autoscaling create-auto-scaling-group --cli-input-json file://asg.json. The price-capacity-optimized strategy favors pools that are both cheap and unlikely to be interrupted. Lowest-price alone tends to pick the pools that are most crowded.
Common errors
- No fallback. If spot capacity disappears and nothing replaces it, the service goes down. Keep an on-demand base, or let the group fall back.
- Keeping state on the instance. Local disks vanish at reclaim. Write checkpoints and results to S3 or a database.
- Ignoring the notice. Without a handler, you lose in-flight work for no reason.
- Setting a low maximum price. The default cap is the on-demand price, which is usually right. A lower cap only raises interruption odds.
- Counting on a discount that has shifted. Spot prices vary by pool and over time. Check current prices before you commit to a design.
Exercise
Exercise
A team runs a nightly video-encoding job on one m5.2xlarge spot instance in a single Availability Zone. The job takes four hours and loses all progress when interrupted. Name two changes that make this workload safer on spot.
Show answer
First, checkpoint progress to durable storage such as S3 (or split the job into small chunks), so an interruption only costs the current chunk. Second, diversify across several instance types and Availability Zones, for example with a mixed instances policy and price-capacity-optimized allocation, so one pool shortage does not stop the job. Handling the two-minute interruption notice is also a valid improvement.