Skip to content
Redis

Pub/Sub

Broadcast messages to subscribed clients.

By EZ4Code Team
pubsubmessagingbroadcast

Code

# Subscriber (terminal 1)
SUBSCRIBE news alerts
PSUBSCRIBE log:*

# Publisher (terminal 2)
PUBLISH news "Server restarted"
PUBLISH log:error "Disk 80% full"

# Message format on subscriber:
# 1) "message"
# 2) "news"
# 3) "Server restarted"

# Pattern subscribe to all log:* channels
# PSUBSCRIBE log:*

# Lists vs pub/sub for durable queues:
# LPUSH + BRPOP keeps messages if no consumer is listening

Explanation

Redis pub/sub delivers messages to all connected subscribers in real time, with no persistence if no one is listening. SUBSCRIBE matches exact channels while PSUBSCRIBE matches glob patterns. For durable messaging, use lists or streams (XADD/XREAD) instead of pub/sub.

More Redis Snippets