Pub/Sub
Fire-and-forget fan-out, patterns, sharded channels, and its limits
Pub/Sub delivers a message to every client currently subscribed to a channel, then forgets it. There's no storage, no acknowledgement, and no replay. That makes it very fast and very simple, and wrong for anything that must not be lost.
Commands
Try it with two terminals:
# terminal 1
docker exec -it redis redis-cli --user app --pass app123 SUBSCRIBE chat:room1
# terminal 2
docker exec redis redis-cli --user app --pass app123 PUBLISH chat:room1 hello
(integer) 1 # delivered to one subscriber
# terminal 1 prints
1) "message"
2) "chat:room1"
3) "hello"Delivery semantics: at most once
A message is delivered only to clients subscribed at that instant.
- A subscriber that's disconnected, restarting, or not yet connected misses it, permanently.
- There's no ack. If the subscriber crashes while handling it, it's gone.
PUBLISHreturning 0 means nobody heard it, and Redis doesn't keep it.
Slow subscribers get disconnected. Redis buffers outgoing messages
per client, and if a subscriber can't keep up, its buffer grows. The
client-output-buffer-limit pubsub 32mb 8mb 60 default closes the
connection if the buffer passes 32 MB, or stays above 8 MB for 60
seconds, dropping everything buffered. This protects Redis from
running out of memory, and it means a slow consumer silently loses
messages.
Good uses
Pub/Sub is right when a missed message is harmless, or when the message is only a hint that the receiver can recover from:
- Live UI updates: "new comment posted", where the page can refetch.
- Cache invalidation broadcasts to app servers' in-memory caches (with a TTL as the backstop).
- Chat presence, typing indicators.
- Telling workers "new work is available" while the work itself lives in a list or stream.
Sharded Pub/Sub
In Redis Cluster, a classic PUBLISH is broadcast to every node,
because subscribers could be connected anywhere. On a large cluster that
traffic dominates. Sharded Pub/Sub (Redis 7+) routes a channel to the
node that owns its hash slot, like a key:
SSUBSCRIBE {room1}:chat
SPUBLISH {room1}:chat "hello"Use sharded channels for any Pub/Sub on a cluster.
Keyspace notifications
Redis can publish events about keys themselves: set, deleted, expired, evicted. Enable them with a flags string:
CONFIG SET notify-keyspace-events KEA # K = keyspace channel, E = keyevent channel, A = all events
PSUBSCRIBE __keyspace@0__:session:* # every event on session keys
SUBSCRIBE __keyevent@0__:expired # every expiryThey're Pub/Sub messages, so the same at-most-once rules apply, and
enabling everything (KEA) adds overhead to every write. Turn on only
the events you need.
Lab
- Run the two-terminal demo above.
- Publish 3 messages, then start the subscriber and publish 1 more. How many does it see?
- Enable
Exnotifications and subscribe to__keyevent@0__:expired. Set a key withEX 3and watch the event arrive. - Note what
PUBLISHreturns with zero, one, and two subscribers.