Redis Publish/subscribe

By

Learn how Redis publish/subscribe messaging works, using the SUBSCRIBE and PUBLISH commands to send a message on a channel to multiple subscribers at once.

~~~

Redis implements a publish/subscribe messaging mechanism.

Its concept is simple: a publisher sends a message on a channel. Multiple subscribers receive it.

The publisher doesn’t know who is listening, and subscribers don’t know who sent the message. The two sides are completely decoupled. That’s what makes pub/sub useful for things like chat messages, live notifications, or telling several app servers to invalidate a cache at the same time.

Subscribe to a channel using

SUBSCRIBE <channel>

Publish to a channel using

PUBLISH <channel> <message>

Example:

SUBSCRIBE dogs

Redis CLI terminal showing SUBSCRIBE dogs command with confirmation messages

In another redis-cli window, type:

PUBLISH dogs "Roger"

Redis CLI terminal showing PUBLISH commands sending Roger and Syd messages to dogs channel

PUBLISH returns a number: how many subscribers received the message. If it returns 0, nobody was listening on that channel.

Messages will be sent to the subscribers, and they’ll by default display the kind of event, the channel, and the message:

Subscriber terminal displaying received messages from dogs channel showing Roger and Syd

Subscribers can listen on multiple channels:

SUBSCRIBE dogs cats

and will receive messages coming from all of them.

Subscribing with a pattern

You can also subscribe to every channel matching a pattern, using PSUBSCRIBE:

PSUBSCRIBE dogs.*

This subscriber receives messages published to dogs.food, dogs.walks, and any other channel starting with dogs..

Why do you need two terminal windows?

Once a client subscribes, that connection enters subscribe mode. It can only manage its subscriptions or run PING. Regular commands like GET and SET are rejected until you unsubscribe.

That’s why the example uses a second redis-cli window to publish. In a real application, you’d use one connection for subscribing and a separate one for everything else.

A pitfall: messages are not stored

Redis pub/sub is fire and forget. A message goes out to the subscribers connected at that exact moment, and then it’s gone. Redis keeps no history.

So if a subscriber is offline, even for a second, it misses every message published in the meantime. There’s no way to catch up.

If your application can’t afford to lose messages, pub/sub is the wrong tool. Use Redis Streams instead, which store messages and let consumers resume from where they left off. Use pub/sub when losing an occasional message is acceptable, like live counters or presence updates.

Tagged: Redis · All topics
~~~

Related posts about redis: