Reading30 min read·Module 4High exam weight

Spot Instances & Interruption Handling

Key concepts

  • Spot pricing model

  • Spot Fleet strategies

  • Interruption handling

  • Spot blocks (deprecated)

  • Capacity-optimized allocation

Overview

EC2 Spot Instances allow you to use spare AWS compute capacity at discounts of up to 90% compared to On-Demand prices. This significant cost savings comes with the trade-off that AWS can reclaim (interrupt) these instances when capacity is needed elsewhere, providing only a 2-minute warning notification.

Core Concept

Spot Instances use spare EC2 capacity at steep discounts (up to 90%). The key trade-off is that instances can be interrupted with 2-minute notice when AWS needs the capacity back. Success with Spot requires designing for interruption: use multiple instance types/AZs, implement graceful shutdown, and leverage Spot Fleet with capacity-optimized allocation for best availability.

Exam Tip

When exam questions mention 'fault-tolerant', 'stateless', 'flexible start/stop times', 'batch processing', or 'can handle interruptions', Spot Instances are likely the answer. Look for workloads that can checkpoint progress or be distributed across multiple instances.

Key Concepts

Spot Pricing Model

Spot Instance Pricing Model
Figure 1: Spot Instance Pricing Dynamics

How Spot Pricing Works

Market-Based Pricing:

  • Spot prices are determined by supply and demand in each Spot pool
  • Each pool = instance type + Availability Zone combination
  • Prices fluctuate but changes are gradual (not auction-based since 2017)
  • You pay the current Spot price, NOT a bid price

Price Characteristics:

  • Typically 60-90% cheaper than On-Demand
  • Prices vary by instance type, AZ, and time
  • Larger instance types often have more stable pricing
  • Newer instance families may have more capacity

How You're Charged:

  • Pay the Spot price at the time of launch
  • Price adjusts each hour to current Spot rate
  • If Spot price exceeds your max price, instance is interrupted
  • No charge for partial hours if AWS interrupts

Setting Maximum Price:

  • You can set a maximum price (optional)
  • Default max price = On-Demand price
  • Instance runs while Spot price <= your max price
  • Setting max price = On-Demand gives you best chance of keeping instances

Spot Price History & Analysis

Viewing Price History:

  • Available through EC2 Console, CLI, or API
  • Shows 90-day price history per instance type and AZ
  • Helps identify stable vs volatile Spot pools
  • Use to select instance types with consistent pricing

Price Stability Factors:

  • Larger pools (popular instance types) tend to be more stable
  • Older generations may have less demand
  • Some AZs consistently have more capacity
  • Time of day/week can affect prices (less on weekends)

Best Practice:

  • Don't optimize purely for lowest price
  • Prioritize capacity availability over price
  • Use capacity-optimized allocation strategy
  • Diversify across multiple instance types and AZs
SHAWS CLI - Spot Price Commands
# View current Spot prices for specific instance types
aws ec2 describe-spot-price-history \
  --instance-types m5.large m5.xlarge c5.large c5.xlarge \
  --product-descriptions "Linux/UNIX" \
  --start-time $(date -u +%Y-%m-%dT%H:%M:%SZ)

# View 7-day Spot price history for m5.large
aws ec2 describe-spot-price-history \
  --instance-types m5.large \
  --product-descriptions "Linux/UNIX" \
  --start-time $(date -u -v-7d +%Y-%m-%dT%H:%M:%SZ) \
  --end-time $(date -u +%Y-%m-%dT%H:%M:%SZ)

# Filter by Availability Zone
aws ec2 describe-spot-price-history \
  --instance-types m5.large \
  --availability-zone us-east-1a \
  --product-descriptions "Linux/UNIX" \
  --start-time $(date -u +%Y-%m-%dT%H:%M:%SZ)

# Get lowest current Spot price across all AZs
aws ec2 describe-spot-price-history \
  --instance-types m5.large m5.xlarge m5.2xlarge \
  --product-descriptions "Linux/UNIX" \
  --start-time $(date -u +%Y-%m-%dT%H:%M:%SZ) \
  --query 'SpotPriceHistory | sort_by(@, &SpotPrice) | [0]'

Spot Fleet Strategies

Spot Fleet Architecture
Figure 2: Spot Fleet with Multiple Pools

Spot Fleet Overview

What is Spot Fleet?

  • Collection of Spot Instances (and optionally On-Demand)
  • Request capacity by number of instances OR vCPUs/memory
  • Automatically launches instances across multiple pools
  • Maintains target capacity by replacing interrupted instances

Fleet Configuration:

  • Define target capacity (instances, vCPUs, or custom weights)
  • Specify multiple launch specifications (instance types, AZs)
  • Choose allocation strategy
  • Set On-Demand base capacity (optional)
  • Configure instance weighting for heterogeneous fleets

Request Types: | Type | Behavior | |------|----------| | request | One-time request, no replacement of interrupted instances | | maintain | Maintains target capacity, replaces interrupted instances | | instant | Synchronous one-time request, returns results immediately |

On-Demand Base:

  • Specify number of On-Demand instances as baseline
  • Remaining capacity filled with Spot
  • Ensures minimum guaranteed capacity
  • Example: 2 On-Demand base + 8 Spot = 10 total, 2 guaranteed

Allocation Strategies

lowestPrice (Not Recommended)

  • Launches from pool with lowest Spot price
  • Maximum cost savings but highest interruption risk
  • All instances may be in one pool (no diversification)
  • AWS recommends against this strategy

capacityOptimized (Recommended)

  • Launches from pools with most available capacity
  • Lowest interruption probability
  • May not be the absolute cheapest
  • Best for workloads sensitive to interruption

capacityOptimizedPrioritized

  • Like capacityOptimized but respects your pool priority order
  • You rank instance types by preference
  • Fleet honors preferences while optimizing for capacity
  • Best when you prefer specific instance types

diversified

  • Distributes instances across all specified pools
  • Balanced approach to cost and interruption risk
  • Good for long-running workloads
  • Limits impact if one pool is reclaimed

priceCapacityOptimized (Newest, Recommended)

  • Considers both price AND capacity availability
  • Identifies pools with high capacity and low price
  • Best balance of cost savings and availability
  • AWS's recommended strategy for most workloads

Spot Fleet Allocation Strategies Comparison

StrategyOptimizes ForInterruption RiskCost SavingsBest For
lowestPricePrice onlyHighestMaximumNot recommended
capacityOptimizedCapacity onlyLowestGoodInterruption-sensitive workloads
priceCapacityOptimizedPrice + CapacityLowVery GoodMost workloads (recommended)
diversifiedSpread across poolsMediumGoodLong-running workloads
capacityOptimizedPrioritizedCapacity + Your priorityLowGoodWhen instance type preference matters
JSONSpot Fleet Request Configuration
{
  "SpotFleetRequestConfig": {
    "IamFleetRole": "arn:aws:iam::123456789012:role/spot-fleet-role",
    "TargetCapacity": 20,
    "OnDemandTargetCapacity": 2,
    "AllocationStrategy": "priceCapacityOptimized",
    "Type": "maintain",
    "ReplaceUnhealthyInstances": true,
    "TerminateInstancesWithExpiration": true,
    "LaunchTemplateConfigs": [
      {
        "LaunchTemplateSpecification": {
          "LaunchTemplateId": "lt-0123456789abcdef",
          "Version": "1"
        },
        "Overrides": [
          {
            "InstanceType": "m5.large",
            "SubnetId": "subnet-1a2b3c4d",
            "WeightedCapacity": 1
          },
          {
            "InstanceType": "m5.xlarge",
            "SubnetId": "subnet-1a2b3c4d",
            "WeightedCapacity": 2
          },
          {
            "InstanceType": "m5a.large",
            "SubnetId": "subnet-5e6f7g8h",
            "WeightedCapacity": 1
          },
          {
            "InstanceType": "m5a.xlarge",
            "SubnetId": "subnet-5e6f7g8h",
            "WeightedCapacity": 2
          },
          {
            "InstanceType": "m4.large",
            "SubnetId": "subnet-9i0j1k2l",
            "WeightedCapacity": 1
          }
        ]
      }
    ]
  }
}
SHAWS CLI - Spot Fleet Commands
# Request a Spot Fleet
aws ec2 request-spot-fleet \
  --spot-fleet-request-config file://spot-fleet-config.json

# List Spot Fleet requests
aws ec2 describe-spot-fleet-requests

# Get instances in a Spot Fleet
aws ec2 describe-spot-fleet-instances \
  --spot-fleet-request-id sfr-12345678-1234-1234-1234-123456789012

# Modify Spot Fleet target capacity
aws ec2 modify-spot-fleet-request \
  --spot-fleet-request-id sfr-12345678-1234-1234-1234-123456789012 \
  --target-capacity 30

# Cancel Spot Fleet (without terminating instances)
aws ec2 cancel-spot-fleet-requests \
  --spot-fleet-request-ids sfr-12345678-1234-1234-1234-123456789012 \
  --no-terminate-instances

# Cancel Spot Fleet and terminate instances
aws ec2 cancel-spot-fleet-requests \
  --spot-fleet-request-ids sfr-12345678-1234-1234-1234-123456789012 \
  --terminate-instances

Interruption Handling

Spot Instance Interruption Handling Flow
Figure 3: Handling Spot Instance Interruptions

Interruption Notice & Behavior

2-Minute Warning:

  • AWS provides exactly 2 minutes notice before interruption
  • Notice available via Instance Metadata Service
  • Also sent as EventBridge (CloudWatch Events) event
  • Time to gracefully shutdown, checkpoint, or drain connections

Checking Interruption Status:

# Check instance metadata for termination notice
curl http://169.254.169.254/latest/meta-data/spot/instance-action

# Response when interruption scheduled:
# {"action": "terminate", "time": "2024-01-15T12:34:56Z"}

Interruption Behaviors (configurable): | Behavior | Description | |----------|-------------| | terminate | Instance is terminated, EBS volumes deleted (default) | | stop | Instance is stopped, EBS root volume persisted | | hibernate | Instance is hibernated, memory saved to EBS |

Stop vs Hibernate:

  • Stop: Faster resume, no memory state
  • Hibernate: Preserves memory state, requires EBS-backed root volume
  • Both require enabling in launch configuration
  • Both allow instance to resume when capacity returns

Interruption Handling Strategies

Application-Level Handling:

  1. Poll Instance Metadata: Check every 5 seconds for termination notice
  2. Save State: Write checkpoints to S3, EFS, or database
  3. Drain Connections: De-register from load balancer, complete in-flight requests
  4. Signal Completion: Mark job progress for resumption

Infrastructure-Level Handling:

  1. Use Spot Fleet: Automatic replacement of interrupted instances
  2. EC2 Auto Scaling: Mixed instances policy replaces interrupted capacity
  3. EventBridge Rules: Trigger Lambda on interruption for custom logic
  4. Target Tracking: Maintain desired capacity automatically

Best Practices:

  • Design stateless applications when possible
  • Store state externally (S3, DynamoDB, EFS)
  • Use checkpointing for long-running jobs
  • Implement graceful shutdown handlers
  • Test interruption handling regularly
JSONEventBridge Rule for Spot Interruption
{
  "source": ["aws.ec2"],
  "detail-type": ["EC2 Spot Instance Interruption Warning"],
  "detail": {
    "instance-action": ["terminate", "stop", "hibernate"]
  }
}
SHAWS CLI - Interruption Handling Setup
# Create EventBridge rule for Spot interruption
aws events put-rule \
  --name "SpotInterruptionHandler" \
  --event-pattern '{
    "source": ["aws.ec2"],
    "detail-type": ["EC2 Spot Instance Interruption Warning"]
  }'

# Add Lambda target for interruption handling
aws events put-targets \
  --rule "SpotInterruptionHandler" \
  --targets '[{
    "Id": "SpotInterruptionLambda",
    "Arn": "arn:aws:lambda:us-east-1:123456789012:function:HandleSpotInterruption"
  }]'

# Create rebalance recommendation rule (proactive)
aws events put-rule \
  --name "SpotRebalanceRecommendation" \
  --event-pattern '{
    "source": ["aws.ec2"],
    "detail-type": ["EC2 Instance Rebalance Recommendation"]
  }'

Rebalance Recommendations

Proactive Capacity Management:

  • AWS sends rebalance recommendation BEFORE interruption
  • Provides more lead time than 2-minute interruption notice
  • Signal that instance MAY be interrupted soon
  • Opportunity to gracefully migrate workload

How It Works:

  1. AWS detects elevated interruption risk for your instance
  2. Sends EC2 Instance Rebalance Recommendation event
  3. You can proactively launch replacement capacity
  4. Gracefully drain and terminate at-risk instance

Auto Scaling Integration:

  • Enable Capacity Rebalancing in Auto Scaling group
  • ASG launches replacement before terminating at-risk instance
  • Ensures continuous capacity during rebalancing
  • Reduces interruption impact

When to Use:

  • Long-running workloads that need graceful transition
  • Stateful applications that need migration time
  • Workloads where 2 minutes is insufficient
  • Cost-optimized with reduced interruption impact

Capacity-Optimized Allocation

Deep Dive: Capacity-Optimized Strategies

Why Capacity Matters More Than Price:

  • Interrupted instance = zero work done
  • Lowest price pools often have lowest capacity
  • Re-launching to same pool may fail
  • Stable capacity = more completed work

capacityOptimized:

Priority: Available Capacity → Launch
  • Ignores price entirely
  • Chooses pool with most spare capacity
  • Lowest interruption rate
  • May pay more per hour

priceCapacityOptimized (Recommended):

Priority: High Capacity + Low Price → Launch
  • Balances capacity and cost
  • Identifies sweet spot of available + affordable
  • Best overall value for most workloads
  • Default recommendation for Spot Fleet

When to Use Each: | Use Case | Recommended Strategy | |----------|---------------------| | CI/CD pipelines | priceCapacityOptimized | | Big data processing | priceCapacityOptimized | | Containerized workloads | priceCapacityOptimized | | Rendering/Encoding | capacityOptimized | | Time-critical batch jobs | capacityOptimized | | Training ML models | capacityOptimized |

Spot Blocks (Deprecated)

Spot Blocks - Deprecated Feature

What Were Spot Blocks?:

  • Spot Instances with defined duration (1-6 hours)
  • Guaranteed no interruption during the block
  • Higher price than regular Spot (but less than On-Demand)
  • Launched with BlockDurationMinutes parameter

Current Status:

  • DEPRECATED as of December 2022
  • No longer available for new requests
  • AWS recommends using On-Demand for uninterruptible workloads
  • Or design for interruption with regular Spot

Exam Relevance:

  • May appear in older exam questions
  • Know that it existed but is now deprecated
  • Current answer: Use On-Demand for guaranteed duration
  • Or use Spot with proper interruption handling

Migration Path:

  • Short jobs (< 6 hours): Regular Spot with checkpointing
  • Guaranteed duration needed: On-Demand Instances
  • Cost optimization: Spot with fallback to On-Demand

Best Practices

  1. Diversify Instance Types: Use 10+ instance types across 3+ AZs to maximize availability
  2. Use priceCapacityOptimized: Best balance of cost savings and availability
  3. Implement Graceful Shutdown: Handle 2-minute warning with checkpointing and connection draining
  4. Set Up Rebalance Handling: Respond to rebalance recommendations proactively
  5. Use Instance Weighting: Enable heterogeneous fleets with appropriate capacity weights
  6. Combine with On-Demand Base: Use On-Demand for baseline, Spot for variable capacity
  7. Monitor Interruption Rates: Track interruptions by instance type to optimize selection
  8. Enable Capacity Rebalancing: Let Auto Scaling replace at-risk instances proactively

Common Exam Scenarios

Exam Scenario Decision Guide

ScenarioRecommended SolutionKey Reasoning
Batch image processing, can restart jobsSpot Fleet with priceCapacityOptimizedFault-tolerant workload, saves up to 90%
CI/CD pipeline buildsSpot Instances with checkpointingShort-lived, stateless, can retry on interruption
Web application with steady trafficAuto Scaling with mixed instances (On-Demand base + Spot)Baseline reliability with cost-optimized scaling
Big data processing on EMREMR with Spot for task nodesData on HDFS, task nodes can be replaced
Containerized microservices on ECSECS with Spot capacity providersContainers can be rescheduled on interruption
Video rendering farmSpot Fleet with capacityOptimizedLong jobs benefit from lowest interruption rate
ML model trainingSpot with checkpointing to S3Training can resume from checkpoint
Need guaranteed 4-hour runtimeOn-Demand Instances (Spot Blocks deprecated)Spot Blocks no longer available

Common Pitfalls

Using lowestPrice Allocation Strategy

The lowestPrice allocation strategy launches all instances from the cheapest pool, concentrating risk. If that pool is reclaimed, all instances are interrupted simultaneously. Always use priceCapacityOptimized or capacityOptimized instead.

Single Instance Type Selection

Specifying only one instance type limits available Spot pools. If that instance type has low capacity, you may not get instances or face frequent interruptions. Always specify multiple instance types (10+) and AZs (3+) for best availability.

Not Handling Interruptions

Spot Instances WILL be interrupted. Applications that don't handle the 2-minute warning lose all in-progress work. Implement metadata polling, checkpointing, and graceful shutdown. Test interruption handling with AWS Fault Injection Simulator.

Assuming Spot Blocks Are Available

Spot Blocks (defined duration Spot) were deprecated in December 2022. Exam questions may still reference them. The current solution for guaranteed duration is On-Demand Instances, not Spot Blocks.

Ignoring Rebalance Recommendations

AWS sends rebalance recommendations before interruption occurs, providing extra lead time. Not listening to these events means missing the opportunity for graceful migration. Enable Capacity Rebalancing in Auto Scaling and handle EventBridge rebalance events.

Quick Reference

Spot Instance Key Numbers

MetricValue
Maximum DiscountUp to 90% vs On-Demand
Interruption Notice2 minutes
Price History Available90 days
Recommended Instance Types10+ per fleet
Recommended AZs3+ per fleet

Allocation Strategy Selection

StrategyUse When
priceCapacityOptimizedDefault choice, most workloads
capacityOptimizedInterruption-sensitive, long-running jobs
diversifiedWant even distribution across pools
lowestPriceNever (not recommended)

Interruption Behavior Options

BehaviorData PersistenceResume Capability
terminateEBS deletedNo
stopEBS persistedYes (manual)
hibernateMemory + EBS persistedYes (with state)

CLI Quick Reference

# Check current Spot prices
aws ec2 describe-spot-price-history \
  --instance-types m5.large c5.large r5.large \
  --product-descriptions "Linux/UNIX" \
  --start-time $(date -u +%Y-%m-%dT%H:%M:%SZ)

# Request Spot Fleet
aws ec2 request-spot-fleet \
  --spot-fleet-request-config file://fleet-config.json

# Check for interruption notice (from instance)
curl -s http://169.254.169.254/latest/meta-data/spot/instance-action

# Describe Spot Fleet instances
aws ec2 describe-spot-fleet-instances \
  --spot-fleet-request-id sfr-xxx

# Modify fleet capacity
aws ec2 modify-spot-fleet-request \
  --spot-fleet-request-id sfr-xxx \
  --target-capacity 25

Instance Metadata Endpoints

EndpointPurpose
/latest/meta-data/spot/instance-actionCheck for interruption notice
/latest/meta-data/spot/termination-timeGet scheduled termination time

Test Your Knowledge

Q

A company runs a batch processing application that processes millions of images daily. Jobs can be interrupted and restarted from checkpoints stored in S3. The company wants to minimize compute costs. Which EC2 purchasing option is MOST cost-effective?

AOn-Demand Instances for flexibility
BStandard Reserved Instances for predictable capacity
CSpot Instances with priceCapacityOptimized allocation
DConvertible Reserved Instances for the ability to change instance types
Q

A solutions architect is configuring a Spot Fleet for a machine learning training workload. Training jobs take 4-6 hours and can checkpoint every 30 minutes. The jobs are time-sensitive and the team wants to minimize interruptions. Which allocation strategy should be used?

AlowestPrice for maximum cost savings
Bdiversified to spread across pools
CcapacityOptimized for lowest interruption probability
DpriceCapacityOptimized for balanced approach
Q

An application team needs to run a critical workload for exactly 4 hours without interruption. The workload cannot be checkpointed or restarted. A solutions architect suggests using Spot Blocks. What is the correct response?

AConfigure Spot Blocks with BlockDurationMinutes=240
BSpot Blocks are the perfect solution for guaranteed duration
CSpot Blocks are deprecated; use On-Demand Instances instead
DUse Spot Fleet with capacityOptimized for 4-hour guarantee
Q

A company is using EC2 Auto Scaling with a mixed instances policy that includes Spot Instances. They want to be notified before Spot interruptions occur so they can gracefully migrate workloads. What should they implement?

APoll instance metadata every 2 minutes
BConfigure EventBridge rule for EC2 Instance Rebalance Recommendation events
CEnable detailed CloudWatch monitoring on all instances
DSet up CloudTrail to log Spot interruption events

Further Reading

Related services

EC2 Spot