Publish/Subscribe Pattern Using Redis

Learn how to integrate our chat servers using Redis and the Publish/Subscribe pattern.

Using Redis as a simple message broker

We start our analysis of the most common Pub/Sub implementations by introducing Redis, which is a very fast and flexible in-memory data structure store. Redis is often used as a database or a cache server, however, among its many features, there’s a pair of commands specifically designed to implement a centralized Pub/Sub message exchange pattern.

Redis’ message brokering capabilities are (intentionally) very simple and basic, especially if we compare them to those of more advanced message-oriented middleware. However, this is one of the main reasons for its popularity. Often, Redis is already available in an existing infrastructure, for example, used as a cache server or as a session data store. Its speed and flexibility make it a very popular choice for sharing data in a distributed system. So, as soon as the need for a publish/subscribe broker arises in a project, the most simple and immediate choice is to reuse Redis itself, avoiding the need to install and maintain a dedicated message broker.

Let’s now work on an example to demonstrate the simplicity and power of using Redis as a message broker.

Note: This example requires a working installation of Redis, listening on its default port. Here’s how to install Redis.

Our plan of action is to integrate our chat servers using Redis as a message broker. Each instance publishes any message received from its clients to the broker, and at the same time, it subscribes for any message coming from other server instances. As we can see, each server in our architecture is both a subscriber and a publisher. The following illustration shows a representation of the architecture that we want to obtain:

Get hands-on with 1200+ tech skills courses.