0Pricing
Serverless Backend with AWS Lambda & API Gateway · Lesson

WebSocket APIs for Real-Time Communication

Build two-way, real-time connections with API Gateway WebSocket APIs. Learn the connect, disconnect, and message routes and how to push data back to clients.

WebSocket APIs for Real-Time Communication is a free Serverless Backend with AWS Lambda & API Gateway lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Serverless Backend with AWS Lambda & API Gateway learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Why WebSockets?

REST APIs are request/response — the server cannot push. For chat, live dashboards, or notifications you need a persistent two-way channel. API Gateway WebSocket APIs provide exactly that.

The Three Built-in Routes

A WebSocket API has special routes:

  • $connect when a client connects
  • $disconnect when it leaves
  • $default for unmatched messages

Route Selection Expression

Custom routes are chosen by a route selection expression, usually a field in the incoming JSON such as $request.body.action.

{
  "action": "sendMessage",
  "data": "hello"
}

Handling $connect

The $connect handler receives a unique connectionId. Store it (e.g. in DynamoDB) so you can message that client later.

exports.handler = async (event) => {
  const id = event.requestContext.connectionId;
  await save(id);
  return { statusCode: 200 };
};

Handling $disconnect

On disconnect, remove the stored connectionId so you do not try to message a dead client.

exports.handler = async (event) => {
  await remove(event.requestContext.connectionId);
  return { statusCode: 200 };
};

Pushing Messages to a Client

To send data back, call the management API with the target connectionId.

const api = new ApiGatewayManagementApi({ endpoint });
await api.postToConnection({
  ConnectionId: id,
  Data: JSON.stringify({ msg: "hi" })
});

Broadcasting to Many Clients

To broadcast, loop over all stored connectionIds and post to each. Remove any that return a 410 Gone status — those clients have disconnected.

Authorizing Connections

Attach a Lambda authorizer to the $connect route to validate a token before the connection is accepted, rejecting unauthorized clients up front.

Connection Lifetime and Limits

WebSocket connections last up to 2 hours, with a 10-minute idle timeout. Clients should reconnect when dropped, and you should handle stale connectionIds gracefully.

Pricing Model

You pay for messages transferred and for connection-minutes, not for idle request count. This makes WebSocket APIs cost-effective for bursty real-time traffic.

When to Use WebSockets

Reach for WebSocket APIs when you need:

  • Live chat or collaboration
  • Real-time dashboards
  • Server-initiated notifications

For simple request/response, stick with REST or HTTP APIs.

Quick Check

Test your WebSocket API knowledge.

Recap

You learned real-time APIs:

  • WebSocket APIs add two-way communication
  • $connect, $disconnect, $default plus custom routes
  • Store connectionIds and push via postToConnection
  • Authorize on $connect; handle stale connections

Frequently asked questions

Is the “WebSocket APIs for Real-Time Communication” lesson free?

Yes — the full text of “WebSocket APIs for Real-Time Communication” is free to read here on the web, and the Serverless Backend with AWS Lambda & API Gateway course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Serverless Backend with AWS Lambda & API Gateway course, upgrade to CoddyKit PRO.

What will I learn in “WebSocket APIs for Real-Time Communication”?

Build two-way, real-time connections with API Gateway WebSocket APIs. Learn the connect, disconnect, and message routes and how to push data back to clients. You practise Serverless Backend with AWS Lambda & API Gateway with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Serverless Backend with AWS Lambda & API Gateway?

No prior experience is required. Serverless Backend with AWS Lambda & API Gateway on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “WebSocket APIs for Real-Time Communication” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Serverless Backend with AWS Lambda & API Gateway lesson?

Yes. Every Serverless Backend with AWS Lambda & API Gateway lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Caching and Throttling
  2. Request/Response Transformations
  3. Custom Domain Names & Edge Optimization
  4. WebSocket APIs for Real-Time Communication
← Back to Serverless Backend with AWS Lambda & API Gateway