Introduction
I've built this app to practice with WebSockets and Redis Pub/Sub. Basically, you create your account, log into it and you're welcomed with profile page. You can create a post, comment under a post, create/join room and talk in that room with its members. As a bonus, there's "friendship" feature that allows you to add/remove friends.
Tech Stack
I've already built few apps to practice my backend skills. I covered Python, FastAPI, SQLAlchemy, PostgreSQL, Docker, AWS deployment, pytest, etc.
Real-Time Communication
First Encounter
First time when I needed to use WebSockets was when working with "Room" feature. When User opens any room, it fetches the messages. However, fetching them over and over again just to get messages(or nothing) - would be insufficient. Instead, WebSocket allows us to keep connection between Server and User open to use that to communicate between them.
Implementation Issues
As previously said, we can establish and keep the connection between User and Server using WebSockets. However, we expect our app to be used by more people than just one user. It creates certain problem that we have to solve: Sending messages to all users in scope of the room.
Storing Connections
Using FastAPI, we can get "WebSocket" object and store it. Each WebSocket needs a user its connected to. That means we can make our backend to store list of WebSockets to track them. When WebSocket disconnects - remove it, when connects - add. Since our connections scope is tied to room_id, I created dictionary "user_room_connections"
user_room_connections: dict[uuid.UUID, list[WebSocket]] = {} Well, will that be enough? No, we also have to associate each WebSocket to each user. Unfortunately, they don't store any "user_id" that we can refer to. To create association, I created class "UserWebSocket".
class UserWebSocket: def __init__(self, user_id: uuid.UUID, websocket: WebSocket): self.user_id = user_id self.websocket = websocket It contains user_id and WebSocket object. That way we can know which user connected to which WebSocket and vice versa. Now, thanks to that we can replace "WebSocket" with "UserWebSocker" in user_room_connection.
user_room_connections: dict[uuid.UUID, list[UserWebSocket]] = {} That's it! Now we can send and receive messages in real time from any user who's in the same room as we... Or can we?
Multiple Workers Problem
Our previous solution works perfectly when we only have one Worker. What is Worker you ask? As I understand it, it's separate operating system process to handle user requests. They run independently from each other and so, they don't share any memory. We need more workers for better performance, scalability and reliability. Technically, it's possible to build communication pipeline between workers from scratch, however there's no need to do so since we already have working solution - Redis, and to be more precise, the Publish/Subscribe(Pub/Sub) features it allows us to use.
Redis
Introduction
When it comes to Redis, it is important to understand that it exists as a separate service, meaning: we have to connect our FastAPI application to the Redis service in our code. Here's the way I did it:
from redis.asyncio import Redis from backend.core.config import settings ... async def lifespan(app: FastAPI): redis = Redis( host=settings.REDIS_HOST, # "localhost" port=settings.REDIS_PORT, # 6379 decode_responses=True ) ... Additionally, it's worth to mention Docker, how useful it becomes when we have multiple services to work with and for establishing communication between them. Currently, our "REDIS_HOST" is set to "localhost" in "settings". You should change it to the name of your Redis service in your .env file whenever you run your application inside of a docker container.
Publish/Subscribe(Pub/Sub)
"Pub/Sub" is probably one of the most useful features that Redis gives us for dynamic communications between workers(workers don't know about each other's existence though). To begin, we first have to subscribe to the channel.
# CHAT_EVENTS_CHANNEL = "chat:events" pubsub = redis.pubsub() await pubsub.subscribe(CHAT_EVENTS_CHANNEL) Now, when our worker is subscribed, whenever user sends a message through a WebSocket, we can use that to publish message there.
# CHAT_EVENTS_CHANNEL = "chat:events" await redis.publish(CHAT_EVENTS_CHANNEL, "Hello, World!") The code here is overly simplified. There's more to "publish" than just raw line of text. In my final version of the app I use "RedisEvent" class to perform actions correspondingly to the event:
class MessagePublic(SQLModel): id: uuid.UUID content: str room_id: uuid.UUID sender_id: uuid.UUID | None created_at: datetime class RedisEvent(SQLModel): event: Literal["message_created", "message_updated", "message_deleted"] room_id: uuid.UUID message: MessagePublic | None = None message_id: uuid.UUID | None = None I then use "publih_chat_event" function to send the event.
CHAT_EVENTS_CHANNEL = "chat:events" async def publish_chat_event(redis: Redis, event: RedisEvent) -> None: await redis.publish(CHAT_EVENTS_CHANNEL, event.model_dump_json()) The decision behind "publish event" function is justified by the necessity of making not only receiving/sending messages dynamic, but also redacting/deleting them. I am sure there's better way to do this - it's something to find out for me next time.
My First Impression
it was my first time creating "Real-Time" communication using WebSockets and Redis service. I was very confused at first, but the more I used it the more I understood. Indeed. I enjoyed working on this project A LOT, especially the latter part. I never thought just how much it helps your site to look more alive and dynamic. I certainly want to experiment more with them in the future.
What Next?
I should mention that Redis has a lot more to it than just "Pub/Sub". There're still features to learn and experiment with. My next project will be all-in backend. I'll do my best to make it look professional so, even if there's no frontend, you still can learn a lot about project through clear documentation. Moreover, I want to deepen my understanding of the backend features I already use, improve my skills even more.
Here's repo: https://github.com/futsu37/ChatNFriend