Redis Pub/Sub

Real-time Redis pub/sub explained and implemented

Rahul Kapoor
3 min readJul 9, 2023
Real-time Redis pub/sub explained and implemented

What is Pub/Sub?

Pub/Sub stands for Publish / Subscribe and it is a messaging paradigm.

Here we have a group of clients subscribing to specific channels and a group of clients publishing to specific channels as well. This happens in real-time and Redis supports it very well.

Senders are called Publishers, responsible for publishing these messages to specific channels, and the receivers are called Subscribers who subscribe to these channels to receive messages.

To install Redis on your local terminal, follow the below article:
https://redis.io/docs/getting-started/installation/install-redis-on-mac-os/

Let’s discuss the format of pushed messages

A message is an array with three elements.

The first element is the kind of message:

  • subscribe: means that we successfully subscribed to the channel given as the second element in the reply. The third argument represents the number of channels we are currently subscribed to (as shown in the screenshot below)
SUBSCRIBE to channels ch1 and ch2
  • unsubscribe: means that we successfully unsubscribed from the channel given as the second element in the reply. The third argument represents the number of channels we are currently subscribed to. Here we got 0 in the below screenshot as I earlier unsubscribed to the ch1 channel which is not captured in the screenshot.
    When the last argument is zero, we are no longer subscribed to any channel, and the client can issue any kind of Redis command as we are outside the Pub/Sub state.
UNSUBSCRIBE to channel ch2
  • message: it is a message received as a result of a PUBLISH command issued by another client. Here done by 0.0.0.0 on ch1 for a message “hie there”.
PUBLISH on channels ch1 and ch2 on host client 0.0.0.0
  • The second element is the name of the originating channel here as ch1 or ch2 in the below screenshot, and the third argument is the actual message payload which comes as “hie there” and “welcome to redis pub/sub”.
Messages received on channels ch1 and ch2 on host client 127.0.0.1

To read more on the pub/sub architecture you can read these awesome articles:
https://www.enjoyalgorithms.com/blog/publisher-subscriber-pattern

https://ably.com/topic/pub-sub

--

--

No responses yet