Redis Pub/Sub
Publish/subscribe is a messaging pattern where senders (publishers) do not send messages to specific receivers. They publish to a named channel, and every client currently subscribed to that channel receives a copy. Redis has built-in pub/sub that is extremely fast and simple, which makes it popular for chat messages, live notifications, cache invalidation signals and real-time dashboards.
The commands
| Command | Who uses it | Effect |
|---|---|---|
SUBSCRIBE ch [ch ...] |
subscriber | listen to exact channel names |
PSUBSCRIBE pattern |
subscriber | listen to every channel matching a glob (news.*) |
UNSUBSCRIBE / PUNSUBSCRIBE |
subscriber | stop listening |
PUBLISH ch message |
publisher | send a message; returns how many clients received it |
PUBSUB CHANNELS / NUMSUB |
anyone | inspect active channels and subscriber counts |
A subscribed connection is in a special mode: it can only (un)subscribe and PING until it unsubscribes from everything. That is why applications use a separate connection for subscribing.
A session with two terminals
Pub/sub needs at least two clients, so it cannot be shown in a single-connection playground. Here is what it looks like with two redis-cli windows:
# Terminal 1 (subscriber)
redis> SUBSCRIBE news.tech news.sport
1) "subscribe"
2) "news.tech"
3) (integer) 1
1) "subscribe"
2) "news.sport"
3) (integer) 2
Reading messages... (press Ctrl-C to quit)
# Terminal 2 (publisher)
redis> PUBLISH news.tech "Redis 8 released"
(integer) 1
# Terminal 1 now prints
1) "message"
2) "news.tech"
3) "Redis 8 released"Each received message is a three-element array: the kind (message), the channel and the payload. Pattern subscriptions deliver pmessage with the pattern as an extra element.
Publishing with nobody listening
The playground can still show the publisher's side. With no subscribers, PUBLISH returns 0 and the message is simply dropped:
PUBLISH news.tech "Nobody hears this"
PUBSUB CHANNELS
PUBSUB NUMSUB news.tech news.sport
PUBSUB NUMPATredis> PUBLISH news.tech "Nobody hears this"
(integer) 0
redis> PUBSUB CHANNELS
(empty array)
redis> PUBSUB NUMSUB news.tech news.sport
1) "news.tech"
2) (integer) 0
3) "news.sport"
4) (integer) 0
redis> PUBSUB NUMPAT
(integer) 0
That is the most important property of Redis pub/sub: it is fire and forget.
Delivery guarantees
| Property | Pub/Sub | Streams |
|---|---|---|
| Message stored | no | yes |
| Subscriber offline during publish | message lost | reads it later |
| Re-reading history | impossible | XRANGE |
| Acknowledgements and retries | no | consumer groups, XACK |
| Fan-out to all listeners | yes | yes (each group or each XREAD reader) |
| Overhead | lowest | a little more memory |
Use pub/sub when losing a message during a disconnect is acceptable (a typing indicator, a "refresh your cache" hint, a live score that is replaced a second later anyway). Use streams when every message must be processed.
A model of the fan-out
The following Python program models what Redis does internally: a dictionary from channel to the set of subscribed clients, plus a list of pattern subscriptions. It shows why a publish to a channel with no subscribers is lost:
from fnmatch import fnmatchcase
class Broker:
def __init__(self):
self.channels = {} # channel -> list of clients
self.patterns = [] # (pattern, client)
def subscribe(self, client, channel):
self.channels.setdefault(channel, []).append(client)
def psubscribe(self, client, pattern):
self.patterns.append((pattern, client))
def publish(self, channel, message):
receivers = 0
for client in self.channels.get(channel, []):
client.inbox.append(("message", channel, message))
receivers += 1
for pattern, client in self.patterns:
if fnmatchcase(channel, pattern):
client.inbox.append(("pmessage", pattern, channel, message))
receivers += 1
return receivers # what PUBLISH replies
class Client:
def __init__(self, name):
self.name, self.inbox = name, []
broker = Broker()
ada, linus = Client("ada"), Client("linus")
broker.subscribe(ada, "news.tech")
broker.psubscribe(linus, "news.*")
print("PUBLISH news.tech ->", broker.publish("news.tech", "Redis 8 released"))
print("PUBLISH news.sport ->", broker.publish("news.sport", "Final score 2-1"))
print("PUBLISH weather ->", broker.publish("weather", "Sunny"))
for c in (ada, linus):
print(c.name, c.inbox)PUBLISH news.tech -> 2
PUBLISH news.sport -> 1
PUBLISH weather -> 0
ada [('message', 'news.tech', 'Redis 8 released')]
linus [('pmessage', 'news.*', 'news.tech', 'Redis 8 released'), ('pmessage', 'news.*', 'news.sport', 'Final score 2-1')]
Keyspace notifications
Redis can publish an event whenever a key changes, for example when it expires. It is disabled by default because it costs CPU; you enable it with a configuration string (K = keyspace events, E = keyevent events, x = expired, g = generic commands like DEL, $ = string commands, A = all):
CONFIG SET notify-keyspace-events Ex
CONFIG GET notify-keyspace-eventsredis> CONFIG SET notify-keyspace-events Ex
OK
redis> CONFIG GET notify-keyspace-events
1) "notify-keyspace-events"
2) "xE"
Redis stores the flags in its own canonical order, so Ex reads back as xE. A client would then subscribe to __keyevent@0__:expired and receive the name of every key in database 0 that expires. Like all pub/sub messages, these events are lost if no one is listening at that moment.
Sharded pub/sub
In a Redis Cluster, a classic PUBLISH is broadcast to every node, which limits scaling. Redis 7 added sharded pub/sub (SSUBSCRIBE, SPUBLISH): a channel lives on the node that owns its hash slot, just like a key, so traffic scales with the number of shards.
Using pub/sub from code
import redis
r = redis.Redis(decode_responses=True)
# Subscriber (usually its own process or thread)
p = r.pubsub()
p.subscribe("chat:room:42")
for msg in p.listen():
if msg["type"] == "message":
print("new message:", msg["data"])
# Publisher (any other connection)
r.publish("chat:room:42", "Hi everyone!")Test yourself
What happens to a message published on a channel that has no subscribers?
- It is stored until someone subscribes
- It is dropped
- It is turned into a stream entry
- PUBLISH returns an error
Which command subscribes to all channels whose names start with orders.?
- SUBSCRIBE orders.*
- PSUBSCRIBE orders.*
- PUBLISH orders.*
- XREAD orders.*
You need every order event processed even if a worker restarts. What should you use?
- Pub/Sub
- Streams with consumer groups
- Keyspace notifications
- PUBSUB CHANNELS