Project: Build a WebSocket Chat Room with API Gateway, Lambda and DynamoDB (Source Code)
WhatsApp Web and live support chat need a push channel, not refresh. API Gateway WebSocket keeps a connection; Lambda handles connect, disconnect and message; DynamoDB stores connection IDs.
In this chapter
- Create WebSocket API routes
- Track connections in DynamoDB
- Broadcast with ManageConnections
- Test with the HTML client and cleanup
1. Everyday example
HTTP request/response cannot push a new chat line to everyone already on the page. WebSocket stays open both ways.
$connect → save connectionId. $disconnect → delete. Custom route sendmessage → save chat row + post_to_connection to all.
Download: websocket-chat.zip — connect/disconnect/message + public/index.html
2. Lab
A. Tables
A WebSocket keeps a connection open so either the browser or the backend can send a message while that connection lasts. Each tab gets its own connectionId. Save those values in the connections table so the backend has an address for each connected tab. Save actual chat records in the messages table, where a message ID identifies each record. A message can remain stored after the tab disconnects.
For example, two tabs might have connection IDs A and B. When A sends classroom text, the message Lambda stores one chat record and sends the text to both A and B using the API Gateway management endpoint. The connection IDs are callback addresses. Use the appropriate account and room membership checks before building private chat.
- Table
yourname-chat-conn, PKconnectionId. - Table
yourname-chat-msg, PKmessageId.
B. Lambdas
- Three functions from the zip (or one router — lab uses three). Use
connect.lambda_handler,disconnect.lambda_handlerandmessage.lambda_handler. SetCONNECTIONS_TABLEon all three. Also setMESSAGES_TABLEon the message Lambda. - IAM: DynamoDB access + execute-api:ManageConnections for the message role.
C. WebSocket API
A route names the action API Gateway should send to a backend. The $connect route runs during the new connection. The message with "action":"sendmessage" selects the custom route of the same name. The management call then sends data to a particular connection during that connection’s lifetime. This is why a green connection indicator alone does not validate the send route or callback permission.
Connect two tabs, send a distinctive short line from tab A, and confirm it arrived in tab B. Then close B and reconnect. Expect a new connection ID. If a callback to the old ID reports GoneException, the old destination is stale. That result helps you decide whether to repair stored connection records or study route selection.
- API Gateway → Create WebSocket API. Routes:
$connect,$disconnect,sendmessage(route selection expression$request.body.actionOR integrate sendmessage as default — lab: set route key sendmessage and client sends {"action":"sendmessage","text":"..."} ). Simpler lab path: use route selection$request.body.actionand body action sendmessage. - Deploy stage
prod. Copywss://URL. - Open public/index.html locally, paste wss URL, Connect, Send from two browser tabs.
// client send body example
{"action":"sendmessage","room":"lobby","text":"hello lab"}
Cleanup
- Delete WebSocket API (stages first), three Lambdas, both tables, roles.
- Closed connections leave stale IDs — deleting the table clears them.
Common errors and fixes
These are synthetic practice situations. Diagnose the signal before changing a resource; no infrastructure changes are needed to read this guide.
The browser connects, but backend callbacks fail.
The browser uses a wss URL; the backend Management API uses an HTTPS endpoint and IAM-signed requests. For the default execute-api domain, use the API and stage for that connection. Check endpoint, stage and ManageConnections permission separately. A successful browser handshake does not grant the worker permission to call back.
Sending JSON never reaches sendmessage.
The route-selection expression and the client property must agree. With $request.body.action, the body action must match the sendmessage route key. A different field name or value can select a fallback instead. Inspect a synthetic message and route configuration before changing database permissions; a routing mismatch can happen before message logic runs.
The Lambda returned success but neither browser shows the chat line.
Returning from a message handler is not by itself a broadcast to all connected clients. The application must call the connection-management API for the intended recipients and handle its results. Distinguish handler completion from callback success and from client display. Inspect those three stages rather than treating one successful invocation as proof of delivery.
Practical FAQ: decisions during real work
Can the connections table be an exact list of online users?
Not without stale-entry handling. The disconnect event is best effort and may never reach the integration. A row can survive a closed browser, and a reconnect receives a new connection identity. Treat the table as connection records requiring validation and cleanup, not as authoritative user presence just because a row exists.
Does a connection ID prove who may read a room?
No. A connection ID is a callback destination, not a user identity or room permission. Authorize the connection and verify the application-level membership before selecting recipients for a private room. A client-supplied room field alone must not decide who receives protected messages. Use synthetic public-room text for this lab, not personal chat data.
Does a successful callback mean the person read the message?
No. Backend acceptance of a callback is not a human read receipt. Durable history, client acknowledgments and read-state are separate application features. If a message must survive reconnects, store it with a stable message identity and define how clients fetch missed history. A live socket alone does not supply that business guarantee.
3. Interview
Q. WebSocket vs HTTP polling?
Push is cheaper and faster for chat.
Q. GoneException?
Connection already closed — delete from table.
Q. Why store connectionId?
post_to_connection needs it.
Q. Auth?
Authorize the $connect route. WebSocket API Gateway supports a Lambda request authorizer on $connect. Authorize room memberships in application code before broadcasting private messages.
Q. Cleanup?
API + Lambdas + tables.
Try at home
- Filter broadcast by roomId.
- Add a history GET via HTTP API.
In short
- WebSocket API + Lambda + DynamoDB connections.
- ManageConnections broadcasts.
- Handle GoneException.
- Clean up.
Trace one live message from each browser
Use connectionId for the connections table and messageId for the messages table, both strings. Open two tabs with synthetic data and verify both receive the same message ID. Set CONNECTIONS_TABLE on all three handlers, plus MESSAGES_TABLE on message.lambda_handler. Watch for a stale connection after closing one tab.
Interview check Does the room field provide privacy?
No. The starter is a single broadcast lobby. The browser uses wss and the backend callback uses the HTTPS Management API; private rooms would need authenticated connections and server-side membership checks.
Practise this chapter
Interview questions and answers
Why are two browser tabs better than one for testing this chat lab?
One tab can demonstrate that a connection opens or show its own local text. Two tabs show that a message entered the send route, reached the backend and was sent back to another connection. Closing and reconnecting a tab also tests whether the stored destination remains current.
Check your understanding
Choose an answer, then compare your reasoning with the explanation.
Practice Tasks
Practice checks run in your browser. They check the answer for this exercise; they do not create resources or connect to your AWS account.
About this scenarioVidarbha Cotton Mills is a textiles business in Nagpur. Ganesh Wankhede looks after its IT and cloud work. They count money in INR and run their AWS resources in the ap-south-1 Region. In the tasks below you do real jobs for them using what this lesson teaches. All names, account IDs, IP addresses and numbers are made up for practice.
0 / 12
Easy List functions
See which functions exist in this Region.
List the Lambda functions in ap-south-1.
- Read the task and decide which AWS service it is about.
- Write aws, then the service name, then the operation (the action word).
- Add each needed flag (--name) followed by its value from the task.
- Flags can be in any order. Click Check answer.
Medium Invoke a function
Invoke runs the function now and saves its answer in a file.
Invoke vidarbhacotton-orders-fn and save the response to out.json.
- Read the task and decide which AWS service it is about.
- Write aws, then the service name, then the operation (the action word).
- Add each needed flag (--name) followed by its value from the task.
- Flags can be in any order. Click Check answer.
Medium Trust policy for a Lambda role
The trust policy says WHO may take the role.
Write a trust policy that lets lambda.amazonaws.com assume the role.
- Start with { "Version": "2012-10-17", "Statement": [ ... ] }.
- In each statement write Effect, Action and Resource.
- Give only what the task needs (least privilege).
- Use double quotes and commas correctly. Click Check answer.
Medium Change timeout and memory
More memory also gives more CPU; timeout stops runaway runs.
Set vidarbhacotton-orders-fn to timeout 30 seconds and memory 512 MB.
- Read the task and decide which AWS service it is about.
- Write aws, then the service name, then the operation (the action word).
- Add each needed flag (--name) followed by its value from the task.
- Flags can be in any order. Click Check answer.
Medium Put an item
DynamoDB JSON shows the type of each value: S for string, N for number.
Put an item into vidarbhacotton-orders with orderId "o-101" (string) and amount 2500 (number).
- Read the task and decide which AWS service it is about.
- Write aws, then the service name, then the operation (the action word).
- Add each needed flag (--name) followed by its value from the task.
- Flags can be in any order. Click Check answer.
Medium Let a function write logs
Without these actions, Lambda logs never appear in CloudWatch.
Allow logs:CreateLogGroup, logs:CreateLogStream, logs:PutLogEvents on arn:aws:logs:*:*:* only.
- Start with { "Version": "2012-10-17", "Statement": [ ... ] }.
- In each statement write Effect, Action and Resource.
- Give only what the task needs (least privilege).
- Use double quotes and commas correctly. Click Check answer.
Hard Let S3 call your function
A resource-based permission is needed before S3 can invoke the function.
Add permission statement s3invoke to vidarbhacotton-orders-fn so s3.amazonaws.com can call lambda:InvokeFunction from bucket arn:aws:s3:::vidarbhacotton-uploads.
- Read the task and decide which AWS service it is about.
- Write aws, then the service name, then the operation (the action word).
- Add each needed flag (--name) followed by its value from the task.
- Flags can be in any order. Click Check answer.
Hard Quick-create an HTTP API for Lambda
Quick create builds an HTTP API, a default route and stage pointing at your function.
Create an HTTP API named vidarbhacotton-api whose target is arn:aws:lambda:ap-south-1:108737854657:function:vidarbhacotton-orders-fn.
- Read the task and decide which AWS service it is about.
- Write aws, then the service name, then the operation (the action word).
- Add each needed flag (--name) followed by its value from the task.
- Flags can be in any order. Click Check answer.
Hard Create a Lambda function
Lambda needs the code zip, a runtime, a handler name and an execution role.
Create function vidarbhacotton-orders-fn: runtime python3.12, handler app.handler, role arn:aws:iam::108737854657:role/lambda-basic, code in function.zip.
- Read the task and decide which AWS service it is about.
- Write aws, then the service name, then the operation (the action word).
- Add each needed flag (--name) followed by its value from the task.
- Flags can be in any order. Click Check answer.
Hard Set environment variables
Keep settings like table names out of the code.
Set the environment variable TABLE=vidarbhacotton-orders on vidarbhacotton-orders-fn.
- Read the task and decide which AWS service it is about.
- Write aws, then the service name, then the operation (the action word).
- Add each needed flag (--name) followed by its value from the task.
- Flags can be in any order. Click Check answer.
Hard Invoke with a JSON payload
In CLI v2, raw JSON needs --cli-binary-format raw-in-base64-out.
Invoke vidarbhacotton-orders-fn with payload {"orderId":"o-101"} (raw JSON) and save the reply in out.json.
- Read the task and decide which AWS service it is about.
- Write aws, then the service name, then the operation (the action word).
- Add each needed flag (--name) followed by its value from the task.
- Flags can be in any order. Click Check answer.
Hard Lambda GB-seconds
Lambda bills memory × time.
1,000,000 invocations, 512 MB memory, 200 ms each. How many GB-seconds?
- Write down the numbers the task gives you.
- Work it out step by step on paper.
- Type only the final answer in the box.
- Click Check answer.
Revision, comparison and interview cards
Revise this lesson in a few minutes. Save the cards on your phone or download them as PNG files. The QR code on each card opens this lesson.






More cards: Ravi Sir's Cards.