Guide · AWS Elastic Beanstalk · Auto-Scaling
Elastic Beanstalk Auto-Scaling for MCP Servers — ALB Sticky Sessions, Scaling Triggers, and SSE Transport
Auto-scaling an MCP server on Elastic Beanstalk requires more care than scaling a stateless REST API: SSE connections are long-lived and stateful, tool calls can run for seconds to minutes, and naive scale-in events will kill in-flight operations and drop active client sessions. This guide covers selecting the ALB over the CLB for SSE transport support, configuring ALB sticky sessions so clients remain pinned to their MCP instance, choosing the right scaling trigger metric for your MCP server's workload profile, and deploying with rolling-with-additional-batch to protect active sessions during deployments. For initial setup, see Elastic Beanstalk Node.js Platform. For Docker platform scaling, see EB Docker Platform. For .ebextensions syntax, see Environment Configuration.
TL;DR
Use an ALB (not CLB) — set LoadBalancerType: application in aws:elasticbeanstalk:environment. Enable sticky sessions on the target group (StickinessEnabled: true, 86400s duration). Use NetworkOut as the scaling trigger for I/O-bound MCP proxy servers, or CPUUtilization for compute-heavy tool servers. Set DeploymentPolicy: RollingWithAdditionalBatch to avoid taking instances out of service while sessions are active. Minimum 2 instances for production redundancy.
Why MCP server auto-scaling is different from REST API scaling
A typical REST API is stateless: any instance can serve any request, scale-in is safe at any time, and load balancer round-robin is the correct distribution strategy. MCP servers break each of these assumptions.
SSE connections are long-lived and stateful. When a client connects to an MCP server via the SSE transport, it establishes a persistent HTTP connection that may live for hours. The server accumulates session state in memory: the negotiated protocol capabilities, the tool call history, and any active streaming responses. If the instance hosting that session is terminated during a scale-in event, the client's session ends abruptly — from the client's perspective, the MCP server went down.
Tool calls can be long-running. An MCP tool that searches a large codebase, calls a third-party AI API, or runs a database migration may take 30 seconds to 5 minutes. Auto Scaling's default scale-in behavior terminates instances without waiting for in-flight work to complete. The 300-second default connection draining period (ALB's deregistration delay) only helps if the tool call completes within that window.
CPU is a misleading metric for proxy-style MCP servers. An MCP server that orchestrates calls to Bedrock, OpenAI, or external databases spends most of its time waiting on I/O. CPU utilization stays low even under heavy load — a 20% CPU trigger would never fire even when the instance is saturated with 500 concurrent SSE connections each waiting on a Bedrock response. Use NetworkOut for these workloads, or implement a custom CloudWatch metric that tracks active SSE connection count.
Load balancer choice: ALB is required for SSE-based MCP
EB supports three load balancer types. The choice has significant implications for MCP server transports:
Classic Load Balancer (CLB): The legacy EB default. No HTTP/2, no WebSocket upgrades, and no support for Server-Sent Events as a first-class protocol. The CLB will close long-lived SSE connections after its idle timeout (default 60 seconds, maximum 4000 seconds). It also does not support path-based routing rules, so you cannot route /sse to one target group and /health to another. Do not use CLB for MCP servers.
Application Load Balancer (ALB): HTTP/2 multiplexing over a single TCP connection, WebSocket upgrade support, SSE connection support with configurable idle timeout (up to 4000 seconds), path-based routing rules, and the AWSALB sticky session cookie. This is the correct choice for MCP servers.
Network Load Balancer (NLB): Layer 4 TCP passthrough. No HTTP-level awareness, no sticky sessions based on application cookies, no WebSocket upgrade handling at the load balancer layer. Useful for extreme throughput scenarios but adds operational complexity for HTTP-based MCP servers. Skip unless you have specific reasons.
# .ebextensions/alb.config — configure ALB for MCP SSE transport
option_settings:
# Must be set at environment creation; cannot change LB type on existing env
aws:elasticbeanstalk:environment:
LoadBalancerType: application
# Increase ALB idle timeout for long-lived SSE connections
# Default is 60s — an SSE session that goes quiet for 60s will be dropped
aws:elbv2:loadbalancer:
IdleTimeout: 3600 # 1 hour in seconds; max is 4000
# ALB access logs (optional but useful for diagnosing SSE disconnects)
aws:elbv2:loadbalancer:
AccessLogsS3Enabled: true
AccessLogsS3Bucket: my-alb-logs-bucket
AccessLogsS3Prefix: mcp-server-prod
ALB sticky sessions: pinning MCP clients to their instance
ALB sticky sessions use the AWSALB cookie (and AWSALBCORS for cross-origin requests) to route a client's subsequent requests to the same target instance. Once a client's first request is load-balanced to instance A and an SSE session is established, all future requests from that client bearing the AWSALB cookie go to instance A — even if other instances are less loaded.
# .ebextensions/sticky-sessions.config
option_settings:
# Enable stickiness on the ALB target group
aws:elbv2:targetgroup:default:
StickinessEnabled: true
# Duration before the stickiness cookie expires and the client can be
# rebalanced to a different instance. 86400s = 24 hours.
# Match this to your expected MCP session lifetime.
StickinessLBCookieDurationSeconds: 86400
# ALB listener stickiness (required in addition to target group stickiness)
aws:elbv2:listenerrule:default:
StickinessEnabled: true
The AWSALB cookie is set by the ALB itself on the first response — your MCP server does not need to do anything. The cookie is a hashed value encoding the target instance; when the instance is terminated and deregistered from the target group, the ALB ignores the cookie and rebalances the client to a healthy instance.
Important caveat: sticky sessions require the client to send cookies. Claude Desktop, Cursor, and other MCP clients that use the official SDK will send cookies correctly in browser-originated SSE connections. For programmatic clients that do not persist cookies between requests, sticky sessions will not work — consider using URL-based session routing (a path prefix encoding the instance ID) or an external session store like ElastiCache.
For CORS-enabled deployments (MCP servers accessed from web applications on a different domain), the ALB sets the AWSALBCORS cookie with SameSite=None; Secure in addition to the standard AWSALB cookie. Your MCP server must set appropriate CORS headers including Access-Control-Allow-Credentials: true for the cookie to be sent on cross-origin SSE requests.
Scaling triggers: choosing the right metric
EB's Auto Scaling triggers use step scaling policies driven by CloudWatch metrics. The aws:autoscaling:trigger namespace controls the trigger configuration:
# .ebextensions/autoscaling.config
option_settings:
aws:autoscaling:asg:
MinSize: 2 # Never fewer than 2 instances — HA baseline
MaxSize: 10 # Maximum instances during peak load
Cooldown: 300 # Seconds after a scaling event before another can fire
# Scaling trigger: NetworkOut is better than CPUUtilization for
# I/O-bound MCP proxy servers (Bedrock/OpenAI orchestration)
aws:autoscaling:trigger:
MeasureName: NetworkOut
Unit: Bytes
Statistic: Average
Period: "5" # Minutes; 5-minute average smooths transient spikes
BreachDuration: "2" # Minutes the metric must stay above threshold
UpperThreshold: "10000000" # 10 MB/5min avg = scale out
LowerThreshold: "1000000" # 1 MB/5min avg = scale in
UpperBreachScaleIncrement: "2" # Add 2 instances per scale-out event
LowerBreachScaleIncrement: "-1" # Remove 1 instance per scale-in event
Choosing MeasureName for your MCP server type
NetworkOut (Bytes): Total bytes sent from the instance to clients. For MCP servers that return large tool call results (file contents, code generation, search results), NetworkOut scales with the number of active tool calls. This is the best default trigger for proxy-style MCP servers where CPU is idle while waiting for upstream APIs.
CPUUtilization (Percent): Better for compute-intensive MCP servers that run local embedding models, code execution sandboxes, or image processing. Scale out at 70% CPU average over 5 minutes; scale in at 20%.
RequestCount (Count): Total HTTP requests to the instance (from ALB). Useful when tool calls are fast and uniform. Requires ALB request count metric, which is in the AWS/ApplicationELB namespace — not directly available as an EB trigger; use RequestCountPerTarget via a custom trigger on the ALB's RequestCountPerTarget metric.
# Alternative trigger for compute-heavy MCP servers (embedding generation, etc.)
option_settings:
aws:autoscaling:trigger:
MeasureName: CPUUtilization
Unit: Percent
Statistic: Average
Period: "5"
BreachDuration: "3"
UpperThreshold: "70"
LowerThreshold: "20"
UpperBreachScaleIncrement: "1"
LowerBreachScaleIncrement: "-1"
Rolling deployments and their interaction with MCP sessions
EB's default deployment policy (AllAtOnce) takes all instances out of service simultaneously, deploys the new version, and brings them back. This destroys all active MCP sessions. For production MCP servers with active users, use a deployment policy that keeps some instances serving traffic throughout the deployment.
# .ebextensions/deployment-policy.config
option_settings:
aws:elasticbeanstalk:command:
# RollingWithAdditionalBatch: adds new instances BEFORE terminating old ones
# - never reduces capacity below MinSize during deployment
# - active MCP sessions on old instances continue until ALB drains them
# - new instances become healthy and join the target group before old ones leave
DeploymentPolicy: RollingWithAdditionalBatch
# Percentage of fleet updated per batch
# 25% = 2 instances at a time (for a fleet of 8)
BatchSizeType: Percentage
BatchSize: "25"
# How long EB waits for the new batch to become healthy before proceeding
# Must be long enough for your MCP server startup + npm install time
Timeout: "600"
# Time EB waits after a successful batch before starting the next
# Gives you time to observe metrics before continuing the rollout
IgnoreHealthCheck: false
The RollingWithAdditionalBatch policy works as follows: for a fleet of 4 instances with BatchSize 25% (1 instance per batch), EB temporarily scales up to 5 instances, deploys the new version on instance 5, waits for it to pass health checks, then terminates instance 1 (the oldest). This continues until all 4 instances run the new version.
The key benefit for MCP servers: instances running the old version continue serving SSE sessions until they are drained by the ALB. The ALB's DeregistrationDelay (connection draining timeout) gives in-flight tool calls time to complete before the instance is terminated.
ALB connection draining and deregistration delay
When Auto Scaling terminates an instance (scale-in or deployment), it first deregisters the instance from the ALB target group. The ALB's deregistration delay is the time the ALB waits before forcibly closing connections to the deregistered instance. During this window, existing connections (including SSE sessions) continue to function; the ALB simply stops routing new requests to the deregistered target.
# .ebextensions/alb-draining.config
option_settings:
aws:elbv2:targetgroup:default:
# Default is 300 seconds (5 minutes)
# Tune this to match your longest expected tool call duration
# For MCP servers with fast tool calls: reduce to 30-60 seconds
# For MCP servers with long-running tools (AI generation, etc.): keep at 300+
DeregistrationDelay: "300"
# Health check settings for the target group
HealthCheckPath: /health
HealthCheckIntervalSeconds: "15"
HealthyThresholdCount: "2"
UnhealthyThresholdCount: "3"
HealthCheckTimeoutSeconds: "5"
During the deregistration delay, ALB sticky session cookies that point to the deregistering instance will be honored — existing sessions reach their instance for the duration of the draining period. After the delay expires, those connections are closed and the instance is fully deregistered.
Setting DeregistrationDelay too low (e.g., 10 seconds) risks aborting long-running tool calls. Setting it too high (e.g., 1800 seconds) slows down scale-in events significantly — with 4 instances scaling down to 2 instances, you would wait 1800 seconds per instance, adding 60 minutes to a scale-in event. Find the right balance by measuring your P99 tool call duration from CloudWatch or application logs.
Minimum and maximum instance counts
Always set MinSize: 2 for production MCP servers. A single-instance environment (MinSize: 1) creates a single point of failure: when EB replaces an unhealthy instance or the instance is terminated during a deployment, there is a gap in availability. With MinSize: 2, at least one instance is always serving traffic.
option_settings:
aws:autoscaling:asg:
MinSize: 2
MaxSize: 10
# Cooldown prevents rapid oscillation during traffic spikes
# 300s = don't start another scale-out within 5 minutes of the last one
Cooldown: 300
# Availability zone distribution — spread instances evenly across AZs
# for resilience against AZ-level failures
aws:ec2:vpc:
Subnets: subnet-1a-id,subnet-1b-id,subnet-1c-id
ELBSubnets: subnet-public-1a,subnet-public-1b,subnet-public-1c
For MaxSize, set a value that reflects your AWS service quotas and cost ceiling. Each EB instance counts against your EC2 On-Demand instance quota. For MCP servers that make Bedrock calls, also factor in Bedrock's requests-per-minute quota — scaling to 10 instances means up to 10x the concurrent Bedrock requests.
Target tracking vs. step scaling on EB
EB's aws:autoscaling:trigger namespace implements step scaling policies: when a metric crosses a threshold, add N instances; when it crosses a lower threshold, remove N instances. Target tracking policies (which automatically adjust the scaling increment to maintain a target metric value) are not natively configurable via EB's .ebextensions.
To use target tracking, configure it on the Auto Scaling group directly after EB creates the environment:
#!/bin/bash
# get-asg-name.sh — retrieve the ASG created by EB for an environment
EB_ENV_NAME="mcp-server-prod"
ASG_NAME=$(aws elasticbeanstalk describe-environment-resources \
--environment-name "${EB_ENV_NAME}" \
--query 'EnvironmentResources.AutoScalingGroups[0].Name' \
--output text)
echo "ASG: ${ASG_NAME}"
# Delete EB-managed step scaling policies
aws autoscaling delete-policy \
--auto-scaling-group-name "${ASG_NAME}" \
--policy-name "awseb-${EB_ENV_NAME}-scalingPolicy"
# Create a target tracking policy: maintain average CPU at 60%
aws autoscaling put-scaling-policy \
--auto-scaling-group-name "${ASG_NAME}" \
--policy-name mcp-server-target-tracking \
--policy-type TargetTrackingScaling \
--target-tracking-configuration '{
"PredefinedMetricSpecification": {
"PredefinedMetricType": "ASGAverageCPUUtilization"
},
"TargetValue": 60.0,
"ScaleInCooldown": 300,
"ScaleOutCooldown": 60
}'
Warning: EB may recreate step scaling policies when you run eb deploy or eb config set, overwriting the target tracking policy. Add a .platform/hooks/postdeploy/ script to re-apply the target tracking configuration after each deployment, as described in Environment Configuration.
Complete example: .ebextensions/autoscaling.config
The following is a production-ready autoscaling configuration for a Node.js MCP server using the SSE transport with sticky sessions, ALB, and rolling-with-additional-batch deployments.
# .ebextensions/autoscaling.config
option_settings:
# --- Load Balancer ---
aws:elasticbeanstalk:environment:
LoadBalancerType: application
aws:elbv2:loadbalancer:
IdleTimeout: 3600
# --- Target Group ---
aws:elbv2:targetgroup:default:
StickinessEnabled: true
StickinessLBCookieDurationSeconds: 86400
DeregistrationDelay: "300"
HealthCheckPath: /health
HealthCheckIntervalSeconds: "15"
HealthyThresholdCount: "2"
UnhealthyThresholdCount: "3"
# --- Listener Rule Stickiness ---
aws:elbv2:listenerrule:default:
StickinessEnabled: true
# --- Auto Scaling Group ---
aws:autoscaling:asg:
MinSize: 2
MaxSize: 10
Cooldown: 300
# --- Scaling Trigger (NetworkOut for I/O-bound MCP proxy) ---
aws:autoscaling:trigger:
MeasureName: NetworkOut
Unit: Bytes
Statistic: Average
Period: "5"
BreachDuration: "2"
UpperThreshold: "10000000"
LowerThreshold: "1000000"
UpperBreachScaleIncrement: "2"
LowerBreachScaleIncrement: "-1"
# --- Deployment Policy ---
aws:elasticbeanstalk:command:
DeploymentPolicy: RollingWithAdditionalBatch
BatchSizeType: Percentage
BatchSize: "25"
Timeout: "600"
IgnoreHealthCheck: false
# --- Enhanced Health ---
aws:elasticbeanstalk:healthreporting:system:
SystemType: enhanced
HealthStreamingEnabled: true
HealthCheckSuccessThreshold: Ok
Connect AliveMCP to monitor /health at a 30-second interval. External monitoring catches ALB-level failures (misconfigured listener rules, certificate expiry, DNS resolution failures) and scale-event gaps that EB's internal health reporting misses. Configure alerting with a 2-failure threshold to avoid noise from brief instance replacement events.