Ravindra BagaleCourses & study guides मराठी Track your progress

AWS Cloud

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.

Chat pathBrowserwss://...API GW WebSocketLambda routesDynamoDB connections + messagespost_to_connectionall clients
Need execute-api:ManageConnections on the API.

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.

  1. Table yourname-chat-conn, PK connectionId.
  2. Table yourname-chat-msg, PK messageId.

B. Lambdas

  1. Three functions from the zip (or one router — lab uses three). Use connect.lambda_handler, disconnect.lambda_handler and message.lambda_handler. Set CONNECTIONS_TABLE on all three. Also set MESSAGES_TABLE on the message Lambda.
  2. 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.

  1. API Gateway → Create WebSocket API. Routes: $connect, $disconnect, sendmessage (route selection expression $request.body.action OR integrate sendmessage as default — lab: set route key sendmessage and client sends {"action":"sendmessage","text":"..."} ). Simpler lab path: use route selection $request.body.action and body action sendmessage.
  2. Deploy stage prod. Copy wss:// URL.
  3. 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

  1. Delete WebSocket API (stages first), three Lambdas, both tables, roles.
  2. 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

  1. Filter broadcast by roomId.
  2. Add a history GET via HTTP API.

In short

  1. WebSocket API + Lambda + DynamoDB connections.
  2. ManageConnections broadcasts.
  3. Handle GoneException.
  4. 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.

Reference documentation

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.

0 of 3 answered correctly
1. A second browser tab opens the same chat. What should identify its connection?

Answer and explanation

C. A new connection ID

A connection ID is attached to a particular WebSocket connection, while message IDs identify saved chat records.

2. The API uses the JSON action field for route selection. Which input selects the sendmessage route?

Answer and explanation

A. A JSON payload with action=sendmessage

The route expression reads the action field from the incoming message and matches its value to a route key.

3. A callback to a closed tab yields GoneException. What does that indicate?

Answer and explanation

B. That stored callback destination is stale

The old connection cannot receive the callback. Keep stored connection records synchronized with active destinations where possible.

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 scenario

Vidarbha 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.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. 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.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. 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.

  1. Start with { "Version": "2012-10-17", "Statement": [ ... ] }.
  2. In each statement write Effect, Action and Resource.
  3. Give only what the task needs (least privilege).
  4. 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.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. 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).

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. 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.

  1. Start with { "Version": "2012-10-17", "Statement": [ ... ] }.
  2. In each statement write Effect, Action and Resource.
  3. Give only what the task needs (least privilege).
  4. 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.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. 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.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. 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.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. 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.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. 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.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. 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?

  1. Write down the numbers the task gives you.
  2. Work it out step by step on paper.
  3. Type only the final answer in the box.
  4. 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.

Revision card: WebSocket chat room. WhatsApp Web and live support need push. Refreshing HTTP every second wastes battery and still feels laggy. API Gateway WebSocket API keeps a connection. Routes $connect, $disconnect, and sendMessage hit Lambda. DynamoDB stores connectionIds and messages. Create WebSocket API, three routes to Lambda, table PK connectionId, tiny HTML client with new WebSocket(wssURL). Two browser tabs connect; one sends hello; both see the message via Management API PostToConnection.
Revision card: WebSocket chat room · Download PNG · Open card page
Revision card: $connect, $disconnect, message. HTTP has one request shape. WebSockets need lifecycle hooks plus your app messages. $connect runs when a client opens the socket — save connectionId. $disconnect removes it. A custom route (e.g. sendMessage) broadcasts. In console: routes $connect, $disconnect, sendMessage → same or separate Lambdas. Deploy stage prod. Copy wss:// invoke URL. On connect, PutItem {connectionId}. On message, Scan/Query connections and post_to_connection each id.
Revision card: $connect, $disconnect, message · Download PNG · Open card page
Revision card: Handle GoneException. Clients leave without a clean $disconnect (closed laptop). Stale connectionIds break broadcasts. PostToConnection on a dead id raises GoneException (410). Delete that connectionId and continue. try/except around post_to_connection; on GoneException delete the DynamoDB row for that connectionId. Broadcast to 5 ids where 1 is stale → 4 get the chat line; stale row is removed automatically.
Revision card: Handle GoneException · Download PNG · Open card page
Comparison: HTTP API vs WebSocket API. HTTP API: One request, one response. WebSocket API: Long-lived push connection.
Comparison: HTTP API vs WebSocket API · Download PNG · Open card page
Interview card: WebSocket vs HTTP polling for chat?. WebSocket keeps a push channel; polling hammers the API and still adds latency. API Gateway WebSocket routes lifecycle and messages to Lambda. wss://…/prod clients; PostToConnection pushes to stored connectionIds.
Interview card: WebSocket vs HTTP polling for chat? · Download PNG · Open card page
Interview card: What is GoneException in WebSocket APIs?. PostToConnection to a closed client returns 410 Gone. Delete that connectionId from DynamoDB and continue broadcasting to others. except ClientError/GoneException: delete_item(Key=connectionId).
Interview card: What is GoneException in WebSocket APIs? · Download PNG · Open card page

More cards: Ravi Sir's Cards.