Sub topic 8
Spot Instances: Spare Capacity at a Discount
This chapter assumes you know what an EC2 instance, an instance type, and an Availability Zone are. It also assumes you can run AWS CLI commands. It covers how Spot pricing works, what you give up in exchange for the discount, and how to build workloads that survive interruptions.
What a Spot Instance is
AWS keeps spare EC2 capacity in every Region. Spot Instances let you rent that spare capacity at a discount of up to 90% off the On-Demand price. A Spot Instance is the same hardware, AMI, and instance type as an On-Demand instance. The one difference is that EC2 can take it back when it needs the capacity.
Unlike commitment-based discounts, Spot requires no term and no hourly spend commitment. You pay for the risk of interruption instead of for a promise. That is why Spot suits some workloads very well and others not at all.
| Property | On-Demand | Spot |
|---|---|---|
| Price | Fixed list price | Varies by capacity pool, usually far below On-Demand |
| Commitment | None | None |
| Can AWS reclaim it? | No | Yes, with a two-minute notice |
| Capacity guaranteed? | Not without a reservation | No |
| Covered by Savings Plans or RIs? | Yes | No |
The last row matters for planning. Reserved Instances and Savings Plans never apply to Spot usage, because Spot is already discounted. Your commitments cover only the On-Demand part of your fleet.
How Spot pricing works
The Spot price is set by AWS and changes gradually, based on long-term supply and demand for each capacity pool. A capacity pool is a set of unused instances with the same instance type in the same Availability Zone (for example, c5.large in us-east-1a). Each pool has its own price.
Older material describes bidding, where the highest bid won. That model no longer applies. You do not need to bid, and prices do not spike the way they used to. Two practical points follow:
- You can set an optional maximum price. If you leave it unset, the cap is the On-Demand price, which is the recommended default.
- A low maximum price does not make the instance cheaper. You pay the current Spot price either way. A low cap only makes interruption more likely.
You can inspect recent prices for a pool with describe-spot-price-history:
aws ec2 describe-spot-price-history \
--instance-types c5.large \
--product-descriptions "Linux/UNIX" \
--max-items 10The output lists one price per Availability Zone over time. Comparing zones shows why a single pool is a fragile choice. The pools are priced and reclaimed independently.
Requesting a Spot Instance
The simplest way to get a Spot Instance is to add market options to run-instances. The AMI ID below is a placeholder, so replace it with one from your Region.
aws ec2 run-instances \
--image-id ami-0123456789abcdef0 \
--instance-type c5.large \
--count 1 \
--instance-market-options '{"MarketType":"spot","SpotOptions":{"SpotInstanceType":"one-time"}}'The request type controls what happens after an interruption:
- one-time: The request is fulfilled once. After the instance is interrupted, the request is closed and nothing is relaunched.
- persistent: EC2 resubmits the request after an interruption and launches a replacement when capacity is available.
You can also choose the interruption behavior: terminate (the default), stop, or hibernate. Stop and hibernate work only with persistent requests. They keep the EBS volumes, and hibernate also saves memory contents to disk.
For anything beyond a single instance, you rarely call run-instances by hand. You let an Auto Scaling group, EC2 Fleet, or Spot Fleet manage requests and replacements for you. Those services also give you diversification, covered below.
Handling interruptions
EC2 interrupts a Spot Instance when it needs the capacity back, or when the Spot price rises above a maximum price you set. The instance gets a notice two minutes before it is stopped, hibernated, or terminated. Two minutes is enough to finish a small unit of work, flush a buffer, deregister from a load balancer, or upload a checkpoint. It is not enough to finish a long job.
Your instance can read both signals from the instance metadata service. The spot/instance-action path returns HTTP 404 until a notice is issued, then returns the action and time. The following script polls it every five seconds and runs on the Spot Instance itself. It requests a fresh token each pass, so token expiry is never a problem.
#!/bin/bash
while true; do
TOKEN=$(curl -s -X PUT "http://169.254.169.254/latest/api/token" \
-H "X-aws-ec2-metadata-token-ttl-seconds: 60")
CODE=$(curl -s -o /dev/null -w "%{http_code}" \
-H "X-aws-ec2-metadata-token: $TOKEN" \
http://169.254.169.254/latest/meta-data/spot/instance-action)
if [ "$CODE" = "200" ]; then
echo "Interruption notice received. Draining and checkpointing."
# Replace this with your own shutdown logic.
break
fi
sleep 5
doneThe rebalance recommendation is an earlier, softer signal at events/recommendations/rebalance. It says the instance is at elevated risk of interruption. It may arrive before the two-minute notice, but it is not guaranteed to arrive first. Auto Scaling groups can use it to launch a replacement ahead of time (capacity rebalancing).
Gotchas with interruption handling
- The notice is best effort. In rare cases the instance can be reclaimed with less warning. Design for the loss of an instance at any moment, and treat the notice as a bonus.
- Local state is lost. Instance store data is gone after termination. Keep durable state in S3, EBS snapshots, a database, or a queue.
- Work must be idempotent. An interrupted job may run again elsewhere. Use queue visibility timeouts or job leases so unfinished work returns to the queue.
- Poll as a daemon. Run the check as a systemd service or sidecar, not by hand.
Diversification and allocation strategies
The most effective way to lower interruption rates is to avoid depending on one capacity pool. If your fleet is spread over many instance types and Availability Zones, a shortage in one pool affects only a fraction of your capacity. If AWS cannot fill one pool, it can fill another.
Practical ways to diversify:
- Use several instance types that are interchangeable for your workload, such as
c5.large,c5a.large, andm5.large. Include different generations and sizes with similar vCPU and memory. - Use all Availability Zones in the Region.
- Use attribute-based instance type selection, where you state vCPU and memory ranges and let EC2 pick the matching types.
- Check the Spot Instance Advisor for the historical interruption frequency of each type. It reports bands such as under 5% or over 20%.
- Check Spot placement scores to see how likely a Region or zone is to satisfy a request of your size.
The allocation strategy tells EC2 how to choose among your pools. For most workloads, use price-capacity-optimized. It picks pools that have the deepest spare capacity and so lower interruption risk, and among those it chooses the lowest price. Other strategies, such as lowest-price, concentrate your fleet in the cheapest pools, and those are often the ones that get reclaimed soonest.
The following mixed instances policy for an Auto Scaling group keeps two On-Demand instances as a baseline, fills the rest with Spot, and spreads Spot across three instance types:
{
"LaunchTemplate": {
"LaunchTemplateSpecification": {
"LaunchTemplateName": "web-template",
"Version": "$Latest"
},
"Overrides": [
{ "InstanceType": "c5.large" },
{ "InstanceType": "c5a.large" },
{ "InstanceType": "m5.large" }
]
},
"InstancesDistribution": {
"OnDemandBaseCapacity": 2,
"OnDemandPercentageAboveBaseCapacity": 0,
"SpotAllocationStrategy": "price-capacity-optimized"
}
}The two baseline On-Demand instances stay up even when Spot capacity disappears, and a Savings Plan or Reserved Instance can cover them. Setting OnDemandPercentageAboveBaseCapacity to 0 means every instance above the baseline is Spot.
Which workloads fit Spot
Spot fits workloads that are fault tolerant, flexible about instance type, and easy to retry:
- Stateless web or API tiers behind a load balancer, mixed with On-Demand baseline capacity
- Batch processing, rendering, and CI/CD build workers
- Containers and big data frameworks that tolerate losing nodes
- Test and development environments
It fits poorly when the work cannot be interrupted, when a very specific instance type is the only one that works, or when you need guaranteed capacity at a fixed time.
Exercise
A team runs a stateless image-resizing service on one Spot request for a single c5.large in one Availability Zone, with a maximum price set at 40% of the On-Demand price to "save money." Interruptions are frequent. Name three changes that would lower the interruption rate, and explain whether the low maximum price saves money.
Show answer
The low maximum price does not save money, because you always pay the current Spot price and never your maximum. It only raises the chance of interruption, so remove it and leave the default (the On-Demand price). To lower interruptions, (1) add several interchangeable instance types such as c5a.large and m5.large, (2) spread across all Availability Zones in the Region, and (3) use the price-capacity-optimized allocation strategy in an Auto Scaling group or EC2 Fleet, optionally with a small On-Demand baseline. Also poll the spot/instance-action metadata path so the service can drain requests within the two-minute notice.