Maintenance

Site is under maintenance — quizzes are still available.

Go to quizzes

Redis Pub/Sub

Learn Redis Pub/Sub: messaging pattern for real-time communication between publishers and subscribers, with hands-on walkthrough and troubleshooting.

Focus: understand redis pub/sub

Sponsored

Imagine you need to broadcast a message to multiple parts of your application instantly—like a score update in a live game or a notification when a user logs out across devices. Without a proper messaging system, you'd end up with polling loops, tight coupling, or complex web of callbacks. Redis Pub/Sub solves this cleanly: it decouples message producers from consumers, letting you broadcast events in real time with minimal overhead. This lesson will demystify Redis Pub/Sub, show you exactly how it works, and equip you to use it confidently in your projects.

The problem this lesson solves

Modern applications often need to react to events in real time: chat messages, price changes, system alerts, or coordination between microservices. Traditional approaches like direct HTTP calls, polling databases, or custom message queues add latency, complexity, and tight coupling. When one service crashes, the others may miss events entirely. Redis Pub/Sub addresses this by providing a lightweight, fire-and-forget publish-subscribe pattern that's built into Redis—no extra infrastructure required. You get low-latency broadcasts with a simple, proven API.

Core concept / mental model

Think of Redis Pub/Sub as a radio station. A publisher is the radio host who speaks into a microphone (a channel). Many subscribers are listeners tuned to that specific frequency (the channel name). When the host says something, every listener tuned in hears it simultaneously. Subscribers can also tune out any time. The station doesn't know who's listening and doesn't care—it just broadcasts. Redis acts as the radio tower: it takes the message from the publisher and pushes it to all active subscribers on that channel. There is no message persistence, no confirmation of delivery, and no queue—what you send is broadcast instantly, and if nobody is listening, the message vanishes.

Key definitions

  • Channel: a named topic (e.g., chat:room1, system:alerts). Subscribers listen on one or more channels.
  • Publisher: a client that sends a message to a channel.
  • Subscriber: a client that receives messages from channels it's subscribed to.
  • Message: a string (or binary-safe payload) published to a channel.

How it works step by step

To understand the flow, follow this sequence:

  1. A subscriber connects to Redis and issues the SUBSCRIBE command with one or more channel names. This puts the connection into "subscriber mode".
  2. The subscriber enters a listening loop—it blocks, waiting for incoming messages. In subscriber mode, the client cannot run other commands like GET or SET. It can only receive messages or unsubscribe.
  3. A publisher connects (any Redis client, possibly on a different connection or even a different machine) and sends PUBLISH <channel> <message>.
  4. Redis receives the publish and instantly forwards the message to all subscribers currently subscribed to that channel.
  5. The subscriber receives the message as a multi-bulk reply: typically three elements — the type (message), the channel name, and the payload.
  6. Messages are fire-and-forget — if a subscriber disconnects between publishes, it misses all messages sent while offline.

Pro tip: Because subscribers block, you typically run pub/sub logic in dedicated threads or processes. Never use a Redis connection for both pub/sub and regular commands—the connection will get stuck waiting for messages.

Hands-on walkthrough

Let's get our hands dirty. You'll need Redis running (local or remote) and the redis-cli tool. Open two terminal windows: one for publishing (terminal A) and one for subscribing (terminal B).

Step 1: Subscribe to a channel

In terminal B, run:

redis-cli
127.0.0.1:6379> SUBSCRIBE news:alerts
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "news:alerts"
3) (integer) 1

The response confirms a subscription to news:alerts. The connection is now blocked, waiting for messages.

Step 2: Publish a message

In terminal A, run:

redis-cli
127.0.0.1:6379> PUBLISH news:alerts "Server load high - take action!"
(integer) 1

The return value 1 means one subscriber received it.

Back in terminal B, you'll see:

1) "message"
2) "news:alerts"
3) "Server load high - take action!"

The subscriber received the exact message in real time.

Step 3: Publish with multiple subscribers

Open terminal C and subscribe to the same channel:

redis-cli
127.0.0.1:6379> SUBSCRIBE news:alerts

Now from terminal A:

127.0.0.1:6379> PUBLISH news:alerts "Database connection pool nearly full"
(integer) 2

Both terminal B and C receive the message instantly.

Step 4: Use pattern subscriptions (advanced)

Redis supports glob-style pattern matching with PSUBSCRIBE. For example, to listen to all channels starting with chat::

127.0.0.1:6379> PSUBSCRIBE chat:*
Reading messages... (press Ctrl-C to quit)
1) "psubscribe"
2) "chat:*"
3) (integer) 1

Now a publish to chat:room1 or chat:room2 will reach this subscriber.

Pro tip: Pattern subscriptions are powerful for multi-tenant systems. But be aware of possible overlap: if you subscribe to both chat:* and chat:room1, you'll get duplicate messages for chat:room1.

Compare options / when to choose what

Redis Pub/Sub is not the only messaging option in the Redis ecosystem. Here's how it stacks up against alternatives:

Feature Redis Pub/Sub Redis Streams Redis Lists (as queue)
Message persistence No Yes (configurable) Yes (as long as list exists)
Delivery guarantee At-most-once At-least-once, exactly-once possible At-most-once (pop)
Message order Not guaranteed across channels Guaranteed within a stream Flimsy (depends on operations)
Consumer groups No Yes (group management) No (manual coordination)
Backpressure handling None (messages lost if subscriber slow) Able (with pending entries) Only if client processes fast
Use case Real-time broadcasts, notifications, chat Event sourcing, log replay, job queues Simple task queues

When to prefer Redis Pub/Sub: - You need instant, one-to-many broadcasting (no message retention). - You are okay with at-most-once delivery (messages can be lost if no subscriber is listening). - You want minimal latency and overhead. - Use cases: live score updates, system alerts, cache invalidation notifications.

When to avoid it: - You need guaranteed delivery or replay of missed messages → use Redis Streams. - You need to coordinate multiple workers consuming from a queue → use Redis Streams with consumer groups. - You need to buffer messages temporarily → consider Redis Lists with a dedicated worker.

Troubleshooting & edge cases

Problem: Messages are not reaching certain subscribers

Symptom: Some clients don't receive publishes.

Causes and fixes: - Subscriber not subscribed at publish time — remember, messages are not queued. Ensure the subscriber's SUBSCRIBE command runs before the publish. - Channel name mismatch — check for trailing spaces, uppercase/lowercase differences. Redis channels are case-sensitive. - Firewall or network partition — if a subscriber's connection is interrupted, messages are lost. Implement a reconnection loop.

Problem: Subscriber receives messages from unintended channels (with PSUBSCRIBE)

Symptom: Pattern chat:* also matches chat:special when you only wanted chat:general.

Fix: Use specific SUBSCRIBE for exact channels, or refine your pattern (e.g., chat:general with PSUBSCRIBE is useless—just use SUBSCRIBE). Or match more precisely: PSUBSCRIBE chat:general:*.

Problem: Blocked connection never unblocks

Symptom: SUBSCRIBE hangs indefinitely.

Causes: - No publisher for that channel. Wait for a publish or use UNSUBSCRIBE from a different connection (not possible—the blocked connection can't process commands). You must kill the client or wait for a timeout. - The Redis client library doesn't handle subscribe mode correctly. Use libraries that support non-blocking pub/sub (e.g., redis-py with publish/subscribe in separate threads).

What you learned & what's next

You now understand the core idea behind Redis Pub/Sub: a lightweight, fire-and-forget messaging pattern where publishers broadcast messages to all subscribed clients on a channel. You've subscribed and published manually using redis-cli, seen pattern subscriptions with PSUBSCRIBE, and compared Pub/Sub with Redis Streams and Lists. You know that Pub/Sub is best for real-time broadcasting without persistence, but not for guaranteed delivery or queue-based workloads.

Next up: In the next lesson, you'll explore Redis Streams—a more robust messaging system that supports message persistence, consumer groups, and replay. You'll learn how to build reliable event pipelines that don't lose messages even when subscribers go offline.

Ready? Subscribe to the next chapter!

Practice recap

Open two terminal windows. In one, subscribe to the channel mychannel. In the other, publish three different messages to mychannel. Verify that the subscriber receives all three. Next, subscribe to a pattern like test:* in one terminal, and publish to test:alpha and test:beta in another. Confirm both messages arrive. This will solidify your understanding of both exact and pattern subscriptions.

Common mistakes

  • Forgetting that messages are not buffered: If a subscriber isn't active at the exact moment a message is published, the message is lost forever. Never rely on Pub/Sub for critical notifications without a fallback.
  • Mixing Pub/Sub and regular commands on the same connection: After SUBSCRIBE, the connection enters subscriber mode and cannot execute commands like GET or SET. Always use separate connections for pub/sub and data operations.
  • Using PUBLISH without confirming subscribers: The return value of PUBLISH only tells you how many subscribers received it instantly. It doesn't mean they processed it correctly—or are even alive.
  • Misapplying Pub/Sub for persistent queues: If you need message replay, buffering, or at-least-once delivery, choose Redis Streams or Lists. Pub/Sub is best for ephemeral broadcasts only.

Variations

  1. Pattern subscription with PSUBSCRIBE: Instead of subscribing to exact channel names, use glob patterns like chat: or system:alerts: to match multiple channels at once.
  2. Client-side filtering: In some languages (e.g., Python with redis-py), you can implement a non-blocking listener using threading or asyncio, while still running other Redis commands on the same client connection using a separate pub/sub instance.
  3. Redis Pub/Sub with TLS: For secure deployments, you can encrypt pub/sub traffic by configuring Redis with TLS enabled. The protocol remains the same, but messages are transmitted over encrypted connections.

Real-world use cases

  • Live chat rooms: Each chat room is a Redis channel (e.g., chat:room:42). Users join via WebSocket, which subscribes to the channel, and messages are published in real time to all participants.
  • Cache invalidation across services: When a microservice updates a shared cached key (e.g., user profile), it publishes to cache:invalidate. All services subscribed clear their local cache for that key.
  • System-wide alerts: A monitoring agent publishes critical alerts to system:alerts. A central dashboard subscribes to this channel and displays alerts to operators instantly, with no polling overhead.

Key takeaways

  • Redis Pub/Sub is a fire-and-forget messaging pattern for real-time broadcasts—no persistence, no queues.
  • Use SUBSCRIBE (or PSUBSCRIBE with patterns) to listen to channels; use PUBLISH to send messages.
  • Subscriber connections block after SUBSCRIBE—always use dedicated connections or threads for pub/sub.
  • Redis Pub/Sub is ideal for ephemeral, at-most-once delivery use cases like chat, alerts, and live updates.
  • For persistent messaging or consumer group coordination, prefer Redis Streams over Pub/Sub.
  • Messages are lost if no subscriber is listening at publish time—design your system to tolerate this, or use a different message pattern.

Sponsored

Sponsored

Discussion

Questions, corrections, and tips help everyone reading this page.

0 comments

Add a comment

Shown publicly with your comment.

Be constructive · max 4,000 characters

No comments yet — start the thread.

Related tutorials, quizzes, and articles for this topic.