Creating a Scalable Serverless Chat Application on AWS
Tags: aws, lambda, cloudcomputing, awschallenge
Published: 2024-07-08 09:59:53

[](url)Today I had used a  AWS serverless services like AWS Lambda and API Gateway to build a chat application in the AWS cloud that can effortlessly scale to meet high demand.

## Prerequisites

-An AWS account with an IAM user that has administrative permissions.

- A basic understanding of a high-level programming language such as Python is recommended but not required.

- Basic understanding of databases and APIs.

- Grit and persistence.

## My Architecture Diagram

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nc3wflw925uzmod33zgm.png)

## Create A Lambda Function
Sign in to the AWS Management Console: Go to the AWS Management Console.

Open the Lambda console: From the AWS Management Console, open the AWS Lambda console by searching for "Lambda" in the services search bar.

Create three function:
Function:1
Click on the "Create function" button.
Choose "Author from scratch".
Configure the following settings:
Function name: Send Message
Runtime: Python 3.x (choose the latest available version)
Role: Choose "Create a new role with basic Lambda permissions"
Click "Create function" to create your Lambda function.

Function:2
Click on the "Create function" button.
Choose "Author from scratch".
Configure the following settings:
Function name: Connect
Runtime: Python 3.x (choose the latest available version)
Role: Choose "Create a new role with basic Lambda permissions"
Click "Create function" to create your Lambda function.

Function:3
Click on the "Create function" button.
Choose "Author from scratch".
Configure the following settings:
Function name: Disconnect
Runtime: Python 3.x (choose the latest available version)
Role: Choose "Create a new role with basic Lambda permissions"
Click "Create function" to create your Lambda function.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4olr2ysbxf33gv8bdhyt.png)

## Create an API
creating an API using API Gateway which is a managed service that makes it fun and easy for developers to create, publish, maintain, monitor, and secure APIs to back-end systems running on EC2, AWS Lambda or any publicly addressable web service

In the API Gateway console, click on the Build button under WebSocket APIs as shown below
You can create a route selection expression like $request.body.action to route messages based on their "action" attribute as we have done in our case. Then, you'd define route actions for different "action" values, such as:

Route Key: sendMessage
Integration: Lambda function to handle the messages
This way, incoming messages will be routed to the appropriate backend Lambda functions based on their “action” attribute. Now let’s go to add routes.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8cnjunjkjkyned4psi4k.png)
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yienqjhyuf7qx8lyvow4.png)
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xn63mtgrgysr64r0pnew.png)

## Add Code to the Lambda Function
Edit the function code:

Scroll down to the "Function code" section.
In the inline code editor, you will see a file named lambda_function.py. This file contains the handler code for your Lambda function.
Write your code: Replace the default code with the following code:
for Send Message

python
Copy code

```
import json
import urllib3
import boto3
client = boto3.client('apigatewaymanagementapi', endpoint_url="xxxxxxxxxx.com/production")

def lambda_handler(event, context):
    print(event)
    #Extract connectionId from incoming event
    connectionId = event["requestContext"]["connectionId"]
    #Do something interesting... 
    responseMessage = "I am fine"
    #Form response and post back to connectionId
    response = client.post_to_connection(ConnectionId=connectionId, Data=json.dumps(responseMessage).encode('utf-8'))
    return { "statusCode": 200  }
```


for connect and disconnect

```
import json

def lambda_handler(event, context):
    print(event)
    print("****")
    print(context)
    return { "statusCode": 200 }


```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yww7rvw488p66gkuj8k5.png)

## Testing our Send Message Route

To make sure our Lambda function is working as integration for our API and a client can send messages, we are going to test our send message route. So go back to [](url)[]{https://piehost.com/websocket-tester} with the WebSocket connection still open and try sending a message in the format:

```
{
  "action": "sendMessage",
  "message": "Hello, how are you?"
}
```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ctqrks1ptrksic1y97r7.png)
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xabshwzp7mlgocg3q91o.png)