Sobes.tech
Junior — Middle

Explain the working principle of the Pub/Sub mechanism in Redis and its use in message exchange systems.

sobes.tech AI

Answer from AI

The Pub/Sub (Publish/Subscribe) mechanism in Redis allows message exchange between clients through channels. Clients can subscribe to one or more channels (subscribe), while other clients publish messages to these channels (publish). When a message is published to a channel, Redis instantly sends it to all subscribers of that channel.

Features:

  • Redis does not store message history — if a client is not subscribed at the time of publication, it will not receive the message.
  • Suitable for systems where fast real-time message delivery is important.

Example of usage in Python with the redis-py library:

import redis

r = redis.Redis()

# Subscriber
pubsub = r.pubsub()
pubsub.subscribe('channel1')

for message in pubsub.listen():
    if message['type'] == 'message':
        print(f"Received message: {message['data'].decode()}")

# Messages can be published from another client:
r.publish('channel1', 'Hello, subscribers!')

In message exchange systems, Redis Pub/Sub is often used for notifications, chats, cache updates, and other scenarios where quick notification of many clients is needed without complex infrastructure.