Dragonfly Cloud is now available on the AWS Marketplace - Learn More

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

Use Case(s)

The command PUBSUB NUMSUB <channel> is used to return the number of subscribers (not counting clients subscribed to patterns) for the specified channels in Redis. This is especially useful in pub/sub scenarios where you need to monitor how many subscribers a certain channel has, for instance, if there are any consumers for the data being published.

Code Examples

Example 1: Using Redis-Py library to get the number of subscribers for a specific channel.

import redis r = redis.Redis(host='localhost', port=6379, db=0) subscribers = r.execute_command('PUBSUB NUMSUB channel-name') print(subscribers)

In this example, we're connecting to a local Redis server on port 6379, then executing a raw Redis command PUBSUB NUMSUB for the channel-name. The output will be a list with the channel name and the number of subscribers.

Example 2: When there are multiple channels.

import redis r = redis.Redis(host='localhost', port=6379, db=0) channels = ['channel1', 'channel2', 'channel3'] for channel in channels: subscribers = r.execute_command('PUBSUB NUMSUB', channel) print(f'{channel}: {subscribers[1]}')

In this example, there are multiple channels. We loop over them, getting and printing the number of subscribers for each.

Best Practices

Always ensure that your Redis server is protected and not exposed to the internet. Only trusted clients should be able to connect and issue commands.

Common Mistakes

  1. Be careful with your channel names. Redis doesn't check whether a given channel has subscribers before publishing a message, which could lead to data being sent into a void.

  2. Ensure that you have proper exception handling around your Redis code. Network-related problems can happen at any time and should be properly handled.

FAQs

  1. Does the PUBSUB NUMSUB command include pattern-based subscriptions? No, it only includes the number of subscribers for the specific channels. Use PUBSUB NUMPAT to get the global count of pattern-based subscriptions.

Was this content helpful?

Switch & save up to 80% 

Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement. Instantly experience up to a 25X boost in performance and 80% reduction in cost