We're Live onShow your support by spreading the word on

Building Real-time Chat Applications using AWS Lambda Websocket

Discover how to build real-time chat applications using AWS Lambda and WebSocket. This guide covers setting up serverless architecture for instant messaging.

What is AWS Lambda WebSocket?

AWS Lambda WebSocket allows developers to build scalable, real-time applications without managing servers. By leveraging WebSocket APIs with AWS Lambda, you can create bidirectional communication between clients and servers, ideal for chat applications, live updates, and interactive interfaces. The serverless nature of AWS Lambda ensures automatic scaling and cost-efficiency, as you only pay for what you use. This setup simplifies the development process by eliminating the need for managing infrastructure while providing robust, low-latency communication for modern web applications.

Getting Started with AWS Lambda WebSocket

Lambda WebSocket integrates AWS Lambda, a serverless compute service, with WebSocket, a communication protocol that provides full-duplex communication channels over a single TCP connection. This combination allows developers to build applications that require real-time data transfer without the need for managing infrastructure.
Using Lambda WebSocket, you can create scalable and cost-effective solutions for various use cases, such as live chat applications, real-time notifications, and online multiplayer games.
In this section, we will walk you through the process of setting up your AWS environment, creating a WebSocket API in API Gateway, developing Lambda functions to handle WebSocket events, and deploying your WebSocket API.

Setting Up Your AWS Environment

Before you can start building your Lambda WebSocket application, you need to set up your AWS environment. Here are the prerequisites:
  • An active AWS account
  • AWS CLI installed and configured on your machine
  • Proper IAM roles and permissions

Step-by-Step Instructions of Lambda WebSocket

  1. Create an IAM Role: Navigate to the IAM console, create a new role, and attach the following policies: AWSLambdaFullAccess, AmazonAPIGatewayAdministrator, and AmazonCloudWatchFullAccess.
  2. Configure AWS CLI: Open your terminal and run aws configure. Enter your AWS Access Key, Secret Key, region, and output format.
  3. Set Up Environment Variables: Export necessary environment variables for AWS access in your terminal or add them to your project configuration.

Creating a WebSocket API in API Gateway

To create a WebSocket API in API Gateway, follow these steps:
  1. Open the API Gateway Console: Navigate to the API Gateway service in the AWS Management Console.
  2. Create a New API: Select "Create API" and choose "WebSocket". Enter an API name and description.
  3. Define Routes: Set up routes for $connect, $disconnect, and $default to handle connection events and messages.
  4. Set Up Route Selection Expression: Use route.request.body.action to allow dynamic route selection based on the action specified in the message body.

Example Route Configuration

json

1{
2  "routes": [
3    {
4      "routeKey": "$connect",
5      "target": "arn:aws:lambda:your-region:your-account-id:function:your-lambda-function"
6    },
7    {
8      "routeKey": "$disconnect",
9      "target": "arn:aws:lambda:your-region:your-account-id:function:your-lambda-function"
10    },
11    {
12      "routeKey": "$default",
13      "target": "arn:aws:lambda:your-region:your-account-id:function:your-lambda-function"
14    }
15  ]
16}

Developing Lambda Functions

Developing Lambda functions to handle WebSocket events is the core of your application. Here, we'll write Lambda functions for connection, disconnection, and message handling.

Connection Handler

Python

1import json
2
3def lambda_handler(event, context):
4    connection_id = event['requestContext']['connectionId']
5    return {
6        'statusCode': 200,
7        'body': json.dumps('Connection successful')
8    }

Disconnection Handler

Python

1import json
2
3def lambda_handler(event, context):
4    connection_id = event['requestContext']['connectionId']
5    return {
6        'statusCode': 200,
7        'body': json.dumps('Disconnected successfully')
8    }

Message Handler

Python

1import json
2
3def lambda_handler(event, context):
4    message = json.loads(event['body'])
5    # Process the message here
6    return {
7        'statusCode': 200,
8        'body': json.dumps('Message received')
9    }

Integrating Lambda with WebSocket API

Once you have your Lambda functions ready, you need to integrate them with your WebSocket API routes.

Assign Lambda Functions to Routes

In the API Gateway console, navigate to your WebSocket API and select the routes ($connect, $disconnect, $default). For each route, choose "Integration Request" and set the integration type to "Lambda Function". Select your corresponding Lambda function.

Grant API Gateway Permission to Invoke Lambda

Use the AWS CLI to add permissions for API Gateway to invoke your Lambda functions:

SH

1    aws lambda add-permission --function-name your-lambda-function --statement-id apigateway-test-2 --action lambda:InvokeFunction --principal apigateway.amazonaws.com --source-arn arn:aws:execute-api:your-region:your-account-id:your-api-id/*/$connect

Deploying the WebSocket API

Deploying your WebSocket API involves creating a deployment stage and verifying the deployment.

Create a Deployment

In the API Gateway console, select your WebSocket API, navigate to "Deployments", and create a new deployment. Choose a stage name, such as dev or prod.

Verify Deployment

Use a WebSocket client (e.g., wscat or a browser-based client) to connect to your WebSocket API endpoint. Test the connection, message sending, and disconnection to ensure everything works correctly.

Scaling and Managing Lambda WebSocket

Lambda WebSocket applications automatically scale with demand. However, it's crucial to monitor and manage your application effectively.

Auto-Scaling

AWS Lambda automatically scales based on the number of incoming requests, ensuring your application can handle varying loads without manual intervention.

Monitoring and Logging

Use Amazon CloudWatch to monitor your Lambda functions and API Gateway. Set up metrics and alarms to keep track of performance and errors. Log important events and messages to CloudWatch Logs for debugging and analysis.

Example Project: Real-time Chat Application

Building a real-time chat application is an excellent way to demonstrate the power of Lambda WebSocket. Here's a brief walkthrough:

Front-End Setup

Create a simple HTML and JavaScript front-end that connects to your WebSocket API.

HTML

1    <html>
2    <body>
3      <input type="text" id="messageInput">
4      <button onclick="sendMessage()">Send</button>
5      <div id="messages"></div>
6
7      <script>
8        var socket = new WebSocket('wss://your-api-id.execute-api.your-region.amazonaws.com/dev');
9
10        socket.onmessage = function(event) {
11          document.getElementById('messages').innerHTML += '<p>' + event.data + '</p>';
12        };
13
14        function sendMessage() {
15          var message = document.getElementById('messageInput').value;
16          socket.send(JSON.stringify({ action: 'sendMessage', message: message }));
17        }
18      </script>
19    </body>
20    </html>

Back-End Lambda Functions

Modify the message handler to broadcast messages to all connected clients.

Python

1    import json
2    import boto3
3
4    client = boto3.client('apigatewaymanagementapi', endpoint_url='https://your-api-id.execute-api.your-region.amazonaws.com/dev')
5
6    def lambda_handler(event, context):
7        connection_id = event['requestContext']['connectionId']
8        message = json.loads(event['body']).get('message', '')
9
10        # Retrieve all connection IDs and broadcast the message
11        connection_ids = get_all_connection_ids()  # Implement this function to store and retrieve connection IDs
12        for conn_id in connection_ids:
13            client.post_to_connection(ConnectionId=conn_id, Data=message)
14
15        return {
16            'statusCode': 200,
17            'body': json.dumps('Message sent')
18        }
By following these steps, you'll have a fully functional real-time chat application using Lambda WebSocket.

Get Free 10,000 Minutes Every Months

No credit card required to start.

Conclusion

Lambda WebSocket offers a powerful combination of AWS Lambda's serverless architecture and WebSocket's real-time communication capabilities. By following this guide, you can build scalable, efficient, and responsive applications for various use cases. Explore the potential of Lambda WebSocket to transform your real-time application development.

Want to level-up your learning? Subscribe now

Subscribe to our newsletter for more tech based insights

FAQ