Getting the Number of Subscribers in Redis Using Python (Detailed Guide w/ Code Examples)

Use Case(s)

In a publish/subscribe (pub/sub) model in Redis, you may want to know the number of subscribers to a particular channel. This is useful for load balancing and traffic management.

Code Examples

To get the number of subscribers in Redis using Python, you can use the pubsub_numsub method from the redis-py client library. Here's an example:

import redis # Create a redis client r = redis.Redis(host='localhost', port=6379, db=0) # Get the number of subscribers to 'channel' num_subscribers = r.pubsub_numsub('channel')[0][1] print(f'There are {num_subscribers} subscribers to the channel')

This script will connect to the Redis server, then get the number of subscribers to the 'channel'. The pubsub_numsub method returns a list where each element is a 2-element tuple; the first element is the channel name and the second is the count of subscribers. In this case, since we are interested in only one channel, we take the first element [0] and the second element of the tuple [1].

Best Practices

  • Always handle exceptions in your code to manage any connection or execution errors.
  • Avoid getting the subscriber count frequently in high throughput systems as it might affect performance.

Common Mistakes

  • Misinterpreting the result of pubsub_numsub. It doesn't return just a number but a list of tuples.


Q: Does pubsub_numsub work for pattern-based subscriptions as well? A: No, pubsub_numsub only works with channel-based subscriptions. Pattern-based subscription counts are not maintained by Redis.

Was this content helpful?

Start building today

Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement.