What Is Pub/Sub In Redis?

Riyazur Razak
2 min readSep 13, 2021

We all know that Redis is an in-memory database, which stores data in memory rather than disk. We all know that Redis is mostly used for caching and other purposes. But Redis is quite powerful than we think. Redis is not only used for caching purposes. It has many features that make our development powerful. Let's see one of the features PUB/SUB.

What Is PUB/SUB?

PUB/SUB is called publisher and subscriber. For more details, let's assume a push notification service. If a publisher sends a message, it will receive to all the subscriber's devices. The same principle is used here. If a publisher sends a message, all the subscribers who subscribers can receive a message.

Let's assume we have two services service A and service B. The task is service A wants to send some data (user data) to service B. Consider both are in different hosts/ports. How can we send the data to service B? For this situation, our PUB/SUB plays a major role. Can you guess how we achieve it?

Our service A is a publisher and our service B is a subscriber for service A. If service A sends a message (user data) it will be received by service B. It sounds simple. But It will help you in many cases when you scale the app.

Is PUB/SUB is only in Redis?

The Answer Is No. There are so many are there like rabbitMq etc… Redis also supports PUB/SUB, But Redis is not only the one.

Coding Time 🤩

I use the Express.js framework here. You can use any framework you want.

Block Diagram of our app
Block Diagram of the below code

We can Publish A message from service A, via the dev channel. The subscribers who want that message can subscribe to the dev channel.

There is No Limit to publishers or subscribers for a single app. You can create as many as you can.

It is quite easy to communicate between our services. I hope you can learn some new topics in Redis. It's not the only way to use PUB/SUB. There are tons of other techniques to use it. Feel Free to share if you find better ways.

--

--