Sunday, December 3, 2023
No menu items!
HomeCloud ComputingBuild a chat server with Cloud Run

Build a chat server with Cloud Run

With Cloud Run — the fully-managed serverless container platform on Google Cloud — you can quickly and easily deploy applications using standard containers. In this article, we will explain how to build a chat server with Cloud Run using Python as the development language. We will build it with the FastAPI framework, based on this FastAPI sample source code.

[Note that this article does not provide detailed descriptions of each service. Refer to other articles for details like Cloud Run settings and the cloudbuild.yaml file format.]

Chat server architecture

The chat server consists of two Cloud Run services: frontend and backend. Code management is done on GitHub. Cloud Build deploys the code, and chat messages are passed between users with Redis pub/sub and Memorystore.

Set the “Authentication” option on the Cloud Run frontend service to “Allow all traffic” for frontend and backend. The two services communicate with a WebSocket, and backend and Memorystore can be connected using a serverless VPC access connector.

Let’s take a look at each service one by one.



The frontend service is written only in HTML. Only modify the WebSocket connection part with a URL of backend Cloud Run in the middle. This code is not perfect as it is just a sample to show the chat in action.

code_block[StructValue([(u’code’, u'<!DOCTYPE html>rn<html>rn <head>rn <title>Chat</title>rn </head>rn <body>rn <h1>Chat</h1>rn <h2>Room: <span id=”room-id”></span><br> Your ID: <span id=”client-id”></span></h2>rn <label>Room: <input type=”text” id=”channelId” autocomplete=”off” value=”foo”/></label>rn <button onclick=”connect(event)”>Connect</button>rn <hr>rn <form style=”position: absolute; bottom:0″ action=”” onsubmit=”sendMessage(event)”>rn <input type=”text” id=”messageText” autocomplete=”off”/>rn <button>Send</button>rn </form>rn <ul id=’messages’>rn </ul>rn <script>rn var ws = null;rn function connect(event) {rn var client_id = document.querySelector(“#client-id”).textContent = client_id;rn document.querySelector(“#room-id”).textContent = channelId.value;rn if (ws) ws.close()rn ws = new WebSocket(`wss://${channelId.value}/${client_id}`);rn ws.onmessage = function(event) {rn var messages = document.getElementById(‘messages’)rn var message = document.createElement(‘li’)rn var content = document.createTextNode( message.appendChild(content)rn messages.appendChild(message)rn };rn event.preventDefault()rn }rn function sendMessage(event) {rn var input = document.getElementById(“messageText”)rn ws.send(input.value)rn input.value = ”rn event.preventDefault()rn document.getElementById(“messageText”).focus()rn }rn </script>rn </body>rn</html>’), (u’language’, u”), (u’caption’, <wagtail.wagtailcore.rich_text.RichText object at 0x3ec97331d410>)])]


The Dockerfile is very simple. Because it is deployed as HTML, nginx:alpine is a good fit.

code_block[StructValue([(u’code’, u’FROM nginx:alpinernrnCOPY index.html /usr/share/nginx/html’), (u’language’, u”), (u’caption’, <wagtail.wagtailcore.rich_text.RichText object at 0x3ec9a0f6c390>)])]


The last part of the frontend service is the cloudbuild.yaml file. You only need to edit the project_id and “frontend”.

code_block[StructValue([(u’code’, u”steps:rn # Build the container imagern – name: ‘’rn args: [‘build’, ‘-t’, ‘$COMMIT_SHA’, ‘.’]rn # Push the container image to Container Registryrn – name: ‘’rn args: [‘push’, ‘$COMMIT_SHA’]rn # Deploy container image to Cloud Runrn – name: ‘’rn entrypoint: gcloudrn args:rn – ‘run’rn – ‘deploy’rn – ‘frontend’rn – ‘–image’rn – ‘$COMMIT_SHA’rn – ‘–region’rn – ‘asia-northeast3’rn – ‘–port’rn – ’80’rn images:rn – ‘$COMMIT_SHA'”), (u’language’, u”), (u’caption’, <wagtail.wagtailcore.rich_text.RichText object at 0x3ec9a0f6cd50>)])]

Backend Service

Let’s look at the server Python code first, starting with the core ChatServer class.

code_block[StructValue([(u’code’, u’class RedisService:rn def __init__(self):rn self.redis_host = f”{os.environ.get(‘REDIS_HOST’, ‘redis://localhost’)}”rnrn async def get_conn(self):rn return await aioredis.from_url(self.redis_host, encoding=”utf-8″, decode_responses=True)rnrnrnclass ChatServer(RedisService):rn def __init__(self, websocket, channel_id, client_id):rn super().__init__()rn WebSocket = websocketrn self.channel_id = channel_idrn self.client_id = client_idrn self.redis = RedisService()rnrn async def publish_handler(self, conn: Redis):rn try:rn while True:rn message = await if message:rn now = date_time = now.strftime(“%Y-%m-%d %H:%M:%S”)rn chat_message = ChatMessage(rn channel_id=self.channel_id, client_id=self.client_id, time=date_time, message=messagern )rn await conn.publish(self.channel_id, json.dumps(asdict(chat_message)))rn except Exception as e:rn logger.error(e)rnrn async def subscribe_handler(self, pubsub: PubSub):rn await pubsub.subscribe(self.channel_id)rn try:rn while True:rn message = await pubsub.get_message(ignore_subscribe_messages=True)rn if message:rn data = json.loads(message.get(“data”))rn chat_message = ChatMessage(**data)rn await”[{chat_message.time}] {chat_message.message} ({chat_message.client_id})”)rn except Exception as e:rn logger.error(e)rnrn async def run(self):rn conn: Redis = await self.redis.get_conn()rn pubsub: PubSub = conn.pubsub()rnrn tasks = [self.publish_handler(conn), self.subscribe_handler(pubsub)]rn results = await asyncio.gather(*tasks)rnrn”Done task: {results}”)’), (u’language’, u’lang-py’), (u’caption’, <wagtail.wagtailcore.rich_text.RichText object at 0x3ec9886d3fd0>)])]

This is a common chat server code. Inside the ChatServer class, there is a publish_handler method and a subscribe_handler method. publish_handler serves to publish a message to the chat room (Redis) when a message comes in through the WebSocket. subscribe_handler delivers a message from the chat room (redis) to the connected WebSocket. Both are coroutine methods. Connect redis in run method and run coroutine method.

This brings us to the endpoint. When a request comes in, this code connects to the WebSocket and connects to the chat server.

code_block[StructValue([(u’code’, u’@app.websocket(“/ws/{channel_id}/{client_id}”)rnasync def websocket_endpoint(websocket: WebSocket, channel_id: str, client_id: int):rn await manager.connect(websocket)rnrn chat_server = ChatServer(websocket, channel_id, client_id)rn await’), (u’language’, u’lang-py’), (u’caption’, <wagtail.wagtailcore.rich_text.RichText object at 0x3ec988b15090>)])]

Here is the rest of the code. Combined, you get the whole code.

code_block[StructValue([(u’code’, u’import asynciornimport jsonrnimport loggingrnimport osrnfrom dataclasses import dataclass, asdictrnfrom datetime import datetimernfrom typing import Listrnrnimport aioredisrnfrom aioredis.client import Redis, PubSubrnfrom fastapi import FastAPI, WebSocketrnrnlogging.basicConfig(level=logging.INFO)rnlogger = logging.getLogger(__name__)rnrnapp = FastAPI()rnrnrnclass ConnectionManager:rn def __init__(self):rn self.active_connections: List[WebSocket] = []rnrn async def connect(self, websocket: WebSocket):rn await websocket.accept()rn self.active_connections.append(websocket)rnrn def disconnect(self, websocket: WebSocket):rn self.active_connections.remove(websocket)rnrn async def send_personal_message(self, message: str, websocket: WebSocket):rn await websocket.send_text(message)rnrn async def broadcast(self, message: dict):rn for connection in self.active_connections:rn await connection.send_json(message, mode=”text”)rnrnrnmanager = ConnectionManager()rnrnrn@dataclassrnclass ChatMessage:rn channel_id: strrn client_id: intrn time: strrn message: str’), (u’language’, u’lang-py’), (u’caption’, <wagtail.wagtailcore.rich_text.RichText object at 0x3ec988b15450>)])]


The following is the Dockerfile for the backend service. Run this application with Uvicorn.

code_block[StructValue([(u’code’, u’FROM python:3.8-slimrnWORKDIR /usr/src/apprnCOPY requirements.txt ./rnRUN pip install -r requirements.txtrnCOPY . .rnCMD [ “uvicorn”, “main:app”, “–host”, “” ]’), (u’language’, u”), (u’caption’, <wagtail.wagtailcore.rich_text.RichText object at 0x3ec988b159d0>)])]


Put the packages for FastAPI and Redis into requirements.txt.

code_block[StructValue([(u’code’, u’aioredis==2.0.1rnfastapi==0.85.0rnuvicorn[standard]’), (u’language’, u”), (u’caption’, <wagtail.wagtailcore.rich_text.RichText object at 0x3ec988b158d0>)])]


The last step is the cloudbuild.yaml file. Just like the frontend service, you can edit the part composed of project_id and backend, and add the IP of the memorystore created at the back into REDIS_HOST.

code_block[StructValue([(u’code’, u”steps:rn # Build the container imagern – name: ‘’rn args: [‘build’, ‘-t’, ‘$COMMIT_SHA’, ‘.’]rn # Push the container image to Container Registryrn – name: ‘’rn args: [‘push’, ‘$COMMIT_SHA’]rn # Deploy container image to Cloud Runrn – name: ‘’rn entrypoint: gcloudrn args:rn – ‘run’rn – ‘deploy’rn – ‘backend’rn – ‘–image’rn – ‘$COMMIT_SHA’rn – ‘–region’rn – ‘asia-northeast3’rn – ‘–port’rn – ‘8000’rn – ‘–update-env-vars’rn – ‘REDIS_HOST=redis://’rn images:rn – ‘$COMMIT_SHA'”), (u’language’, u”), (u’caption’, <wagtail.wagtailcore.rich_text.RichText object at 0x3ec988b15cd0>)])]

Cloud Build

You can set Cloud Build to automatically build and deploy from Cloud Run when the source code is pushed to GitHub. Just select “Create trigger” and enter the required values. First, select “Push to a branch” for Event.

Next, go to the Source Repository. If this is your first time, you will need GitHub authentication. Our repository also has cloudbuild.yaml, so we also select the “Location” setting as the repository.

Serverless VPC access connector

Since both the Frontend service and the Backend service currently exist in the Internet network, you’ll need a serverless VPC access connector  to connect to the memorystore in the private band. You can do this by following this example code:

code_block[StructValue([(u’code’, u’bashrngcloud compute networks vpc-access connectors create chat-connector \rn–region=us-central1 \rn–network=default \rn–range= \rn–min-instances=2 \rn–max-instances=10 \rn–machine-type=e2-micro’), (u’language’, u”), (u’caption’, <wagtail.wagtailcore.rich_text.RichText object at 0x3ec9a1f2b0d0>)])]

Create memorystore

To create the memorystore that will pass chat messages, use this code:

code_block[StructValue([(u’code’, u’bashrngcloud redis instances create myinstance –size=2 –region=us-central1 \rn –redis-version=redis_6_X’), (u’language’, u”), (u’caption’, <wagtail.wagtailcore.rich_text.RichText object at 0x3ec9a27767d0>)])]

chat test

To demonstrate what you should see, we put two users into a conversation in a chat room called “test”. This will work regardless of how many users you have, and users will not see the conversations in other chat rooms until they join.


In this article, I built a serverless chat server using Cloud Run. By using Firestore instead of Memorystore, it is also possible to take the entire architecture serverless. Also, since the code is written on a container basis, it is easy to change to another environment such as GKE Autopilot, but Cloud Run is already a great platform for deploying microservices. Instances grow quickly and elastically according to the number of users connecting, so why would I need to choose another platform? Try it out now in the Cloud Console.

Related Article

Hidden gems of Google BigQuery

Read on to learn about BigQuery features I did not know about until recently. Once I discovered them, I loved them immediately. I hope yo…

Read Article

Related Article

Efficient File Management using Batch Requests with Google Apps Script

Google Drive can handle small file management but when it comes to larger batches of files, with Google Apps Script, even large batches c…

Read Article

Cloud BlogRead More



Please enter your comment!
Please enter your name here

Most Popular

Recent Comments