...

/

Build a Chat Application with Redis Pub/Sub

Build a Chat Application with Redis Pub/Sub

Learn how to combine Redis Pub/Sub with WebSocket to build a collaborative chat service.

Pub/Sub with the go-redis client

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

Press + to interact
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 also subscribed to this channel, it receives this message and sends the ...