Guide · Amazon EC2 · Cost Optimization

EC2 Spot Instances for MCP Servers — Interruption Handling and Mixed Fleet Cost Optimization

EC2 Spot instances offer up to 90% discount over on-demand pricing by using spare AWS capacity. For MCP servers running behind an ALB, spot instances are a viable and cost-effective option — MCP servers are stateless (session state lives in DynamoDB or Redis, not in the Node.js process heap), and the ALB's connection draining handles interruptions gracefully. The key requirement: your server must handle the 2-minute interruption warning, drain active connections, and exit cleanly before AWS reclaims the instance. This guide covers the spot interruption notice mechanism (IMDS polling and EventBridge), the Mixed Instances Policy for Auto Scaling groups that blends spot and on-demand, interruption handler implementation in Node.js, instance diversification to minimize interruption frequency, and the total cost savings achievable on a typical MCP server fleet.

TL;DR

Use an Auto Scaling Group with a Mixed Instances Policy: set OnDemandBaseCapacity: 1 (always keep one on-demand instance), and fill the rest with spot. Use at least 5 instance type variants in your policy to reduce interruption risk. Poll the IMDS spot termination endpoint every 5 seconds, or use EventBridge for event-driven notification. On interruption, return 503 from /health immediately so the ALB stops routing traffic, then drain in-flight tool calls within the 2-minute window, then exit. Expected savings: 60–80% on spot instances in a 2:1 spot-to-on-demand fleet.

The 2-minute interruption warning

When AWS needs to reclaim a Spot instance, it sends a termination notice exactly 2 minutes before the instance is stopped. There are two ways to detect this notice:

Option 1: Poll the IMDS endpoint (simplest)

// Spot interruption poller — start this sidecar at process startup
// Polls every 5 seconds; total check window = 24 polls in 2 minutes

let spotInterruptionNoticed = false;

async function pollSpotInterruption(): Promise<void> {
  while (true) {
    try {
      // IMDSv2: get token first
      const tokenResp = await fetch('http://169.254.169.254/latest/api/token', {
        method: 'PUT',
        headers: { 'X-aws-ec2-metadata-token-ttl-seconds': '30' },
      });
      const token = await tokenResp.text();

      // Check for termination notice (HTTP 200 = interruption coming, HTTP 404 = no interruption)
      const resp = await fetch(
        'http://169.254.169.254/latest/meta-data/spot/termination-time',
        { headers: { 'X-aws-ec2-metadata-token': token } }
      );

      if (resp.status === 200) {
        const terminationTime = await resp.text(); // ISO 8601 timestamp
        console.log(`SPOT INTERRUPTION NOTICE: terminating at ${terminationTime}`);
        spotInterruptionNoticed = true;
        await handleSpotInterruption();
        break;
      }
      // HTTP 404 = no interruption pending, continue polling
    } catch (err) {
      // Network error on the metadata endpoint — not running on EC2 or IMDSv2 token issue
      // Fail silently in dev/non-EC2 environments
    }

    await new Promise(resolve => setTimeout(resolve, 5000)); // poll every 5s
  }
}

// Start the poller at application startup
pollSpotInterruption().catch(err => console.error('Spot poller error:', err));

Option 2: EventBridge (event-driven, no polling)

# Create an EventBridge rule for Spot interruption warnings
aws events put-rule \
  --name spot-interruption-handler \
  --event-pattern '{
    "source": ["aws.ec2"],
    "detail-type": ["EC2 Spot Instance Interruption Warning"]
  }' \
  --state ENABLED

# Target: Lambda that calls your MCP server's /drain endpoint
# or SNS topic that triggers an ASA lifecycle hook

The IMDS polling approach works without Lambda and without IAM changes — it runs entirely within the instance. EventBridge is better for fleet-wide automation (e.g., automatically starting a replacement instance before the old one terminates).

Interruption handler in Node.js

import { AutoScalingClient, CompleteLifecycleActionCommand } from '@aws-sdk/client-auto-scaling';

const asgClient = new AutoScalingClient({ region: process.env.AWS_REGION! });
let isShuttingDown = false;
let activeConnections = new Set<any>();

// Track active SSE connections
httpServer.on('connection', socket => {
  activeConnections.add(socket);
  socket.once('close', () => activeConnections.delete(socket));
});

async function handleSpotInterruption(): Promise<void> {
  console.log('Starting graceful shutdown for spot interruption');
  isShuttingDown = true;

  // 1. Immediately return 503 from /health — ALB stops routing new requests within seconds
  //    (ALB health check interval is 15s, unhealthy threshold 3 × 15s = 45s to deregister)
  //    But with connection draining, ALB stops sending NEW requests immediately after 503

  // 2. Close SSE streams gracefully — send a final message to clients so they can reconnect
  for (const socket of activeConnections) {
    try {
      // For SSE transport: send reconnect event before closing
      socket.write('event: reconnect\ndata: {"reason":"spot_interruption"}\n\n');
      socket.end();
    } catch {
      socket.destroy();
    }
  }

  // 3. Stop accepting new HTTP connections
  httpServer.close();

  // 4. Wait for in-flight tool calls to complete (max 90s — leaves 30s buffer before 2min deadline)
  const drainDeadline = Date.now() + 90_000;
  while (activeConnections.size > 0 && Date.now() < drainDeadline) {
    console.log(`Waiting for ${activeConnections.size} active connections to drain`);
    await new Promise(resolve => setTimeout(resolve, 2000));
  }

  // 5. Complete the Auto Scaling lifecycle hook (if using terminating lifecycle hook)
  try {
    const instanceId = await getInstanceIdFromIMDS();
    await asgClient.send(new CompleteLifecycleActionCommand({
      LifecycleHookName: 'drain-connections',
      AutoScalingGroupName: process.env.ASG_NAME!,
      LifecycleActionResult: 'CONTINUE',
      InstanceId: instanceId,
    }));
  } catch (err) {
    console.error('Failed to complete lifecycle action:', err);
    // Not fatal — AWS will terminate after heartbeat-timeout regardless
  }

  console.log('Graceful shutdown complete');
  process.exit(0);
}

// /health returns 503 during shutdown — ALB deregisters the instance
app.get('/health', (_req, res) => {
  if (isShuttingDown || spotInterruptionNoticed) {
    res.status(503).json({ status: 'shutting_down' });
  } else {
    res.json({ status: 'ok', uptime: process.uptime() });
  }
});

Mixed Instances Policy — on-demand base + spot scale

The Mixed Instances Policy in an Auto Scaling Group blends on-demand and spot instances. The recommended pattern for MCP servers is:

aws autoscaling create-auto-scaling-group \
  --auto-scaling-group-name mcp-server-asg \
  --min-size 2 \
  --max-size 10 \
  --desired-capacity 3 \
  --vpc-zone-identifier "subnet-aaa,subnet-bbb,subnet-ccc" \
  --target-group-arns arn:aws:elasticloadbalancing:...:targetgroup/mcp-server-tg/abc \
  --health-check-type ELB \
  --health-check-grace-period 120 \
  --default-instance-warmup 90 \
  --mixed-instances-policy '{
    "LaunchTemplate": {
      "LaunchTemplateSpecification": {
        "LaunchTemplateName": "mcp-server-lt",
        "Version": "$Latest"
      },
      "Overrides": [
        {"InstanceType": "m7g.large"},
        {"InstanceType": "m7g.xlarge"},
        {"InstanceType": "m6g.large"},
        {"InstanceType": "m6g.xlarge"},
        {"InstanceType": "c7g.large"},
        {"InstanceType": "r7g.medium"}
      ]
    },
    "InstancesDistribution": {
      "OnDemandBaseCapacity": 1,
      "OnDemandPercentageAboveBaseCapacity": 25,
      "SpotAllocationStrategy": "price-capacity-optimized"
    }
  }'

SpotAllocationStrategy: price-capacity-optimized — AWS selects the spot pool with the lowest price that also has enough spare capacity to minimize interruption risk. This strategy outperforms lowest-price (which chases cheapest pools regardless of capacity) for production workloads.

Interruption frequency by instance type pool

Not all Spot instance pools are equally volatile. Use the EC2 Spot Instance Advisor to find instance pools with <5% interruption frequency. For Graviton (ARM) pools in us-east-1 as of late 2026, m7g and c7g families typically have <5% interruption rates. x86 pools (m5, c5) tend to have higher interruption rates due to larger demand.

StrategyInterruption RiskCostRecommendation
Single instance type, single AZHigh — entire pool reclaimed togetherLowest priceDev/test only
3 instance types, 1 AZMedium — diversified pools, single AZLowNon-critical workloads
5+ instance types, 3 AZsLow — price-capacity-optimized picks stable poolsLow–mediumProduction MCP servers with ALB
Mixed: 1 on-demand base + spotMinimal — base capacity always availableMedium (25–50% on-demand)Production with availability SLA

Cost savings calculation

For a 4-instance fleet of m7g.large in us-east-1:

ConfigurationInstancesHourly costMonthly costSavings vs all on-demand
All on-demand4 × m7g.large$0.0906 × 4 = $0.362~$263Baseline
1 on-demand + 3 spot1 OD + 3 spot (~$0.027/hr)$0.0906 + 3 × $0.027 = $0.172~$125~52% savings
2 on-demand + 2 spot2 OD + 2 spot (~$0.027/hr)2 × $0.0906 + 2 × $0.027 = $0.235~$170~35% savings

Spot prices vary by pool and time. Graviton m7g spots typically run at 60–75% discount from on-demand. The savings compound further with Savings Plans on the on-demand portion (Compute Savings Plans apply on-demand rates before spot discount calculations).

MCP server suitability for Spot

MCP servers are well-suited for Spot instances when:

MCP servers that are not good candidates for Spot without additional engineering:

Common errors and fixes

Error / SymptomCauseFix
Spot requests consistently unfulfilledInsufficient capacity in selected pool; too few instance type variantsAdd more instance type overrides in Mixed Instances Policy; use price-capacity-optimized strategy; try different AZs
Connections dropped abruptly on interruptionServer exits without draining; deregistration_delay too shortImplement IMDS interruption poller + graceful shutdown; set deregistration_delay to 60s
All spot instances interrupted simultaneouslyAll instances in same pool (same type + AZ)Diversify across 5+ instance types in 3 AZs; use price-capacity-optimized
IMDS interruption poller returns 404 alwaysRunning on on-demand instance (expected) or non-EC2 environmentHTTP 404 = no interruption pending — this is correct behaviour; ignore in dev/on-demand environments
Lifecycle action fails (autoscaling:CompleteLifecycleAction AccessDenied)Instance role missing autoscaling:CompleteLifecycleAction permissionAdd permission to instance IAM role; scope Resource to the specific ASG ARN

Related guides