Search⌘ K
AI Features

Build a Chat Application with Redis Pub/Sub

Explore building a chat application with Redis Pub/Sub and WebSocket using Go. Understand how to enable real-time messaging across multiple application instances to ensure scalability and seamless user communication.

Pub/Sub with the go-redis client

Conceptually, Redis Pub/Sub is quite simple. Here’s how it works with the go-redis client:

Go (1.18.2)
client.Publish(context.Background(), chatChannel, user+":"+string(message)).Err()
subscription := client.Subscribe(context.Background(), chatChannel)
messagesChannel := subscription.Channel()
sub.Unsubscribe(context.Background(), chatChannel)
  • Line 1: Producers send data to a Redis channel.

  • Lines 3–4: Consumers subscribe to the channel to receive messages using Subscribe and receive messages via a Go channel.

  • Line 6: Here, we use Unsubscribe and close the connection.

The application used in this lesson is a simplified version of a chat service.

Application overview

The application uses a combination of Redis Pub/Sub and WebSocket to allow a horizontally scalable architecture. The application hosts a WebSocket server endpoint that clients (users) can connect to using a WebSocket client.

Here’s the high-level application flow:

  1. A user connects to an endpoint provided by the application. If successful, this creates a WebSocket connection between the client and application (server).

  2. When the user sends a chat message, it’s relayed over the WebSocket connection to the application.

  3. The application publishes this message to the Redis channel.

  4. Because the application is ...