<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by VenuVereY on Medium]]></title>
        <description><![CDATA[Stories by VenuVereY on Medium]]></description>
        <link>https://medium.com/@asarellyvenuverey?source=rss-f59d79817a13------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*UJUlnF_0bF0ZYX7O</url>
            <title>Stories by VenuVereY on Medium</title>
            <link>https://medium.com/@asarellyvenuverey?source=rss-f59d79817a13------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 03:23:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@asarellyvenuverey/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Real-time Made Simple: Using WebSocket API Gateway with Node.js on AWS]]></title>
            <link>https://medium.com/@asarellyvenuverey/real-time-made-simple-using-websocket-api-gateway-with-node-js-on-aws-a189f40d2930?source=rss-f59d79817a13------2</link>
            <guid isPermaLink="false">https://medium.com/p/a189f40d2930</guid>
            <category><![CDATA[api-gateway]]></category>
            <category><![CDATA[dynamodb]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[websocket]]></category>
            <dc:creator><![CDATA[VenuVereY]]></dc:creator>
            <pubDate>Fri, 11 Apr 2025 09:01:50 GMT</pubDate>
            <atom:updated>2025-04-14T07:03:00.874Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>In modern web applications, real-time updates have become essential — especially for scenarios like food ordering, ride tracking, or dashboards. Instead of constantly refreshing the page or polling the server every few seconds, WebSockets provide an efficient, event-driven way to push updates from the server to the client instantly.</blockquote><p>In this blog, we’ll walk through how to implement <strong>WebSocket communication using AWS API Gateway and Node.js</strong>, specifically for a real-world use case: <strong>showing new orders in real-time on an admin website</strong>.</p><p>Imagine a restaurant receiving online orders from customers. As soon as a new order is placed, the admin dashboard should reflect it immediately without needing a refresh. We’ll use AWS WebSocket API Gateway to handle the real-time connection and trigger AWS Lambda functions in the backend to manage connections and broadcast new orders.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0j9Bi-6SFGs5k4Flcj19UA.png" /></figure><h3>What are WebSockets?</h3><p><strong>WebSockets</strong> are a communication protocol that allows for <strong>two-way, real-time interaction between a client (like a browser) and a server</strong> over a single, long-lived connection.Unlike traditional HTTP, where the client has to send a request every time it needs data (request-response model), <strong>WebSockets keep the connection open</strong>, so the server can send updates <strong>instantly</strong> to the client whenever something happens — without the client asking.</p><h3>Why use WebSockets over REST for real-time communication?</h3><h3>Instant Updates</h3><p>With REST, the client must keep asking, “Any new data? Any now? How about now?” With WebSockets, the server <strong>pushes updates automatically</strong> the moment something changes. Ideal for : Chats, dashboards, notifications, online games, live orders.</p><h3>Two-Way Communication</h3><p>REST is request-response only. The <strong>server can’t talk to the client unless the client asks</strong>. WebSockets allow both client and server to talk freely at any time.</p><h3>WebSocket Architecture Overview</h3><h3>🧭 Flow:</h3><p><strong>WebSocket API Gateway ↔️ AWS Lambda ↔️ Database (PostgreSQL / DynamoDB)</strong></p><ul><li><strong>WebSocket API Gateway</strong></li><li>Manages all WebSocket connections.</li><li>Routes messages to specific Lambda functions based on route keys like:</li><li>$connect – when a client connects</li><li>$disconnect – when a client disconnects</li><li>sendMessage (or custom route) – when a client sends a message</li><li><strong>AWS Lambda</strong></li><li>Executes your business logic:</li><li>Stores connection IDs when clients connect</li><li>Removes them when disconnected</li><li>Sends messages to specific clients via the connectionId</li><li>Uses ApiGatewayManagementApi to send messages back through the WebSocket</li><li><strong>Database (PostgreSQL / DynamoDB)</strong></li><li>Stores active connection IDs with related metadata (e.g., user ID, role)</li><li>Allows querying connection IDs when sending messages to targeted users/admins</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z0UBWpPqmsO72NqORLK6Tw.png" /></figure><h3>This is a clean and production-ready Node.js function that <strong>broadcasts messages to all connected WebSocket clients using AWS API Gateway and DynamoDB</strong>.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*DQbm31m90gKBPG-zsJfb_Q.png" /></figure><p>Here’s the command to install all the required dependencies for your WebSocket broadcast setup:</p><blockquote>npm install <a href="http://twitter.com/aws">@aws</a>-sdk/client-dynamodb <a href="http://twitter.com/aws">@aws</a>-sdk/client-apigatewaymanagementapi dotenv</blockquote><pre>Importing Required AWS SDK Clients<br>const {<br> DynamoDBClient,<br> ScanCommand,<br> DeleteItemCommand,<br>} = require(“@aws-sdk/client-dynamodb”);</pre><p>We import necessary DynamoDB clients:</p><ul><li>DynamoDBClient – to interact with DynamoDB.</li><li>ScanCommand – to retrieve all items (connections) from the table.</li><li>DeleteItemCommand – to remove stale/disconnected connections.</li></ul><pre>const {<br> ApiGatewayManagementApiClient,<br> PostToConnectionCommand,<br>} = require(“@aws-sdk/client-apigatewaymanagementapi”);</pre><p>These are used to <strong>send messages back to connected clients</strong> via WebSocket.</p><ul><li>ApiGatewayManagementApiClient – the WebSocket management interface.</li><li>PostToConnectionCommand – sends a message to a specific connection.</li></ul><pre>const REGION = process.env.AWS_REGION;<br>const TABLE_NAME = process.env.DYNAMO_TABLE_NAME;<br>const WEBSOCKET_ENDPOINT = process.env.WEBSOCKET_ENDPOINT;</pre><p>Configure DynamoDB Client</p><pre>const dynamoClient = new DynamoDBClient({<br> region: REGION,<br> credentials: {<br> accessKeyId: process.env.AWS_ACCESS_KEY_ID,<br> secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,<br> },<br>});</pre><ul><li>This sets up a DynamoDB client using your region and credentials.</li><li>Used to <strong>read and delete</strong> WebSocket connection IDs from the DynamoDB table.</li></ul><pre>Configure WebSocket Client<br>const wsClient = new ApiGatewayManagementApiClient({<br> region: REGION,<br> endpoint: WEBSOCKET_ENDPOINT,<br> credentials: {<br> accessKeyId: process.env.AWS_ACCESS_KEY_ID,<br> secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,<br> },<br>});</pre><ul><li>This is the AWS client to <strong>push messages</strong> to the connected clients via WebSocket.</li><li>WEBSOCKET_ENDPOINT is usually something like:<br> <a href="https://your-api-id.execute-api.region.amazonaws.com/prod">https://your-api-id.execute-api.region.amazonaws.com/prod</a></li></ul><h3>Broadcast Function: Send Messages to All Clients</h3><pre>const sendMessageToAllConnections = async (payload) =&gt; {<br> try {<br> const scanCommand = new ScanCommand({ TableName: TABLE_NAME });<br> const data = await dynamoClient.send(scanCommand);<br> const connections = data.Items;<br>for (const connection of connections) {<br> const connectionId = connection.connection_id.S<br>try {<br> const postCommand = new PostToConnectionCommand({<br> ConnectionId: connectionId,<br> Data: Buffer.from(JSON.stringify(payload)),<br> });<br>await wsClient.send(postCommand);<br> } catch (err) {<br> if (err.statusCode === 410) {<br> // Stale connection - remove it from DynamoDB<br> await dynamoClient.send(<br> new DeleteItemCommand({<br> TableName: TABLE_NAME,<br> Key: { connection_id: { S: connectionId } },<br> })<br> );<br> } else {<br> console.error(`⚠️ Error sending to ${connectionId}:`, err);<br> }<br> }<br> }<br> } catch (err) {<br> console.error(&quot;❌ Error broadcasting WebSocket message:&quot;, err);<br> }<br>};</pre><h3>Conclusion</h3><p>Integrating WebSocket API Gateway with AWS Lambda and DynamoDB allows you to build a <strong>scalable, real-time communication system</strong> without managing your own WebSocket server. This is especially useful for applications like admin dashboards, order tracking, notifications, chats, and live updates.</p><p>In this blog, we:</p><ul><li>Understood what WebSockets are and <strong>why they are preferred over REST</strong> for real-time data.</li><li>Built a Lambda function to <strong>broadcast messages to all active clients</strong> using sendMessageToAllConnections.</li><li>Cleaned up <strong>stale WebSocket connections</strong> from DynamoDB.</li><li>Leveraged AWS services like API Gateway, Lambda, and DynamoDB for a fully serverless and maintainable architecture.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a189f40d2930" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>