Guide · Amazon EC2 · Auto Scaling

EC2 Auto Scaling Groups for MCP Servers — Launch Templates, Lifecycle Hooks, and Rolling Deploys

An EC2 Auto Scaling Group (ASG) keeps a fleet of MCP server instances at a desired capacity, automatically replaces unhealthy instances, scales out under load, and enables zero-downtime code deploys via instance refresh. Compared to running a single EC2 instance, an ASG adds a small operational overhead but eliminates single-instance failures as an outage cause, makes horizontal scaling automatic, and turns code deploys into a first-class operation. This guide covers creating Launch Templates with user data, associating an ASG with an ALB target group, configuring target tracking scaling policies with the right warmup and cooldown settings, using lifecycle hooks to drain connections before termination, and running rolling instance refresh deployments.

TL;DR

Use a Launch Template (not a deprecated Launch Configuration) with your user data bootstrap script. Associate the ASG with an ALB Target Group — the ALB health check gates traffic, and DeregistrationDelay drains connections before termination. Set a target tracking scaling policy on ALBRequestCountPerTarget at ~50–80 requests per minute per instance for typical MCP servers. Add a Terminating lifecycle hook to give your server time to drain SSE connections before EC2 terminates it. Use instance refresh for zero-downtime code deploys.

Launch Template

Launch Templates replace deprecated Launch Configurations. They version-control your instance configuration and support mixed instance types (required for Spot instances).

# Create Launch Template referencing your bootstrap script
aws ec2 create-launch-template \
  --launch-template-name mcp-server-lt \
  --version-description "initial" \
  --launch-template-data '{
    "ImageId": "ami-0abcdef1234567890",
    "InstanceType": "m7g.large",
    "IamInstanceProfile": { "Name": "mcp-server-profile" },
    "SecurityGroupIds": ["sg-mcp-server"],
    "MetadataOptions": {
      "HttpTokens": "required",
      "HttpEndpoint": "enabled",
      "HttpPutResponseHopLimit": 1
    },
    "BlockDeviceMappings": [{
      "DeviceName": "/dev/xvda",
      "Ebs": {
        "VolumeSize": 30,
        "VolumeType": "gp3",
        "Encrypted": true,
        "DeleteOnTermination": true
      }
    }],
    "TagSpecifications": [{
      "ResourceType": "instance",
      "Tags": [{"Key": "Name", "Value": "mcp-server"}, {"Key": "Service", "Value": "mcp"}]
    }]
  }' \
  --user-data "$(base64 -w 0 bootstrap.sh)"

# Update user data for a new version (code deploy)
aws ec2 create-launch-template-version \
  --launch-template-name mcp-server-lt \
  --version-description "v2-updated-app" \
  --source-version 1 \
  --launch-template-data '{}'  \
  --user-data "$(base64 -w 0 bootstrap-v2.sh)"

Auto Scaling Group with ALB target group

# Create the ALB target group first
aws elbv2 create-target-group \
  --name mcp-server-tg \
  --protocol HTTP \
  --port 3000 \
  --vpc-id vpc-12345678 \
  --target-type instance \
  --health-check-path /health \
  --health-check-interval-seconds 15 \
  --healthy-threshold-count 2 \
  --unhealthy-threshold-count 3 \
  --health-check-timeout-seconds 5

# Reduce deregistration delay for fast deploys (default 300s is too slow)
aws elbv2 modify-target-group-attributes \
  --target-group-arn arn:aws:elasticloadbalancing:...:targetgroup/mcp-server-tg/abc \
  --attributes '[{
    "Key": "deregistration_delay.timeout_seconds",
    "Value": "30"
  }]'

# Create the Auto Scaling Group
aws autoscaling create-auto-scaling-group \
  --auto-scaling-group-name mcp-server-asg \
  --launch-template LaunchTemplateName=mcp-server-lt,Version='$Latest' \
  --min-size 2 \
  --max-size 10 \
  --desired-capacity 2 \
  --vpc-zone-identifier "subnet-aaa,subnet-bbb" \
  --target-group-arns arn:aws:elasticloadbalancing:...:targetgroup/mcp-server-tg/abc \
  --health-check-type ELB \
  --health-check-grace-period 120 \
  --default-instance-warmup 90

Key settings:

Target tracking scaling policy

Target tracking automatically adjusts the desired capacity to maintain a target metric value. For HTTP MCP servers, ALBRequestCountPerTarget is the best scaling trigger:

aws autoscaling put-scaling-policy \
  --auto-scaling-group-name mcp-server-asg \
  --policy-name mcp-server-scale-on-requests \
  --policy-type TargetTrackingScaling \
  --target-tracking-configuration '{
    "PredefinedMetricSpecification": {
      "PredefinedMetricType": "ALBRequestCountPerTarget",
      "ResourceLabel": "app/mcp-server-alb/abcdef123456/targetgroup/mcp-server-tg/abc123"
    },
    "TargetValue": 60.0,
    "ScaleInCooldown": 300,
    "ScaleOutCooldown": 60
  }'

Target value guidance for MCP servers:

Lifecycle hooks — graceful shutdown

When Auto Scaling terminates an instance (scale-in, instance refresh, or replacement of unhealthy instance), it moves the instance to Terminating:Wait state. A lifecycle hook gives you time to drain connections before EC2 issues the actual shutdown. Without a hook, the instance is terminated immediately after ALB deregistration, which can drop in-flight SSE connections.

# Create a termination lifecycle hook with a 120-second timeout
aws autoscaling put-lifecycle-hook \
  --auto-scaling-group-name mcp-server-asg \
  --lifecycle-hook-name drain-connections \
  --lifecycle-transition autoscaling:EC2_INSTANCE_TERMINATING \
  --default-result CONTINUE \
  --heartbeat-timeout 120

The hook fires before SIGTERM reaches the instance. During the 120-second window, your MCP server can:

  1. Stop accepting new connections (remove from health check registration, or return 503 from /health)
  2. Finish in-flight tool calls
  3. Close SSE streams gracefully
  4. Signal the lifecycle hook to continue (complete the termination)
// In your MCP server Node.js code — handle SIGTERM gracefully
let isShuttingDown = false;

process.on('SIGTERM', async () => {
  isShuttingDown = true;
  console.log('SIGTERM received, stopping new connections');

  // Stop the HTTP server from accepting new connections
  httpServer.close(() => {
    console.log('HTTP server closed');
  });

  // Wait for in-flight requests to complete (max 30s)
  await new Promise(resolve => setTimeout(resolve, 30_000));

  // Signal Auto Scaling lifecycle hook to complete termination
  // (requires autoscaling:CompleteLifecycleAction IAM permission)
  const instanceId = await getInstanceIdFromIMDS();
  await autoscalingClient.send(new CompleteLifecycleActionCommand({
    LifecycleHookName: 'drain-connections',
    AutoScalingGroupName: 'mcp-server-asg',
    LifecycleActionResult: 'CONTINUE',
    InstanceId: instanceId,
  }));

  process.exit(0);
});

// Return 503 during shutdown to remove from ALB rotation
app.get('/health', (req, res) => {
  if (isShuttingDown) {
    res.status(503).json({ status: 'shutting_down' });
  } else {
    res.json({ status: 'ok' });
  }
});

Add autoscaling:CompleteLifecycleAction to the instance role IAM policy so the server can signal the hook:

{
  "Effect": "Allow",
  "Action": "autoscaling:CompleteLifecycleAction",
  "Resource": "arn:aws:autoscaling:us-east-1:ACCOUNT_ID:autoScalingGroup:*:autoScalingGroupName/mcp-server-asg"
}

Instance refresh — zero-downtime code deploys

Instance refresh replaces instances in the ASG with new instances launched from the latest Launch Template version. It is the correct way to deploy code changes on an EC2 Auto Scaling fleet.

# Step 1: Update Launch Template to new version (new user data with updated app)
aws ec2 create-launch-template-version \
  --launch-template-name mcp-server-lt \
  --version-description "deploy-$(date +%Y%m%d-%H%M)" \
  --source-version '$Latest' \
  --user-data "$(base64 -w 0 bootstrap-v2.sh)"

# Set the new version as default
aws ec2 modify-launch-template \
  --launch-template-name mcp-server-lt \
  --default-version '$Latest'

# Step 2: Start instance refresh
aws autoscaling start-instance-refresh \
  --auto-scaling-group-name mcp-server-asg \
  --preferences '{
    "MinHealthyPercentage": 50,
    "InstanceWarmup": 120,
    "CheckpointPercentages": [50],
    "CheckpointDelay": 60
  }'

# Step 3: Monitor refresh progress
aws autoscaling describe-instance-refreshes \
  --auto-scaling-group-name mcp-server-asg \
  --query 'InstanceRefreshes[0].{Status:Status,Progress:PercentageComplete}'

Settings explanation:

To cancel an in-progress instance refresh:

aws autoscaling cancel-instance-refresh \
  --auto-scaling-group-name mcp-server-asg

Cancelled refreshes do not roll back already-replaced instances — instances launched on the new Launch Template version continue running.

Warm pools — eliminating cold start latency

A warm pool maintains a set of pre-initialized stopped instances that can be quickly launched when the ASG needs to scale out. For MCP servers with slow bootstrap scripts (60–120s Node.js install + S3 download), warm pools can reduce scale-out latency from 2 minutes to under 10 seconds.

aws autoscaling put-warm-pool \
  --auto-scaling-group-name mcp-server-asg \
  --pool-state Stopped \
  --min-size 1 \
  --max-group-prepared-capacity 3

Instances in the warm pool complete your bootstrap script (all the slow steps: Node.js install, S3 download, npm ci) and then stop. When the ASG needs a new instance, it starts a warm pool instance — which starts in ~15s — rather than launching a cold new instance.

Warm pool instances incur EBS storage costs (the stopped instance's volume), but no compute cost. For a 30 GB gp3 volume, that's ~$0.0024/hr per warm instance. For most MCP server deployments, keeping 1–2 warm instances is cost-effective insurance against traffic spikes.

Common errors and fixes

Error / SymptomCauseFix
Instances launched and terminated repeatedly (thrashing)Bootstrap takes longer than health-check-grace-period; instance marked unhealthy before MCP server startsIncrease health-check-grace-period to 150% of your bootstrap duration; add /health endpoint that returns 503 during startup
Scale-out triggered but new instances not healthyNew instance fails ALB health check at /healthCheck ALB target group health check logs; verify security group allows ALB to reach instance on the health check port
Connections dropped during scale-inDeregistrationDelay too short for long-lived SSE connectionsIncrease deregistration_delay to 60–120s; add lifecycle hook with heartbeat-timeout matching your longest expected session duration
Instance refresh stuck at checkpointAuto-proceeding is disabled or CheckpointDelay not setManually continue with aws autoscaling continue-instance-refresh or set a CheckpointDelay
Scaling out does not trigger (ALBRequestCountPerTarget not found)Target group not associated with the ASG, or ResourceLabel in the scaling policy is wrongVerify ALB ARN + target group ARN in the ResourceLabel: format is app/LOAD-BALANCER-NAME/LOAD-BALANCER-ID/targetgroup/TG-NAME/TG-ID

Related guides