Publish Messages to Channels
Learn to publish messages to channels in Redis—step-by-step with hands-on exercise, troubleshooting, and next lesson.
Focus: publish messages to channels
Imagine a flock of birds reacting in near-perfect unison the moment one spots a predator. You don't want each bird to constantly check on the one that sensed danger; you want the first bird to broadcast a single warning that ripples through the whole flock instantly. When building real-time applications—like live chat, stock tickers, or IoT alerts—Redis pub/sub lets you achieve exactly this pattern: one message, many listeners, zero polling.
The Problem This Lesson Solves
Before pub/sub, distributed systems relied on polling or shared databases to propagate events. Polling wastes CPU, increases latency, and forces every consumer to ask "is there something new?" at fixed intervals. Writing custom message queues adds complexity, boilerplate, and potential race conditions. Redis pub/sub eliminates polling by giving you a lightweight, fire‑and‑forget channel where publishers send messages and subscribers receive them instantly—no shared state, no long‑running queries, just a single command.
Core Concept / Mental Model
Think of Redis pub/sub as a radio broadcast. A publisher speaks into a microphone (the channel) and every tuned‑in receiver (subscriber) hears the message at exactly the same time. The radio station (Redis) doesn't store the broadcast; if you tune in late, you missed it. This is the defining trait of pub/sub: messages are not persisted. Subscribers must be actively listening to receive messages.
Key Definitions
- Channel – A named message topic (e.g.,
order_updates,sensor_alerts). - Publisher – A client that sends a message to one or more channels.
- Subscriber – A client that listens on a channel and receives messages sent after subscribing.
Pro Tip: Pub/sub is not a queue. If a subscriber disconnects, it will not receive messages sent while it was offline. For durable messaging with replay, use Redis Streams instead.
How It Works Step by Step
1. A subscriber connects and subscribes to a channel
The subscriber issues SUBSCRIBE channel_name. Redis opens a dedicated subscription context—no further commands are processed until the subscriber unsubscribes or closes the connection.
2. A publisher sends a message to the same channel
Using PUBLISH channel_name message, Redis immediately delivers the message to all active subscribers of that channel.
3. Each subscriber receives the message
Redis pushes the message back as a three‑element array: [message_type, channel, payload]. The message_type is message for regular content.
4. The message is delivered once, then discarded
Redis forgets it instantly. No storage, no redelivery, no acknowledgment. This is the core trade‑off.
Hands‑on Walkthrough
Let's use redis-cli to simulate a live notification system. Open two terminals.
Terminal 1 – Subscribe to a channel
# Start redis-cli and listen to the 'notifications' channel
$ redis-cli
127.0.0.1:6379> SUBSCRIBE notifications
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "notifications"
3) (integer) 1
Now this terminal is blocking on notifications. It will print every incoming message.
Terminal 2 – Publish a message
# In a second terminal, publish a message
$ redis-cli
127.0.0.1:6379> PUBLISH notifications "Deploy completed - v2.1.0"
(integer) 1
The return value 1 means one subscriber received it.
Switch back to Terminal 1 – see the message
1) "message"
2) "notifications"
3) "Deploy completed - v2.1.0"
The subscriber received the exact string published. The three‑element response tells you the event type, channel, and payload.
Python example – publish with Redis SDK
import redis
r = redis.Redis(host='localhost', port=6379, decode_responses=True)
# Publish a message to 'alerts'
result = r.publish('alerts', 'Server load exceeded 90%')
print(f"Subscribers who got the message: {result}")
Expected output (if a subscriber is listening):
Subscribers who got the message: 1
Python example – subscribe and listen in a loop
import redis
r = redis.Redis(host='localhost', port=6379, decode_responses=True)
pubsub = r.pubsub()
pubsub.subscribe('alerts')
print("Listening for alerts...")
for message in pubsub.listen():
if message['type'] == 'message':
print(f"[{message['channel']}] {message['data']}")
When you run this script and then publish from redis-cli or another script, it will print the alert in real‑time.
Compare Options / When to Choose What
| Feature | Redis Pub/Sub | Redis Streams | RabbitMQ / Kafka |
|---|---|---|---|
| Message persistence | None – fire‑and‑forget | Yes – can replay | Yes – configurable |
| Delivery guarantee | At‑most‑once (lost if no subscriber) | At‑least‑once with consumer groups | At‑least‑once or exactly‑once |
| Ideal use case | Live notifications, ephemeral events | Job queues, audit logs, replayable events | Heavy‑duty enterprise messaging |
| Complexity | Minimal – two commands | Medium – streams + consumer groups | High – deployment, config, protocols |
When to choose pub/sub: Pure live updates—chat messages that shouldn't be stored, real‑time dashboard refreshes, broadcast alerts where missing a message is acceptable. If you need durability or guaranteed delivery, upgrade to Redis Streams.
Troubleshooting & Edge Cases
“I published but my subscriber didn’t receive the message”
- Subscriber subscribed after the publish – Pub/sub delivers only to currently subscribed clients. Publish after the SUBSCRIBE arrives.
- Wrong channel name – Channel names are case‑sensitive.
"Alerts"≠"alerts". - Connection type mismatch – If you publish from a connection that is already subscribed, you’ll get an error:
ERR only (P)SUBSCRIBE / (P)UNSUBSCRIBE / QUIT allowed in this context. Use a dedicated connection for publishing.
“My subscriber blocks forever”
SUBSCRIBE blocks the connection. You cannot issue other Redis commands on that connection while subscribed. In Python, use a separate connection for publishing.
“Subscribers receive duplicate messages”
A single PUBLISH is delivered exactly once to each subscriber. If you see duplicates, check if multiple subscriber scripts are running on the same channel.
What You Learned & What's Next
You now understand that Redis pub/sub is a lightweight, non‑persistent messaging pattern ideal for real‑time broadcasting. You can publish messages to channels with PUBLISH, subscribe with SUBSCRIBE, and handle messages in Python using the pubsub interface. You also know when to choose pub/sub over Streams or traditional message brokers.
Next step: Learn how to subscribe to multiple channels at once with pattern‑based subscriptions using PSUBSCRIBE, or dive into Redis Streams for durable, replayable message processing.
Practice recap
Try this: Open two redis-cli terminals. In one, SUBSCRIBE weather. In the other, PUBLISH weather "Rain expected at 3 PM". Watch the message appear in the first terminal. Now close the subscriber, publish again, and notice the count returns 0. This exercise solidifies the ephemeral nature of pub/sub – a perfect foundation before moving to pattern subscriptions with PSUBSCRIBE.
Common mistakes
- Trying to use a subscribed connection for other Redis commands – you must use a separate connection for publishes.
- Assuming messages are persisted – if no subscriber is listening, the message is lost forever.
- Mixing up channel name case – Redis channel names are case‑sensitive (
Alertsvsalerts). - Expecting message order guarantees across different subscribers – each subscriber receives messages sequentially, but two subscribers may process at different rates.
Variations
- Use
PSUBSCRIBEwith glob‑style patterns (e.g.,orders:*) to subscribe to multiple related channels at once. - Implement a custom pub/sub relay by using
SUBSCRIBE+PUBLISHon the same client (on different connections) to filter or transform messages. - Combine pub/sub with Lua scripts to atomically publish a message and update a key in a single step.
Real-world use cases
- Live chat room – every message a user sends is published to a channel; all other participants in that room receive it instantly.
- Real‑time dashboard updates – a backend publishes new metrics (e.g., CPU load, request rate) to a channel every second; frontend subscribers refresh the display without polling.
- IoT sensor alerts – a temperature sensor publishes 'overheat' to an alert channel; all subscribed alert handlers (SMS, email, logging) act on it simultaneously.
Key takeaways
- Redis pub/sub is a fire‑and‑forget messaging pattern – messages are not stored and are lost if no subscriber is listening.
- Use
PUBLISH channel messageto send a message andSUBSCRIBE channelto receive messages – case‑sensitive channel names. - A subscribed connection cannot execute other Redis commands; always use a separate connection for publishing.
- Pub/sub is ideal for ephemeral real‑time updates (live chat, notifications) but not for durable message processing.
- The
PUBLISHcommand returns the number of subscribers that received the message – a quick health check. - For replayable or guaranteed delivery, upgrade to Redis Streams instead of pub/sub.
Keep learning
Related tutorials, quizzes, and articles for this topic.
Discussion
Questions, corrections, and tips help everyone reading this page.
0 comments
Add a comment
No comments yet — start the thread.