Serverless · Freelance

Build a Realtime WebSocket App with API Gateway, Lambda and DynamoDB

A serverless realtime word-cloud and live-feed backend: API Gateway WebSocket routes, Lambda handlers, and a DynamoDB connection registry used for fan-out broadcasts.

  • API Gateway WebSocket
  • AWS Lambda
  • DynamoDB
  • Python
  • boto3
  • IAM
  • CloudWatch
  • AWS SAM

// Why this matters

A websocket api gateway lambda design is the cheapest way to add realtime behaviour to an application that is otherwise idle most of the day. Live word clouds, audience polls and activity feeds all share one trait: bursts of traffic around an event, then silence. Paying for an always-on socket server for that shape of load is wasteful, and so is the operational work of scaling and patching it.

From the engineering side, serverless sockets remove the hardest part of realtime systems, which is holding tens of thousands of open TCP connections. API Gateway terminates and holds the sockets. Your code runs only when a frame arrives or a client connects or disconnects. That changes the problem from capacity planning into data modelling: who is connected, and what do they need to be told.

I built this pattern for realtime word-cloud and live-feed applications. The technique is small enough to reproduce in an afternoon, and it generalises to chat, dashboards and collaborative tools.

// The problem

Plain request/response APIs cannot push. Polling works at small scale but multiplies request volume and still shows stale data between polls. Once an audience of a few hundred people is typing words into a shared screen, polling at one-second intervals produces a flood of mostly empty requests and a visibly laggy cloud.

WebSockets fix the delivery side but create a state problem. A Lambda function is stateless and short-lived, so it cannot remember who is connected. Two invocations that handle two different clients share no memory, yet one of them has to tell the other client about a new word. Without a shared registry of connections, broadcast is impossible.

There are also failure modes that only show up under real use. Clients close tabs without a clean disconnect, mobile networks drop sockets silently, and a broadcast loop that does not handle dead connections will either throw or keep retrying them forever. Concurrency is the last trap: if two handlers read a count, add one, and write it back, increments are lost.

// The solution

The architecture has three parts: an API Gateway WebSocket API with a route selection expression, a single Lambda function (or one per route) that implements the routes, and two DynamoDB tables. The route selection expression is set to $request.body.action, so a frame like {"action":"word","text":"cloud"} is dispatched to the route named word. The reserved routes $connect, $disconnect and $default handle the lifecycle and anything unmatched.

The connections table is keyed by connection ID, with a numeric ttl attribute that DynamoDB expires automatically. This is the registry. On $connect we put an item, on $disconnect we delete it, and the TTL is a safety net for sockets that vanish without a disconnect event. API Gateway has a hard two-hour connection limit anyway, so a TTL a little longer than that never leaves orphans for long.

The word table is keyed by the normalised word. The handler uses an UpdateItem with an ADD expression, which DynamoDB applies atomically on the server. That removes the read-modify-write race entirely, and it is cheaper than a conditional write loop.

Broadcast happens inline in the word handler. After updating the count it scans the connections table and calls post_to_connection for each ID using the API Gateway management client, whose endpoint is the stage URL with https. When the call raises GoneException (HTTP 410), the connection no longer exists and we delete its record. This self-cleaning behaviour means no separate sweeper is needed.

Alternatives I considered: a Redis pub/sub backed server on containers (more moving parts and a fixed cost), AWS IoT Core over MQTT (excellent for devices but awkward for browser-first apps), and AppSync subscriptions (great if you already use GraphQL). For a plain JSON-over-socket app with spiky traffic, the native WebSocket API is the simplest option. If you later need very large fan-out, move the broadcast into an SQS or SNS driven worker so one slow client cannot delay the others; see Event-driven Call-Recording Transcoding and Transcription for the queue-driven pattern.

How it flows flow1. Client connects → 2. $connect route → 3. Client sends message → 4. Route selection → 5. Aggregate → 6. Scan connections → 7. Broadcast → 8. Stale check → 9. $disconnect route01Client connects02$connect route03Client sends message04Route selection05Aggregate06Scan connections07Broadcast08 · GATEStale check09$disconnect route
How it flows. End-to-end flow. Dashed pink nodes are gates: points where a human or a check must pass before the next stage runs.
  1. Client connectsbrowser opens a wss:// connection to the API stage
  2. $connect routeLambda writes the connection ID into DynamoDB with a TTL
  3. Client sends messageJSON frame such as {"action":"word","text":"hello"} hits a custom route
  4. Route selectionAPI Gateway matches the action field and invokes the handler
  5. Aggregatehandler increments the word counter atomically in DynamoDB
  6. Scan connectionshandler lists active connection IDs
  7. Broadcastpost_to_connection sends the new totals to every client
  8. Stale check gatea 410 Gone response means the client left, so the record is deleted
  9. $disconnect routeLambda removes the connection record
Client AAPI GatewayLambdaDynamoDBClient Bwss connect$connect eventput connection id + ttlframe action=wordinvoke word routeADD count (atomic)scan connection idspost_to_connection per idpush new totals
Message and broadcast lifecycle. How one client message results in updates for every connected client.
ClientsBrowser word cloudLive feed viewerAdmin screenEdgeAPI Gateway WebSocketRoute selectionStage + throttlingComputeconnect handlerword handlerdisconnect handlerStateconnections tableword counts tableTTL cleanup
Architecture layers. Managed edge, stateless compute, and two small tables.

// Before you start

  • An AWS account and a role or user able to create API Gateway, Lambda, DynamoDB and IAM resources
  • AWS CLI v2 and AWS SAM CLI 1.100 or later configured for your target <region>
  • Python 3.12 and boto3 for the Lambda handler
  • wscat (npm i -g wscat) or any websocket client for testing
  • Basic familiarity with IAM policies and DynamoDB key design

// Step-by-step implementation

  1. 01 Create the two DynamoDB tables

    Start with state, because every route depends on it. The connections table needs only a partition key on the connection ID. Enable TTL on the ttl attribute so abandoned records disappear without any code. The words table is keyed on the word itself.

    Use on-demand billing for both. Traffic is bursty, and provisioned capacity would either throttle during an event or sit idle the rest of the time.

  2. 02 Declare the WebSocket API and its routes

    The API resource needs a route selection expression. We key on an action field in the JSON body, which keeps the client protocol explicit and extensible. Each route is a pair: an integration pointing at Lambda and a route that references it.

    Do not forget the Lambda permission that lets API Gateway invoke the function; without it the routes return 500 and the logs show nothing useful.

  3. 03 Grant least-privilege IAM to the function

    The handler needs three things: read and write on the two tables, and permission to call the execute-api management endpoint to push frames. Scope the execute-api permission to the specific API and stage rather than a wildcard.

    ManageConnections is the action that covers PostToConnection and DeleteConnection.

  4. 04 Write the connect and disconnect handlers

    The connect handler stores the ID and an expiry timestamp. Choose a TTL slightly above the API Gateway two-hour connection limit. The disconnect handler removes the record. Both return a plain status code; API Gateway ignores the body for these routes.

    One routing function dispatches on the route key from the request context, so a single Lambda serves every route.

  5. 05 Aggregate words with an atomic update

    Normalise input first: lowercase, trim, cap the length, and reject empty strings. Then use UpdateItem with ADD so DynamoDB increments server-side. ReturnValues lets you avoid a second read.

    This is the line that makes the system correct under concurrency. Two clients sending the same word in the same millisecond both get counted.

  6. 06 Broadcast to every client and prune dead sockets

    The management client is built from the stage URL. API Gateway puts the domain and stage in the request context, so no configuration is needed. For each stored ID, call post_to_connection. A GoneException means the socket is closed: delete the record and move on.

    Scan is acceptable for hundreds or low thousands of connections. For larger audiences, page through results, or shard broadcast across workers via SQS.

  7. 07 Build, deploy and open a socket

    SAM builds the package and creates the stack. The deployed WebSocket URL is in the stack outputs, or you can assemble it from the API ID, region and stage name. Then connect with wscat and send a frame.

    Open two terminals so you can watch a message from one appear in the other.

// How to verify it works

  • Run wscat in two terminals; sending {"action":"word","text":"hello"} in one should print a cloud frame containing hello in both.
  • Scan the connections table: you should see exactly one item per open socket, each with a ttl value in the future.
  • Close one wscat session and rescan: the item disappears from the table on $disconnect.
  • Send the same word from several clients quickly and confirm the stored count equals the number of sends.
  • Kill a client with Ctrl+Z so no disconnect is sent, broadcast again and watch the CloudWatch logs delete the stale record after a GoneException.

// Design decisions and trade-offs

  • Store connection IDs in DynamoDB with a TTL instead of keeping any state inside Lambda
  • Broadcast from the same function that receives a message, and prune stale connections on 410 Gone
  • Aggregate word counts with an atomic DynamoDB update expression rather than read-modify-write
  • Deploy with SAM so routes, integrations and permissions live in one reviewable template
  • Keep one table per concern: connections and word counts, each with its own capacity mode

// Pitfalls and lessons learned

  • Forgetting lambda:InvokeFunction permission for API Gateway produces 500s with an empty Lambda log group, which looks like a code bug.
  • Using the wrong management endpoint (the wss:// URL or no stage) causes ForbiddenException or 403 on post_to_connection; it must be https plus the stage.
  • Doing read-modify-write for counters silently loses increments under load. Use ADD.
  • An unhandled error inside the broadcast loop aborts delivery to every later client. Catch per connection.
  • The $connect route is the only place to reject a client (return 403), and it runs before any frame. Put any auth check there, not in message routes.
  • Idle timeouts close sockets after ten minutes of silence, so have the client send a ping frame periodically.

// Frequently asked questions

How do I build a websocket api gateway lambda app without a server?

Create an API Gateway WebSocket API, define $connect, $disconnect and custom routes that proxy to Lambda, and keep connection IDs in DynamoDB. Lambda pushes data back through the management API.

How do I send a message to all connected clients?

Read every connection ID from your registry and call post_to_connection for each. Delete records that return 410 Gone.

Why do I need DynamoDB at all?

Lambda is stateless and API Gateway does not expose a list of open connections, so you must keep your own registry to broadcast.

How many connections can this handle?

API Gateway scales the connections for you; the practical limit is the time your broadcast loop takes. Beyond a few thousand clients, fan out through a queue.

Can I authenticate WebSocket clients?

Yes. Attach a Lambda authorizer to the $connect route and pass a token in the query string or a header during the handshake.

// The outcome

The backend scales to zero between events and needs no servers to patch. Clients get updates over a single persistent socket, and the only operational concern left is pruning dead connections, which is handled in the broadcast path itself.

// Where to take it next

  • Add a Lambda authorizer on $connect and per-room partitioning of the connections table.
  • Move broadcast to an SQS-driven worker to handle larger audiences, as in Serverless Video-on-Demand with MediaConvert, CloudFront and Cognito.
  • Add CloudWatch alarms on the Lambda error rate and on throttles for the API stage.
  • Replace the table scan with a global secondary index keyed by room.

// Keep reading