AWS Builder Center

Building Real-Time Applications with AWS WebSocket API Gateway, Lambda, and React

A complete guide to building a serverless real-time chat application using AWS CDK

cloud engineer

Introduction

HTTP follows a simple request-response pattern - the client asks, the server answers. But what happens when you need the server to push data to clients in real time? Think chat applications, live dashboards, multiplayer games, or stock tickers.
WebSocket solves this by maintaining a persistent, bidirectional connection between client and server. AWS API Gateway now natively supports WebSocket APIs, allowing you to build fully serverless real-time applications without managing any WebSocket servers.
In this article, we'll build a real-time chat application from scratch using:
  • AWS API Gateway (WebSocket) - manages persistent connections
  • AWS Lambda - handles connect, disconnect, and message events
  • Amazon DynamoDB - stores active connection IDs
  • AWS CDK -**** defines and deploys all infrastructure as code
  • React.js - the frontend client
By the end, you'll have a working chat app where multiple browser tabs can exchange messages in real time - all running serverlessly.

Architecture Overview

Here's how the pieces fit together:


How WebSocket API Gateway Works

Unlike REST APIs, a WebSocket API maintains a long-lived connection. API Gateway assigns a unique connectionId to each client and routes incoming frames to Lambda functions based on route keys.
There are three special routes:
Route
Trigger
Purpose
 $connect 
Client opens connection
Store the connectionId
 $disconnect 
Client closes connection
Remove the connectionId
 sendMessage 
Client sends  {"action": "sendMessage", ...} 
Broadcast to all clients
The route selection expression  $request.body.action  tells API Gateway to look at the  action  field in the JSON body to determine which route to invoke.



Project Structure

aws-websocket-gateway/
├── backend/
│ ├── bin/app.ts # CDK app entry point
│ ├── lib/websocket-stack.ts # Infrastructure definition
│ ├── src/
│ │ ├── connect.js # $connect Lambda handler
│ │ ├── disconnect.js # $disconnect Lambda handler
│ │ └── sendMessage.js # sendMessage Lambda handler
│ ├── cdk.json
│ ├── tsconfig.json
│ └── package.json
├── frontend/
│ ├── src/
│ │ ├── App.jsx
│ │ ├── components/Chat.jsx
│ │ ├── hooks/useWebSocket.js
│ │ ├── main.jsx
│ │ └── index.css
│ ├── index.html
│ ├── vite.config.js
│ └── package.json
└── package.json # npm workspaces root

Part 1: The Backend - Infrastructure with AWS CDK

Why CDK over CloudFormation or SAM?

AWS CDK lets you define cloud infrastructure using familiar programming languages. You get type safety, IDE autocompletion, and the ability to encapsulate patterns into reusable constructs. For WebSocket APIs with multiple Lambda integrations, CDK drastically reduces boilerplate.

The CDK Stack

// backend/lib/websocket-stack.ts
import * as cdk from "aws-cdk-lib";
import { Construct } from "constructs";
import * as dynamodb from "aws-cdk-lib/aws-dynamodb";
import * as lambda from "aws-cdk-lib/aws-lambda";
import * as apigatewayv2 from "aws-cdk-lib/aws-apigatewayv2";
import * as apigatewayv2_integrations from "aws-cdk-lib/aws-apigatewayv2-integrations";
import * as iam from "aws-cdk-lib/aws-iam";
import * as path from "path";

export class WebSocketStack extends cdk.Stack {
constructor(scope: Construct, id: string, props?: cdk.StackProps) {
super(scope, id, props);

// DynamoDB table to store active connections
const connectionsTable = new dynamodb.Table(this, "ConnectionsTable", {
tableName: "WebSocketConnections",
partitionKey: {
name: "connectionId",
type: dynamodb.AttributeType.STRING,
},
billingMode: dynamodb.BillingMode.PAY_PER_REQUEST,
removalPolicy: cdk.RemovalPolicy.DESTROY,
});

const lambdaEnvironment = {
CONNECTIONS_TABLE: connectionsTable.tableName,
};

// Lambda handlers
const connectHandler = new lambda.Function(this, "ConnectHandler", {
runtime: lambda.Runtime.NODEJS_18_X,
handler: "connect.handler",
code: lambda.Code.fromAsset(path.join(__dirname, "../src")),
environment: lambdaEnvironment,
});

const disconnectHandler = new lambda.Function(this, "DisconnectHandler", {
runtime: lambda.Runtime.NODEJS_18_X,
handler: "disconnect.handler",
code: lambda.Code.fromAsset(path.join(__dirname, "../src")),
environment: lambdaEnvironment,
});

const sendMessageHandler = new lambda.Function(this, "SendMessageHandler", {
runtime: lambda.Runtime.NODEJS_18_X,
handler: "sendMessage.handler",
code: lambda.Code.fromAsset(path.join(__dirname, "../src")),
environment: lambdaEnvironment,
});

// Grant DynamoDB permissions
connectionsTable.grantReadWriteData(connectHandler);
connectionsTable.grantReadWriteData(disconnectHandler);
connectionsTable.grantReadWriteData(sendMessageHandler);

// WebSocket API
const webSocketApi = new apigatewayv2.WebSocketApi(this, "WebSocketChatApi", {
apiName: "WebSocketChatApi",
routeSelectionExpression: "$request.body.action",
connectRouteOptions: {
integration: new apigatewayv2_integrations.WebSocketLambdaIntegration(
"ConnectIntegration", connectHandler
),
},
disconnectRouteOptions: {
integration: new apigatewayv2_integrations.WebSocketLambdaIntegration(
"DisconnectIntegration", disconnectHandler
),
},
});

webSocketApi.addRoute("sendMessage", {
integration: new apigatewayv2_integrations.WebSocketLambdaIntegration(
"SendMessageIntegration", sendMessageHandler
),
});

// Deploy to a stage
const stage = new apigatewayv2.WebSocketStage(this, "ProductionStage", {
webSocketApi,
stageName: "production",
autoDeploy: true,
});

// Allow sendMessage Lambda to push messages back to clients
sendMessageHandler.addToRolePolicy(
new iam.PolicyStatement({
actions: ["execute-api:ManageConnections"],
resources: [
`arn:aws:execute-api:${this.region}:${this.account}:${webSocketApi.apiId}/${stage.stageName}/*`,
],
})
);

new cdk.CfnOutput(this, "WebSocketURL", {
value: stage.url,
description: "WebSocket API URL",
});
}
}
Key points:
  • PAY_PER_REQUEST billing means zero cost when idle
  •  autoDeploy: true  means route changes are deployed automatically
  • The ManageConnections permission is critical - without it, the sendMessage Lambda cannot post data back to connected clients

Part 2: Lambda Handlers

Connect Handler

When a client opens a WebSocket connection, API Gateway invokes this function with the new  connectionId . We store it in DynamoDB:
// backend/src/connect.js
const { DynamoDBClient } = require("@aws-sdk/client-dynamodb");
const { DynamoDBDocumentClient, PutCommand } = require("@aws-sdk/lib-dynamodb");

const client = new DynamoDBClient({});
const ddb = DynamoDBDocumentClient.from(client);
const TABLE_NAME = process.env.CONNECTIONS_TABLE;

exports.handler = async (event) => {
const connectionId = event.requestContext.connectionId;

await ddb.send(
new PutCommand({
TableName: TABLE_NAME,
Item: {
connectionId,
connectedAt: new Date().toISOString(),
},
})
);

return { statusCode: 200, body: "Connected." };
};

Disconnect Handler

Cleanup is just as simple - delete the connection record:
// backend/src/disconnect.js
exports.handler = async (event) => {
const connectionId = event.requestContext.connectionId;

await ddb.send(
new DeleteCommand({
TableName: TABLE_NAME,
Key: { connectionId },
})
);

return { statusCode: 200, body: "Disconnected." };
};

SendMessage Handler -The Interesting One

This is where the magic happens. When one client sends a message, we broadcast it to all connected clients using the API Gateway Management API:
// backend/src/sendMessage.js
const { ApiGatewayManagementApiClient, PostToConnectionCommand }
= require("@aws-sdk/client-apigatewaymanagementapi");

exports.handler = async (event) => {
const { domainName, stage } = event.requestContext;
const endpoint = `https://${domainName}/${stage}`;

const apigwClient = new ApiGatewayManagementApiClient({ endpoint });

const body = JSON.parse(event.body);
const message = body.message || "";
const senderConnectionId = event.requestContext.connectionId;

// Get all active connections
const result = await ddb.send(new ScanCommand({ TableName: TABLE_NAME }));
const connections = result.Items || [];

// Broadcast to everyone
const payload = JSON.stringify({
message,
sender: senderConnectionId,
timestamp: new Date().toISOString(),
});

const postCalls = connections.map(async ({ connectionId }) => {
try {
await apigwClient.send(
new PostToConnectionCommand({
ConnectionId: connectionId,
Data: payload,
})
);
} catch (error) {
if (error.statusCode === 410) {
// Stale connection — client disconnected without triggering $disconnect
await ddb.send(new DeleteCommand({
TableName: TABLE_NAME,
Key: { connectionId },
}));
}
}
});

await Promise.all(postCalls);
return { statusCode: 200, body: "Message sent." };
};
Important detail: The  410 Gone  status code means the connection no longer exists. This happens when clients disconnect abruptly (e.g., closing the browser tab without a clean close frame). We handle this by removing stale entries from DynamoDB.



Part 3: React Frontend

The useWebSocket Custom Hook

We encapsulate all WebSocket logic in a custom React hook. This keeps the component clean and the connection logic reusable:
// frontend/src/hooks/useWebSocket.js
import { useState, useEffect, useRef, useCallback } from "react";

const WS_URL = import.meta.env.VITE_WS_URL;

export function useWebSocket() {
const [messages, setMessages] = useState([]);
const [connectionStatus, setConnectionStatus] = useState("disconnected");
const wsRef = useRef(null);
const reconnectTimeoutRef = useRef(null);

const connect = useCallback(() => {
const ws = new WebSocket(WS_URL);
wsRef.current = ws;
setConnectionStatus("connecting");

ws.onopen = () => setConnectionStatus("connected");

ws.onmessage = (event) => {
const data = JSON.parse(event.data);
setMessages((prev) => [...prev, {
id: Date.now() + Math.random(),
message: data.message,
sender: data.sender,
timestamp: data.timestamp,
isOwn: false,
}]);
};

ws.onclose = () => {
setConnectionStatus("disconnected");
// Auto-reconnect after 3 seconds
reconnectTimeoutRef.current = setTimeout(connect, 3000);
};

ws.onerror = () => setConnectionStatus("error");
}, []);

const sendMessage = useCallback((message) => {
if (wsRef.current?.readyState === WebSocket.OPEN) {
wsRef.current.send(JSON.stringify({
action: "sendMessage",
message,
}));
// Optimistically add our own message
setMessages((prev) => [...prev, {
id: Date.now() + Math.random(),
message,
sender: "You",
timestamp: new Date().toISOString(),
isOwn: true,
}]);
}
}, []);

// Cleanup on unmount
useEffect(() => {
return () => {
clearTimeout(reconnectTimeoutRef.current);
wsRef.current?.close();
};
}, []);

return { messages, connectionStatus, connect, disconnect, sendMessage, clearMessages };
}
Design decisions:
  • Optimistic updates - the sender sees their message immediately without waiting for the server round-trip
  • Auto-reconnect - if the connection drops, we retry after 3 seconds
  • Ref-based WebSocket -using  useRef  avoids re-renders when the WebSocket instance changes

The Chat Component

The UI is straightforward: a status indicator, a message list, and an input form. Messages from "you" float right; messages from others float left - similar to any modern messaging app.
// frontend/src/components/Chat.jsx
function Chat() {
const { messages, connectionStatus, connect, disconnect, sendMessage } = useWebSocket();
const [inputMessage, setInputMessage] = useState("");

const handleSubmit = (e) => {
e.preventDefault();
if (inputMessage.trim()) {
sendMessage(inputMessage.trim());
setInputMessage("");
}
};

return (
<div className="chat-container">
<div className="chat-controls">
<StatusIndicator status={connectionStatus} />
<button onClick={connectionStatus === "connected" ? disconnect : connect}>
{connectionStatus === "connected" ? "Disconnect" : "Connect"}
</button>
</div>
<div className="messages-container">
{messages.map((msg) => (
<Message key={msg.id} {...msg} />
))}
</div>
<form onSubmit={handleSubmit}>
<input
value={inputMessage}
onChange={(e) => setInputMessage(e.target.value)}
disabled={connectionStatus !== "connected"}
placeholder="Type a message..."
/>
<button type="submit" disabled={connectionStatus !== "connected"}>
Send
</button>
</form>
</div>
);
}

Part 4: Deployment

Prerequisites

  • Node.js 18+
  • AWS CLI configured ( aws configure )
  • AWS CDK CLI ( npm install -g aws-cdk )

Steps

# 1. Install dependencies
npm install

# 2. Bootstrap CDK (one-time per AWS account/region)
cd backend
npx cdk bootstrap

# 3. Deploy the stack
npx cdk deploy
CDK will output the WebSocket URL:
Outputs:
WebSocketGatewayStack.WebSocketURL = wss://abc123.execute-api.us-east-1.amazonaws.com/production

Configure the Frontend

cd frontend
echo "VITE_WS_URL=wss://abc123.execute-api.us-east-1.amazonaws.com/production" > .env
npm run dev
Open two browser tabs and watch messages flow in real time.

The Message Flow

Let's trace what happens when Client A sends "Hello":
  1. Client A sends  {"action": "sendMessage", "message": "Hello"}  over WebSocket
  1. API Gateway reads  action: "sendMessage"  and routes to the sendMessage Lambda
  1. sendMessage Lambda scans DynamoDB for all active connectionIds
  1. Lambda calls  PostToConnection  for each connectionId via the API Gateway Management API
  1. API Gateway pushes the message frame to each connected client
  1. Client B receives the message via  ws.onmessage  and renders it
Total server cost for this interaction: fractions of a cent.

Cost Analysis

This architecture is remarkably cost-effective for low-to-moderate traffic:
Service
Pricing
Idle Cost
API Gateway WebSocket
$1.00 per million connection minutes + $1.00 per million messages
$0
Lambda
$0.20 per million requests + duration
$0
DynamoDB (on-demand)
$1.25 per million writes, $0.25 per million reads
$0
Zero idle cost - you only pay when users are connected and actively messaging.

Production Considerations

Before going to production, consider:
  1. Authentication - Add a Lambda authorizer to the  $connect  route to validate JWT tokens or API keys
  1. Rate limiting - Configure throttling on the WebSocket stage
  1. Message validation - Validate and sanitize message content in the sendMessage handler
  1. Connection limits - DynamoDB Scan becomes expensive at scale; consider using a GSI or switching to Redis/ElastiCache for connection management
  1. Dead letter queues - Add DLQ to Lambda functions for failed broadcasts
  1. CORS - WebSocket connections aren't subject to CORS, but your initial handshake might be if you add HTTP endpoints

Cleanup

Remove all AWS resources with a single command:
cd backend
npx cdk destroy

Conclusion

AWS WebSocket API Gateway removes the operational burden of managing WebSocket servers while keeping the serverless cost model. Combined with CDK for infrastructure-as-code and React for the frontend, you get a complete real-time stack that scales to zero and costs nothing when idle.
The full source code is available in the  repository . Clone it, deploy it, and build something real-time.
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article