AWS Builder Center
How To Add Real-Time Messaging To AWS Architecture

How To Add Real-Time Messaging To AWS Architecture

Learn how to add real time messaging to your AWS architecture without starting from scratch. A clear guide that shows you how to install a pre-built chat SDK on your AWS-hosted application including setup, API integration, and message delivery at scale. Perfect for those developers who want to add real-time communication features to existing AWS products quickly and reliably.

Freelance Writer & Digital Marketer
In this guide, I’ll  walk you through the steps to build a messaging infrastructure for business apps that run on AWS. There are two ways to do this:
  1. Write the code from scratch to build the sockets, message queues, media pipelines and message servers.
  1. Use a SDK that already contains pre-built codes for implementing the messaging functionality.

Architecture Overview

In the AWS architecture, the following components help build the messaging infrastructure, with the third-party chat engine as a primary messaging layer.
Layer
AWS Service
Mobile Client
Android App (Chat SDK)
Entry
Application Load Balancer
Compute
Amazon EKS 
Chat Engine
Third-Party SDK Services
Database
Amazon RDS
Cache
ElastiCache Redis
Object Storage
Amazon S3
Networking
VPC + Security Groups
The reason I’m going with EKS ((Elastic Kubernetes Service) instead of a plain EC2 is because Kubernetes can scale the chat service pods horizontally when the traffic spikes, and can restart instantly when WebSocket connection crashes. For daily communication, EKS is a component you can rely on. 

Chat Service Installation Into The AWS Infrastructure 

Part I: AWS Setup

Setting up AWS for building a messaging infrastructure involves 3 steps:

Step 1: Create a secure VPC

A VPC (Virtual Private Cloud) is a business’s own private network within AWS cloud. The reason you’ll need a VPC here is that the chat data stays under your control without exposure to the public internet. 
To do this
  • Login to your AWS Management Console
  • Search for VPC. Under services, pick VPC
  • Click the Create VPC button.
Create a secure VPC

  • Under Resources to create, select VPC and more,
  • Configure the VPC Wizard settings, set up Subnets, Route tables, and Network connections. 
  • Review the visual architecture
  • Click on Create VPC at the bottom of the page
  • Wait for green checkmarks, and then click View VPC.

Step 2: Launch Kubernetes (Amazon EKS)

Once the VPC is set up, set up EKS using the command-line utility eksct1. The steps involve:
  • Go to the AQS CLI Official page & download the tool
  • Open the local terminal 
  • Login and connect your workspace to the AWS environment.
aws configure
  • Go to Kuberneted Documentation
  • Install Kubernetes CLI
  • Go to eksctl site
  • Download and install the EKS utility tool
  • Run the eksctl create cluster command
eksctl create cluster \
--name my-eks-cluster \
--region us-east-1 \
--nodegroup-name standard-workers \
--node-type t3.medium \
--nodes 3 \
--managed

This creates a group of EC2 worker nodes and a managed control plane. 
  • Test the cluster connectivity
kubectl get nodes
  • Check the network routing functions by deploying a sample workload.
kubectl create deployment web-app --image=nginx

Step 3: Configure Supporting Storage Services

Once the EKS is set up, set up the storage services where your database will be managed. 
Use the following AWS services;
  • Amazon RD (PostgresSQL) to manage user & message data.
  • Amazon ElastiCache (Redis) for session & presence cache.
  • Amazon S3 for media & file attachments.
  • Amazon CloudWatch for logging and monitoring.

Step 4: Install & Configure The Chat Backend Service

Get a chat service from providers like MirrorFly, Sendbird or CometChat. 
  • Install the dependencies.
sudo apt-get update && sudo apt-get upgrade -y
sudo apt-get install docker.io docker-compose -y
  • Upload the Docker compose files and the chat SDK’s server application binaries directly into the server. 
  • Configure the environment file as provided by the chat service. This includes the AWS RDS endpoint and credentials, S3 configurations and SSL/TLS paths and deployment token. 
  • Use a Docker daemon or a configuration manager to start the backend platform service.
docker-compose up -d

Part II: Android Integration With Chat SDK

For demonstration purposes I’ve used MirrorFly as the chat service in this section. 

Step 1: Add Repository

  • Go to settings.gradle
  • Add the repo to the gradle file
dependencyResolutionManagement {
repositories {
mavenCentral()
google()
jcenter()
maven {
url "https://repo.mirrorfly.com/release"
}
}
}

Step 2: Add the SDK Dependency

In the build gradle file, add the below code.
dependencies {
implementation 'com.mirrorfly.sdk:mirrorflysdk:7.13.32'
}

Step 3: Enable Jetifier

To avoid library conflicts, enable Jetifier in the gradle properties.
android.enableJetifier=true

Step 4: Add Permissions

In the manifest file, add the following internet permissions.
android.enableJetifier=true

Step 5: Initialize The SDK

Go to the onCreate() method of your Application class, and initialize the SDK as below.
ChatManager.initializeSDK("LICENSE_KEY", (isSuccess, throwable, data) -> {
if (isSuccess) {
Log.d("TAG", "initializeSDK success");
} else {
Log.d("TAG", "initializeSDK failed with reason " + data.get("message"));
}
});
Then register your Application subclass in AndroidManifest.xml:
<application
android:name=".MyApplication"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

Step 6: Register a User

FlyCore.registerUser(USER_IDENTIFIER, (isSuccess, throwable, data) -> {
if (isSuccess) {
Boolean isNewUser = (Boolean) data.get("is_new_user");
String userJid = (String) data.get("userJid");
JSONObject responseObject = (JSONObject) data.get("data");
String username = responseObject.getString("username");
} else {
// registration failed — inspect throwable for details
}
});

Step 7: Connect & Observer Connection Events

ChatManager.setConnectionListener(new ChatConnectionListener() {
@Override
public void onConnected() {
// navigate to profile page / start chatting
}
@Override
public void onDisconnected() {
// connection lost
}
@Override
public void onConnectionFailed(@NonNull FlyException e) {
// auth failure or unable to connect
}
@Override
public void onReconnecting() {
// automatic reconnection in progress
}
});

Step 8: Generate User JID
FlyUtils.getJid(USER_NAME)
Step 9: Send One-to-One Message
TextMessage textMessage = new TextMessage();
textMessage.setToId(TO_JID);
textMessage.setMessageText(TEXT);
FlyMessenger.sendTextMessage(textMessage, (isSuccess, error, chatMessage) -> {
if (isSuccess) {
// you will get the message sent success response
}
});


Step 10: Receive One-to-One Message

ChatEventsManager.setupMessageEventListener(new MessageEventsListener() {
@Override
public void onMessageReceived(@NotNull ChatMessage message) {
//called when the new message is received
}
});

Closing Notes

That’s how businesses add chat services to AWS infrastructure. Should you have any queries, feel free to raise your questions in the comments below.
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article