Pub/Sub
Pub/Sub commands for real-time messaging between clients. Messages are broadcast to all subscribers of a channel.
Commands
Section titled âCommandsâ| Command | Syntax | Description |
|---|---|---|
| SUBSCRIBE | SUBSCRIBE channel [channel ...] | Subscribe to channels |
| UNSUBSCRIBE | UNSUBSCRIBE [channel ...] | Unsubscribe from channels |
| PUBLISH | PUBLISH channel message | Publish message to channel |
| PSUBSCRIBE | PSUBSCRIBE pattern [pattern ...] | Subscribe to pattern-matched channels |
| PUNSUBSCRIBE | PUNSUBSCRIBE [pattern ...] | Unsubscribe from patterns |
How Pub/Sub Works
Section titled âHow Pub/Sub Worksâ- Clients subscribe to channels using
SUBSCRIBEorPSUBSCRIBE - Publishers send messages with
PUBLISH - All subscribed clients receive the message
- Messages are not persisted - if no subscribers, message is lost
Examples
Section titled âExamplesâBasic Subscribe/Publish
Section titled âBasic Subscribe/PublishâTerminal 1 (Subscriber):
127.0.0.1:6379> SUBSCRIBE newsReading messages... (press Ctrl-C to quit)1) "subscribe"2) "news"3) (integer) 1
# When message arrives:1) "message"2) "news"3) "Breaking: Redlite 1.0 released!"Terminal 2 (Publisher):
127.0.0.1:6379> PUBLISH news "Breaking: Redlite 1.0 released!"(integer) 1 # Number of subscribers who received itMultiple Channels
Section titled âMultiple ChannelsâSubscriber:
127.0.0.1:6379> SUBSCRIBE sports weather newsReading messages...1) "subscribe"2) "sports"3) (integer) 11) "subscribe"2) "weather"3) (integer) 21) "subscribe"4) "news"3) (integer) 3
# Messages from any channel:1) "message"2) "sports"3) "Goal!"
1) "message"2) "weather"3) "Sunny, 72F"Pattern Subscriptions
Section titled âPattern SubscriptionsâSubscribe to all channels matching a pattern:
Subscriber:
127.0.0.1:6379> PSUBSCRIBE news:*Reading messages...1) "psubscribe"2) "news:*"3) (integer) 1
# Matches news:sports, news:tech, news:local, etc.1) "pmessage"2) "news:*"3) "news:tech"4) "New iPhone announced"
1) "pmessage"2) "news:*"3) "news:sports"4) "Championship finals tonight"Publisher:
127.0.0.1:6379> PUBLISH news:tech "New iPhone announced"(integer) 1
127.0.0.1:6379> PUBLISH news:sports "Championship finals tonight"(integer) 1
127.0.0.1:6379> PUBLISH weather "Sunny"(integer) 0 # No pattern matchUnsubscribe
Section titled âUnsubscribeâ# Unsubscribe from specific channels127.0.0.1:6379> UNSUBSCRIBE news weather1) "unsubscribe"2) "news"3) (integer) 11) "unsubscribe"2) "weather"3) (integer) 0
# Unsubscribe from all channels127.0.0.1:6379> UNSUBSCRIBE1) "unsubscribe"2) (nil)3) (integer) 0
# Unsubscribe from patterns127.0.0.1:6379> PUNSUBSCRIBE news:*1) "punsubscribe"2) "news:*"3) (integer) 0Check Subscriber Count
Section titled âCheck Subscriber Countâ# PUBLISH returns number of subscribers127.0.0.1:6379> PUBLISH mychannel "test"(integer) 3 # 3 clients received the message
127.0.0.1:6379> PUBLISH emptychannel "test"(integer) 0 # No subscribersPattern Syntax
Section titled âPattern Syntaxâ| Pattern | Matches |
|---|---|
* | Any sequence of characters |
? | Any single character |
[abc] | Any character in brackets |
Examples:
news:*matchesnews:sports,news:tech,news:localuser:?matchesuser:1,user:abut notuser:12log:[we]rrormatcheslog:error,log:wrror
Message Format
Section titled âMessage FormatâSubscribe Confirmation
Section titled âSubscribe Confirmationâ1) "subscribe" # Message type2) "channel-name" # Channel subscribed to3) (integer) N # Total subscriptions for this clientRegular Message
Section titled âRegular Messageâ1) "message" # Message type2) "channel-name" # Source channel3) "message-body" # The message contentPattern Message
Section titled âPattern Messageâ1) "pmessage" # Message type (pattern)2) "pattern" # Pattern that matched3) "channel-name" # Actual channel4) "message-body" # The message contentImportant Notes
Section titled âImportant NotesâAt-Most-Once Delivery
Section titled âAt-Most-Once Deliveryâ- Messages are delivered to current subscribers only
- If no subscribers exist, the message is lost
- No message persistence or history
- No acknowledgment or retry mechanism
Subscription Mode
Section titled âSubscription ModeâOnce a client enters subscription mode:
- Only
SUBSCRIBE,UNSUBSCRIBE,PSUBSCRIBE,PUNSUBSCRIBE, andQUITare allowed - Regular commands like
GET,SETare not available - Use a separate connection for commands
Server Mode Only
Section titled âServer Mode OnlyâPub/Sub requires server mode because:
- Requires persistent TCP connections
- Real-time message delivery
- Multiple client coordination
Use Cases
Section titled âUse CasesâReal-Time Notifications
Section titled âReal-Time Notificationsâ# User activity channelSUBSCRIBE user:123:notifications
# Send notificationPUBLISH user:123:notifications '{"type":"message","from":"user:456"}'Chat Rooms
Section titled âChat Roomsâ# Join roomSUBSCRIBE room:general
# Send messagePUBLISH room:general '{"user":"alice","text":"Hello everyone!"}'Cache Invalidation
Section titled âCache Invalidationâ# All app instances subscribePSUBSCRIBE cache:invalidate:*
# When data changesPUBLISH cache:invalidate:users "user:123"PUBLISH cache:invalidate:products "product:456"Event Broadcasting
Section titled âEvent Broadcastingâ# Subscribe to all eventsPSUBSCRIBE events:*
# Publish eventsPUBLISH events:user:created '{"id":123}'PUBLISH events:order:completed '{"id":456}'Distributed Coordination
Section titled âDistributed Coordinationâ# Leader election channelSUBSCRIBE leader:election
# Announce leadershipPUBLISH leader:election '{"node":"node-1","action":"claim"}'Comparison with Streams
Section titled âComparison with Streamsâ| Feature | Pub/Sub | Streams |
|---|---|---|
| Persistence | No | Yes |
| Message history | No | Yes |
| Consumer groups | No | Yes |
| Acknowledgment | No | Yes |
| Blocking read | Subscribe-based | XREAD BLOCK |
| Use case | Real-time broadcast | Reliable queuing |
Use Pub/Sub for fire-and-forget broadcasting. Use Streams when you need reliability and history.