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:
health-check-type ELB— ASG uses ALB health check results (not just EC2 instance running status) to determine instance health. Unhealthy instances are replaced automatically.health-check-grace-period 120— EC2 Auto Scaling waits 120 seconds after launch before checking ALB health. Set this longer than your bootstrap duration. If bootstrap takes 90s, use 120–180s.default-instance-warmup 90— Prevents new instances from contributing to scaling metrics during their warmup period, avoiding premature scale-in.deregistration_delay 30— ALB waits 30s after deregistering an instance for in-flight requests to complete. For MCP servers with SSE connections that may last minutes, consider 60–120s instead.
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:
- 60 requests/minute/instance is a reasonable starting point for MCP tool calls that average 500ms–2s. This keeps CPU under 50% with headroom for spikes.
- MCP servers with long-running tools (Bedrock inference, database queries) should use a lower target (20–40 req/min) to prevent overloading an instance with concurrent slow calls.
- MCP servers with SSE transport (long-lived connections) should scale on
ALBActiveConnectionCountinstead — each SSE session is an active connection, not a completed request per minute. ScaleInCooldown: 300— wait 5 minutes before scaling in to prevent flapping. Scale in slowly, scale out fast.ScaleOutCooldown: 60— scale out within 1 minute when load spikes.
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:
- Stop accepting new connections (remove from health check registration, or return 503 from
/health) - Finish in-flight tool calls
- Close SSE streams gracefully
- 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:
MinHealthyPercentage: 50— At least 50% of instances remain healthy during the refresh. For a 4-instance ASG, 2 instances are replaced at a time.InstanceWarmup: 120— New instances have 120 seconds to become healthy before the next batch replaces.CheckpointPercentages: [50]— Pause after 50% of instances are replaced for manual validation before continuing.CheckpointDelay: 60— Wait 60 seconds at the checkpoint before auto-proceeding (or you can cancel if something is wrong).
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 / Symptom | Cause | Fix |
|---|---|---|
| Instances launched and terminated repeatedly (thrashing) | Bootstrap takes longer than health-check-grace-period; instance marked unhealthy before MCP server starts | Increase 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 healthy | New instance fails ALB health check at /health | Check ALB target group health check logs; verify security group allows ALB to reach instance on the health check port |
| Connections dropped during scale-in | DeregistrationDelay too short for long-lived SSE connections | Increase deregistration_delay to 60–120s; add lifecycle hook with heartbeat-timeout matching your longest expected session duration |
| Instance refresh stuck at checkpoint | Auto-proceeding is disabled or CheckpointDelay not set | Manually 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 wrong | Verify ALB ARN + target group ARN in the ResourceLabel: format is app/LOAD-BALANCER-NAME/LOAD-BALANCER-ID/targetgroup/TG-NAME/TG-ID |
Related guides
- EC2 core patterns for MCP servers: instance profiles, IMDSv2, security groups
- EC2 user data and cloud-init for MCP server bootstrap automation
- EC2 Spot instances for MCP servers: interruption handling and mixed fleet
- Graceful shutdown patterns for MCP servers: SIGTERM, connection draining
- MCP server uptime monitoring