Redis Pub Sub, somehow may sound weird that it provides such a functionality since when you think of Redis the first thing that comes to mind is of a cache key value store. But indeed Redis does allow us to use the messaging paradigm by using channels to publish messages and for subscribers to listen for notification of the message. Redis Pub Sub allows multiple subscribers to listen to one or more channels, and to only receive messages that are of interest. It decouples the subscriber from the publisher since the subscriber has no knowledge of whom the publishers are and vice versa there could be multiple publisher not knowing whom the subscribers are.

Sample Diagram of Redis Pub Sub

RedisPubSub

Redis Pub Sub

There are definitely certain restrictions of using Redis Pub Sub as a Messaging System, it will not be like RabbitMQ, Kafka or Azure MessageBus etc. Those message bus are able to store the message for durability or even replay of an old message for consumption. Redis uses a listener model where there are no listeners (subscribers) it will not receive those messages. But if you wish to have a simple pub sub without the heavy tools then Redis does quite a good job at it.

Redis Pub Sub – Operations

  • PUBLISH channels message: Posts a message to the given channel O(N+M)
  • SUBSCRIBE [channel]: Subscribe to a given channel for message, O(N) where N is the number of channels to subscribe to
  • PSUBSCRIBE [channel]: Subscribes the client to the given patterns, O(N) where N is the number of patterns the client is already subscribed to.
  • PUBSUB CHANNELS pattern: Currently active channels, O(N)
  • PUBSUB NUMSUB channel: Number of subscribers to the channels provided, O(N)
  • PUBSUB NUMPAT: Number of subscriptions to all the patterns O(N)
  • PUNSUBSCRIBE: Unsubscribes the client from a pattern, O(N+M)
  • UNSUBSCRIBE: Unsubscribes the client from a channel, O(N) where N is the number of clients already subscribed to a channel.

C# code using Redis PubSub

So this covers the basic usage of Redis PubSub, in the next blog post I will cover how to use Pipelines in Redis.

For the code please visit
https://github.com/taswar/RedisForNetDevelopers/tree/master/9.RedisPubSub

For previous Redis topics

  1. Intro to Redis for .NET Developers
  2. Redis for .NET Developer – Connecting with C#
  3. Redis for .NET Developer – String Datatype
  4. Redis for .NET Developer – String Datatype part 2
  5. Redis for .NET Developer – Hash Datatype
  6. Redis for .NET Developer – List Datatype
  7. Redis for .NET Developer – Redis Sets Datatype
  8. Redis for .NET Developer – Redis Sorted Sets Datatype
  9. Redis for .NET Developer – Redis Hyperloglog