TL;DR: This guide demonstrates how to eliminate the scaling bottlenecks of stateful Socket.io connections by migrating to AWS API Gateway WebSockets. API Gateway holds the client connections and DynamoDB stores connection IDs, so your Node.js handlers keep no connection state, scale horizontally, and can be redeployed without dropping client sockets. The trade-offs are hard limits (2-hour connections, 10-minute idle timeout, 32 KB frames) and per-message pricing.
Key Takeaways
- Offload persistent connection management to AWS API Gateway so backend deployments and scale-in events no longer disconnect clients.
- Remove the need for a Socket.io adapter such as
@socket.io/redis-adapter; fan-out becomes a DynamoDB query plusPostToConnectioncalls. - Configure
$connect,$disconnect, and$defaultWebSocket routes using the Serverless Framework to translate socket frames into stateless Lambda invocations. - Provision Amazon DynamoDB as a connection store, and authenticate
$connectwith a short-lived, single-use ticket rather than a long-lived token in the URL. - Design clients for the hard limits: reconnect before the 2-hour maximum, send heartbeats inside the 10-minute idle timeout, and keep frames under 32 KB.
You have a successful Node.js application. Your real-time features, whether powered by live fleet tracking, a collaborative dashboard, or a high-frequency trading ticker, are built on Socket.io. Everything works until your user base grows, the auto-scaler starts adding and removing instances, and every deployment or scale-in event disconnects thousands of clients at once.
The core problem is fundamental to how traditional WebSockets operate: stateful connections.
When a client connects to a Node.js server via Socket.io, that specific server instance holds the TCP socket open and allocates memory for the connection. If the instance dies, the connection dies with it. If you keep Socket.io's HTTP long-polling transport enabled, scaling horizontally requires sticky sessions on your Application Load Balancer (ALB) so that every request in a session reaches the same instance. (Restricting clients to transports: ['websocket'] removes that requirement, at the cost of no polling fallback.) Either way, as soon as you broadcast across instances you need an adapter backed by Redis or another pub/sub system.
The result: instances are sized for open connections rather than work, CPU-based auto-scaling metrics stop reflecting load, and rolling deployments trigger reconnect storms.
One alternative is to separate the persistent connection layer from your application logic. By offloading WebSocket connections to AWS API Gateway, your Node.js handlers no longer hold connection state.
In this guide, we will break down the migration strategy, the infrastructure provisioning, and the production code required to replace Socket.io with AWS API Gateway WebSockets.
The Stateful Trap: Why Socket.io Breaks at Scale
When running Socket.io across a cluster (ECS, EKS, or EC2 auto-scaling groups), the common approach is the @socket.io/redis-adapter.
// The legacy stateful approach
import { Server } from 'socket.io';
import { createAdapter } from '@socket.io/redis-adapter';
import { createClient } from 'redis';
const pubClient = createClient({ url: 'redis://your-elasticache-cluster:6379' });
const subClient = pubClient.duplicate();
await Promise.all([pubClient.connect(), subClient.connect()]);
const io = new Server(3000);
io.adapter(createAdapter(pubClient, subClient));
io.on('connection', (socket) => {
socket.on('location_update', (data) => {
// Emits to all clients across all servers via Redis pub/sub
io.to(data.fleetId).emit('location_updated', data);
});
});
This architecture works well for many teams, but it has costs that grow with connection count:
- Connection-bound capacity: Every open socket consumes memory and file descriptors on an application instance, and heartbeats and broadcasts run on the same event loop as your business logic, so instances are sized for connections rather than work.
- Disruptive deployments: When you deploy a new container, the old one drains. Its clients disconnect together and reconnect at once, producing a spike on the load balancer and backend.
- Shared pub/sub dependency: Every cross-instance broadcast goes through Redis Pub/Sub, so Redis availability and network throughput become part of your real-time path.
Production Note: Sticky sessions at the ALB level route traffic based on a cookie. If an instance fails, all clients attached to that instance must re-establish their connection, which can leave load unevenly distributed across the remaining instances.
The Stateless Alternative: AWS API Gateway WebSockets
AWS API Gateway provides WebSocket APIs (Regional endpoints) that change this model. Instead of your Node.js app holding the TCP connection, API Gateway holds it.
When a client sends a message over the socket, API Gateway translates that WebSocket frame into a standard HTTP request (or a direct Lambda invocation) and forwards it to your backend. Your Node.js server processes the payload, updates the database, and responds. The backend instance can then be replaced or recycled without closing the client's connection.
To provision this, we define three core routes in API Gateway: $connect, $disconnect, and $default. Here is how you define this infrastructure using the Serverless Framework:
# serverless.yml
service: websocket-stateless-api
provider:
name: aws
runtime: nodejs22.x
websocketsApiName: stateless-realtime-api
websocketsApiRouteSelectionExpression: $request.body.action
functions:
connectionHandler:
handler: src/handlers/connection.handler
events:
- websocket:
route: $connect
- websocket:
route: $disconnect
defaultMessage:
handler: src/handlers/message.handler
events:
- websocket:
route: $default
With this configuration, your handlers no longer manage connections themselves. (nodejs20.x reached Lambda deprecation in April 2026, so use nodejs22.x or nodejs24.x.)
Provisioning the Connection State Store (DynamoDB)
Because your Node.js application is now stateless, it has no memory of who is connected. When you want to push a message to a specific user (e.g., notifying User A that their driver has arrived), you need a way to look up User A’s active WebSocket connection ID.
We need a highly available, low-latency key-value store. DynamoDB fits well: one table keyed by connectionId, with global secondary indexes to look up connections by userId or groupId.
// infrastructure/dynamo.ts
import { DynamoDBClient, CreateTableCommand } from '@aws-sdk/client-dynamodb';
const client = new DynamoDBClient({ region: 'us-east-1' });
export const createConnectionsTable = async () => {
const command = new CreateTableCommand({
TableName: 'WebSocketConnections',
AttributeDefinitions: [
{ AttributeName: 'connectionId', AttributeType: 'S' },
{ AttributeName: 'userId', AttributeType: 'S' },
{ AttributeName: 'groupId', AttributeType: 'S' },
],
KeySchema: [
{ AttributeName: 'connectionId', KeyType: 'HASH' }, // Primary Key
],
GlobalSecondaryIndexes: [
{
IndexName: 'UserIdIndex',
KeySchema: [{ AttributeName: 'userId', KeyType: 'HASH' }],
Projection: { ProjectionType: 'ALL' },
},
{
IndexName: 'GroupIdIndex',
KeySchema: [{ AttributeName: 'groupId', KeyType: 'HASH' }],
Projection: { ProjectionType: 'ALL' },
},
],
BillingMode: 'PAY_PER_REQUEST',
});
await client.send(command);
};
Tip on Stale Connections:
$disconnectis delivered on a best-effort basis, so some records will never be deleted by your handler. Add attlattribute a little longer than the 2-hour maximum connection duration and enable DynamoDB TTL on it, so stale rows are removed automatically. TTL deletion is not immediate, so also clean up onGoneExceptionas shown below.
Wiring the Integration: $connect, $disconnect, and $default
When a client initiates a WebSocket connection, API Gateway triggers the $connect route. Your Node.js backend must authenticate the client and save the generated connectionId to DynamoDB.
Browsers cannot set custom headers on a WebSocket handshake, so credentials usually travel in the query string, and query strings end up in access logs. Do not put a long-lived session or JWT there. Instead, have the client fetch a short-lived, single-use ticket from an authenticated HTTPS endpoint and pass that. For larger systems, move this check into a Lambda REQUEST authorizer on the $connect route.
Here is the implementation using the AWS SDK v3:
// src/handlers/connection.ts
import { DynamoDBClient } from '@aws-sdk/client-dynamodb';
import { DynamoDBDocumentClient, PutCommand, DeleteCommand } from '@aws-sdk/lib-dynamodb';
import { APIGatewayProxyWebsocketEvent } from 'aws-lambda';
const client = new DynamoDBClient({});
const docClient = DynamoDBDocumentClient.from(client);
export const handler = async (event: APIGatewayProxyWebsocketEvent) => {
const { connectionId, eventType } = event.requestContext;
// Short-lived, single-use ticket: wss://{api-id}.execute-api.{region}.amazonaws.com/dev?ticket=...
const ticket = event.queryStringParameters?.ticket;
if (eventType === 'CONNECT') {
try {
// Look up and delete the ticket atomically, reject if missing or expired
const user = await redeemConnectTicket(ticket);
await docClient.send(
new PutCommand({
TableName: 'WebSocketConnections',
Item: {
connectionId,
userId: user.id,
groupId: user.groupId,
connectedAt: new Date().toISOString(),
ttl: Math.floor(Date.now() / 1000) + 60 * 60 * 3, // 3h: past the 2h max connection
},
}),
);
return { statusCode: 200, body: 'Connected' };
} catch (error) {
return { statusCode: 403, body: 'Unauthorized' };
}
}
if (eventType === 'DISCONNECT') {
await docClient.send(
new DeleteCommand({
TableName: 'WebSocketConnections',
Key: { connectionId },
}),
);
return { statusCode: 200, body: 'Disconnected' };
}
return { statusCode: 200 };
};
Because these handlers are plain functions behind API Gateway, they fit naturally into an event-driven backend. If you are splitting a monolith to get there, our backend development and API services cover this kind of migration.
Pushing Data to Clients: The API Gateway Management API
Unlike Socket.io, where you simply call socket.emit(), sending data back to the client in this architecture requires a signed HTTP POST to the API Gateway @connections endpoint. API Gateway then forwards that payload over the open connection to the client.
We execute this using the ApiGatewayManagementApiClient from the AWS SDK v3.
// src/utils/socketPush.ts
import {
ApiGatewayManagementApiClient,
PostToConnectionCommand,
GoneException,
} from '@aws-sdk/client-apigatewaymanagementapi';
import { DynamoDBClient } from '@aws-sdk/client-dynamodb';
import { DynamoDBDocumentClient, DeleteCommand } from '@aws-sdk/lib-dynamodb';
const client = new DynamoDBClient({});
const docClient = DynamoDBDocumentClient.from(client);
export const pushToClient = async (connectionId: string, payload: object, endpointUrl: string) => {
const wsClient = new ApiGatewayManagementApiClient({
endpoint: endpointUrl, // e.g., https://api-id.execute-api.us-east-1.amazonaws.com/prod
});
try {
// AWS SDK v3 requires Data to be a Uint8Array
await wsClient.send(
new PostToConnectionCommand({
ConnectionId: connectionId,
Data: new TextEncoder().encode(JSON.stringify(payload)),
}),
);
} catch (error) {
if (error instanceof GoneException) {
// The client disconnected silently. Clean up DynamoDB to save costs.
console.warn(`Connection ${connectionId} is stale. Removing.`);
await docClient.send(
new DeleteCommand({
TableName: 'WebSocketConnections',
Key: { connectionId },
}),
);
} else {
throw error;
}
}
};
Handling GoneException matters. Mobile clients on cellular networks often drop without sending a close frame. Treating HTTP 410 (Gone) as a signal to delete the record keeps the connection table accurate without waiting for TTL.
Broadcasting at Scale: Fan-Out Patterns
In Socket.io, broadcasting a message to a "room" is abstracted for you. With API Gateway, you must orchestrate the fan-out yourself.
When an event occurs, for example a GPS coordinate update for a delivery truck, you query for all connections subscribed to that truck and post the payload to each one.
Each push is an independent HTTP request, so send them concurrently in bounded chunks with Promise.all. Node.js handles many in-flight I/O requests on one thread; the chunk size caps concurrency so you stay inside API Gateway's request throttling and your own memory budget.
// src/services/broadcaster.ts
import { DynamoDBClient } from '@aws-sdk/client-dynamodb';
import { DynamoDBDocumentClient, QueryCommand } from '@aws-sdk/lib-dynamodb';
import { pushToClient } from '../utils/socketPush';
const client = new DynamoDBClient({});
const docClient = DynamoDBDocumentClient.from(client);
const CHUNK_SIZE = 50;
export const broadcastToGroup = async (groupId: string, message: object, endpointUrl: string) => {
// 1. Fetch all connection IDs for the group using the GSI
// A single Query returns up to 1 MB; follow LastEvaluatedKey for larger groups
const result = await docClient.send(
new QueryCommand({
TableName: 'WebSocketConnections',
IndexName: 'GroupIdIndex',
KeyConditionExpression: 'groupId = :groupId',
ExpressionAttributeValues: { ':groupId': groupId },
}),
);
const connections = result.Items || [];
// 2. Chunk the connections to prevent memory exhaustion and respect rate limits
for (let i = 0; i < connections.length; i += CHUNK_SIZE) {
const chunk = connections.slice(i, i + CHUNK_SIZE);
// 3. Fire parallel requests to API Gateway
const pushPromises = chunk.map((conn) =>
pushToClient(conn.connectionId, message, endpointUrl)
// Catch individual errors so one failed connection doesn't break the chunk
.catch((err) => console.error(`Failed to push to ${conn.connectionId}`, err)),
);
await Promise.all(pushPromises);
}
};
API Gateway does not cap concurrent connections directly. The effective ceiling comes from the rate of new connections (500 per second per account per Region by default, adjustable) combined with the 2-hour maximum duration, plus account-level request throttling for @connections calls. For very large rooms, move the fan-out into a queue-driven worker so the request that triggered the broadcast is not slowed down. GSIs are eventually consistent, so a connection created milliseconds ago may miss its first broadcast.
Handling API Gateway Limits and Production Edge Cases
Moving to AWS API Gateway WebSockets removes connection management from your servers, but it introduces specific limits that you must design around.
1. IAM Permissions Setup
Your Node.js Lambda functions or ECS tasks require explicitly defined IAM roles to push data back to connections. Without execute-api:ManageConnections, your PostToConnectionCommand will fail with an HTTP 403 Forbidden.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["execute-api:ManageConnections"],
"Resource": "arn:aws:execute-api:us-east-1:123456789012:api-id/*"
}
]
}
2. Hard Connection Timeouts
AWS API Gateway imposes a 2-hour maximum connection duration for WebSockets, along with a 10-minute idle timeout. Neither can be increased, so your frontend (React, React Native, or Flutter) must reconnect automatically.
// Frontend auto-reconnect strategy with exponential backoff
let socket;
let heartbeat;
let reconnectInterval = 1000;
async function connect() {
// Fetch a fresh single-use ticket over HTTPS for every connection attempt
const ticket = await fetchConnectTicket();
socket = new WebSocket(`wss://api-id.execute-api.region.amazonaws.com/prod?ticket=${ticket}`);
socket.onopen = () => {
reconnectInterval = 1000; // Reset backoff on success
// Heartbeat inside the 10-minute idle timeout (routed to $default)
heartbeat = setInterval(() => socket.send(JSON.stringify({ action: 'ping' })), 5 * 60 * 1000);
};
socket.onclose = () => {
clearInterval(heartbeat); // Avoid stacking intervals across reconnects
// Exponential backoff with jitter, capped at 10 seconds
const delay = reconnectInterval * (0.5 + Math.random());
reconnectInterval = Math.min(reconnectInterval * 2, 10000);
setTimeout(connect, delay);
};
}
3. Payload Size Constraints
API Gateway limits a WebSocket frame to 32 KB and a message to 128 KB; larger messages must be split across frames, and anything bigger closes the connection with code 1009. If your application transmits large payloads (like audio or base64 images), upload them to Amazon S3, generate a pre-signed URL, and send the URL over the WebSocket instead of the raw data.
Designing for the Future
Migrating from Socket.io to a stateless WebSocket backend is not a small refactor. It requires changing how your application conceptualizes user state, authorization, and event broadcasting.
In return, you no longer manage sticky sessions or a pub/sub adapter, backend CPU tracks actual work rather than open sockets, and deployments no longer disconnect clients. Cost is a trade-off rather than an automatic win: API Gateway bills per million messages and per connection-minute, so model both against your current instance costs before migrating. Teams with steady, very high message volumes sometimes find self-hosted WebSocket servers cheaper.
Sources
- Amazon API Gateway quotas for WebSocket APIs (frame and message size, 2-hour duration, 10-minute idle timeout, new-connection rate)
- Socket.IO docs: Using multiple nodes (when sticky sessions are required)
- Serverless Framework: AWS WebSocket events (
websocketsApiName, route selection expression) - AWS Lambda runtimes (Node.js runtime deprecation dates)
Need help building this in production?
SoftwareCrafting is a full-stack dev agency - we ship fast, scalable React, Next.js, Node.js, React Native & Flutter apps for global clients.
Get a Free ConsultationFrequently Asked Questions
Why does Socket.io become hard to scale?
Each Socket.io server holds its connections in memory, so horizontal scaling needs sticky sessions and a shared adapter such as Redis to broadcast across instances. That state makes deployments, autoscaling, and failover harder as connection counts grow.
How do API Gateway WebSockets keep the backend stateless?
API Gateway holds the open connections and calls your backend only for $connect, $disconnect, and incoming messages. Your Node.js code stores connection IDs in a table such as DynamoDB and sends messages back through the API Gateway Management API, so any instance or function can handle any request.
What limits should I plan for with API Gateway WebSockets?
Connections have a maximum duration of two hours and an idle timeout of ten minutes, frames are limited to 32 KB and messages to 128 KB. Clients need reconnect logic and periodic heartbeats, and large payloads should be sent as a reference to S3 instead of inline.
How do you broadcast one message to thousands of clients?
Query the connection IDs for the room or topic, then post to them in parallel batches, removing connections that return 410 Gone. For very large fan-out, push the work to a queue so the request that triggered the broadcast is not slowed down.
