With AWS AppSync and DynamoDB, this post demonstrates how to build a real-time, serverless chat service with high availability, low delay, and scalability.
Modern apps need to be able to talk to each other in real time, whether they’re for customer service, games, or working together as a team. In the past, making these kinds of apps meant keeping up with WebSocket servers and other complicated systems. However, AWS AppSync, which is driven by GraphQL subscriptions, makes it easy to make real-time apps.
You will learn the following in this lesson:
Learn how to set up AWS AppSync to handle messages in real time.
This article explains how to store messages in DynamoDB, a NoSQL database that can grow as needed.
This article explains how to use AWS Lambda to build your own business code.
This article explains how to use React to make a simple front end that talks to the chat back end.
By the end of this tutorial, you’ll have a serverless chat app that works perfectly and can handle many people at once.
Why doesn’t a chat app need a server?
Conventional chat apps need a WebSocket server to control connections, transmit messages, and keep state. These require their systems and careful scaling. Conversely, a serverless method provides the following benefits:
Scalability: AWS handles scaling based on how many people are using the service at any given time.
You incur fewer operational expenses because you don’t have to manage or maintain WebSocket servers.
Cost-effectiveness: Since you only pay for what you use, it’s a fantastic deal.
Real-time GraphQL subscriptions are available through AWS AppSync, so you don’t have to handle WebSockets. DynamoDB makes sure that storage is fast, highly available, and needs little setup.
Step 1: Setting Up AWS AppSync
The outcome is a controlled GraphQL service called AWS AppSync that lets clients and a backend share data in real time.
Make an API for AWS AppSync.
- To make a new API, go to AWS AppSync.
- Pick “Build from scratch” and GraphQL.
- Please consider naming your API something like “ChatAppSyncAPI.”
Set up the GraphQL schema.
It tells our chat app how to handle data using the GraphQL model. Go to Schema in AWS AppSync and set the following:
type Message {
id: ID!
sender: String!
content: String!
timestamp: AWSDateTime!
chatRoomId: ID!
}
type Subscription {
onNewMessage(chatRoomId: ID!): Message
@aws_subscribe(mutations: ["sendMessage"])
}
type Mutation {
sendMessage(chatRoomId: ID!, sender: String!, content: String!): Message
}
type Query {
getMessages(chatRoomId: ID!): [Message]
}
This schema allows users to send and receive messages in real time.
Step 2: Configuring DynamoDB for Storage
Amazon Designed as a completely controlled NoSQL database, DynamoDB guarantees excellent speed with very minimal configuration.
Create a DynamoDB database.
- Pick out DynamoDB.
- Create a table by clicking Click.
- The main key should be the chosen ID.
- Enable Auto Scaling to adjust capacity dynamically.
Set up AppSync using DynamoDB.
- Visit Data Sources and add DynamoDB as a new data source to connect it to AppSync.
- Choose the one you created.
Let AppSync connect via IAM to DynamoDB.
Configure Resolvers.Map Send messages to DynamoDB, adding data.
Plan Map: Get your chat logs with the getMessages search.
Step 3: Implementing Business Logic with AWS Lambda
AWS Lambda lets us modify program logic in ways DynamoDB cannot.
Generate a Lambda function.
Get to AWS Lambda and create a fresh function.
Run Pick Node.JS 18 at that point.
Working with DynamoDB requires you to be granted execution rights.
Write the Lambda Function
const AWS = require('aws-sdk');
const dynamoDb = new AWS.DynamoDB.DocumentClient();
exports.handler = async (event) => {
const { chatRoomId, sender, content } = event.arguments;
const timestamp = new Date().toISOString();
const message = { id: `${Date.now()}`, chatRoomId, sender, content, timestamp };
await dynamoDb.put({
TableName: 'ChatMessages',
Item: message
}).promise();
return message;
};
Link AppSync with Lambda.
Create a Lambda data source by visiting Data Sources in AppSync.
Include this code within sendMessage.
Step 4: React will help you to create the front end.
We construct the frontend with React and AWS Amplify.
- Install AWS Amplify
npm install aws-amplify @aws-amplify/ui-react
- Configure Amplify
import Amplify from 'aws-amplify';
import config from './aws-exports';
Amplify.configure(config);
. Implement Chat Interface
import { API, graphqlOperation } from 'aws-amplify';
import { onNewMessage } from './graphql/subscriptions';
import { sendMessage } from './graphql/mutations';
const Chat = () => {
const [messages, setMessages] = useState([]);
const [newMessage, setNewMessage] = useState("");
useEffect(() => {
const subscription = API.graphql(graphqlOperation(onNewMessage))
.subscribe({
next: ({ value }) => {
setMessages([...messages, value.data.onNewMessage]);
}
});
return () => subscription.unsubscribe();
}, [messages]);
const handleSend = async () => {
await API.graphql(graphqlOperation(sendMessage, { sender: "User", content: newMessage, chatRoomId: "1" }));
setNewMessage("");
};
return (
<div>
{messages.map(msg => <p key={msg.id}>{msg.sender}: {msg.content}</p>)}
<input value={newMessage} onChange={(e) => setNewMessage(e.target.value)} />
<button onClick={handleSend}>Send</button>
</div>
);
};
Step 5: Deploying the Application
To make the chat app work:
Setting up the front end
To set up the React website, use either AWS Amplify Hosting or Vercel.
Deploying the back end
Use AWS CloudFormation to set up AppSync and Lambda.
Conclusion:
We were able to use AWS to build a real-time chat app that doesn’t need a server. We got rid of the need to handle WebSockets by using AppSync, DynamoDB, and Lambda. These improvements made our solution more scalable and cost-effective.
Main Points
- AWS AppSync lets you subscribe to GraphQL in real time.
- DynamoDB makes sure that your data store is flexible and always available.
- AWS Lambda adds business logic and makes features bigger.
- AWS Amplify makes it easy to integrate the front end.
You can find more reading on the official AWS instruction page:
Top comments (0)