Skip to content
Redis CLI

Pub/Sub: SUBSCRIBE, PUBLISH & PSUBSCRIBE

Fan-out messaging with channels and pattern subscriptions.

By EZ4Code Team
pubsubpublishsubscribepattern

Code

# Terminal 1: subscribe to a channel
$ redis-cli
127.0.0.1:6379> SUBSCRIBE news.tech
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "news.tech"
3) (integer) 1
1) "message"
2) "news.tech"
3) "Redis 7.4 released"

# Terminal 2: publish
$ redis-cli PUBLISH news.tech "Redis 7.4 released"
(integer) 1   # number of subscribers that received it

# Pattern subscriptions (glob-style)
127.0.0.1:6379> PSUBSCRIBE news.*
127.0.0.1:6379> PUNSUBSCRIBE news.*

# Inspect active subscriptions
127.0.0.1:6379> PUBSUB CHANNELS news.*
127.0.0.1:6379> PUBSUB NUMSUB news.tech   # subscriber count per channel
127.0.0.1:6379> PUBSUB NUMPAT             # count of pattern subscriptions

# Stream (consumer groups) is the durable alternative — see XADD/XREADGROUP

Explanation

Redis Pub/Sub delivers messages to all current subscribers — no persistence, no offline replay. SUBSCRIBE blocks the connection; you can hold multiple channels per connection. PUBLISH returns the number of receivers (0 if none). PSUBSCRIBE uses glob patterns (news.*, user.*.login). PUBSUB CHANNELS pattern lists active channels with subscribers; NUMSUB gives per-channel counts. Because messages are dropped when no subscriber is online, use Redis Streams (XADD/XREADGROUP with consumer groups) when you need durability, replay, or fan-out with acknowledgements.

More Redis CLI Snippets