Implement Redis Pub/Sub Messaging in Python
Build real-time pub/sub messaging with Redis and Python including pattern subscriptions, message serialization, connection pooling, and broadcast patterns for microservices.
Overview
Redis Pub/Sub is a lightweight messaging pattern where publishers send messages to channels and subscribers receive them in real-time. Unlike queues, there’s no persistence — if no subscriber is listening, the message is gone. That trade-off is the whole point: you get dead-simple fan-out to every listener at once, in exchange for durability you’ll have to build yourself when it matters.
Below: publishing and subscribing with Python, pattern subscriptions with wildcards, structured message serialization, connection management, and broadcast patterns for microservice communication.
When to Use This
- Real-time notifications (chat messages, live updates, status changes)
- Cache invalidation across service instances
- Microservice event broadcasting (config changes, feature flags)
- Any fire-and-forget messaging where message loss is acceptable
Prerequisites
- Python 3.10+
- Redis server (local or cloud)
redispackage
Solution
1. Basic Publisher and Subscriber
import redis
import json
# Publisher
def publish_message(channel: str, message: dict):
r = redis.Redis(host='localhost', port=6379, db=0)
r.publish(channel, json.dumps(message))
print(f"Published to {channel}: {message}")
# Subscriber
def subscribe_channel(channel: str):
r = redis.Redis(host='localhost', port=6379, db=0)
pubsub = r.pubsub()
pubsub.subscribe(channel)
print(f"Subscribed to {channel}")
for message in pubsub.listen():
if message['type'] == 'message':
data = json.loads(message['data'])
print(f"Received: {data}")
# Usage
publish_message('events', {'type': 'user.created', 'userId': '123'})
# In another process
subscribe_channel('events')
2. Pattern Subscription (Wildcards)
import redis
import json
def subscribe_pattern(pattern: str):
r = redis.Redis(host='localhost', port=6379, db=0)
pubsub = r.pubsub()
pubsub.psubscribe(pattern)
print(f"Subscribed to pattern: {pattern}")
for message in pubsub.listen():
if message['type'] == 'pmessage':
channel = message['channel'].decode('utf-8')
data = json.loads(message['data'])
print(f"Channel={channel}, Data={data}")
# Subscribe to all user events: user.created, user.updated, user.deleted
subscribe_pattern('user.*')
# Subscribe to all events from any service
subscribe_pattern('service.*.events')
3. Structured Message Handler
import redis
import json
import logging
from dataclasses import dataclass, asdict
from typing import Optional
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
@dataclass
class Event:
event_type: str
source: str
payload: dict
timestamp: str
correlation_id: Optional[str] = None
class EventBus:
def __init__(self, host: str = 'localhost', port: int = 6379):
self.redis = redis.Redis(host=host, port=port, db=0, decode_responses=True)
def publish(self, channel: str, event: Event):
message = json.dumps(asdict(event))
subscribers = self.redis.publish(channel, message)
logger.info(f"Published to {channel}: {subscribers} subscribers received")
def subscribe(self, channels: list, handler):
pubsub = self.redis.pubsub()
pubsub.subscribe(channels)
for message in pubsub.listen():
if message['type'] == 'message':
event = Event(**json.loads(message['data']))
handler(event, message['channel'])
def psubscribe(self, patterns: list, handler):
pubsub = self.redis.pubsub()
pubsub.psubscribe(patterns)
for message in pubsub.listen():
if message['type'] == 'pmessage':
event = Event(**json.loads(message['data']))
handler(event, message['channel'])
# Usage
bus = EventBus()
# Publish
bus.publish('user.events', Event(
event_type='user.created',
source='auth-service',
payload={'userId': '123', 'email': 'user@example.com'},
timestamp='2026-07-03T10:00:00Z',
correlation_id='req-abc',
))
# Subscribe
def handle_event(event: Event, channel: str):
logger.info(f"[{channel}] {event.event_type}: {event.payload}")
bus.subscribe(['user.events', 'order.events'], handle_event)
4. Multi-Service Broadcast
import redis
import json
from datetime import datetime, timezone
class ServiceBroadcaster:
"""Broadcast events to all instances of a service via pub/sub."""
def __init__(self, service_name: str, instance_id: str):
self.redis = redis.Redis(host='localhost', port=6379, db=0, decode_responses=True)
self.service_name = service_name
self.instance_id = instance_id
self.channel = f'{service_name}.broadcast'
def broadcast(self, event_type: str, data: dict):
message = json.dumps({
'event_type': event_type,
'source': self.instance_id,
'data': data,
'timestamp': datetime.now(timezone.utc).isoformat(),
})
self.redis.publish(self.channel, message)
def listen(self, handler):
pubsub = self.redis.pubsub()
pubsub.subscribe(self.channel)
for message in pubsub.listen():
if message['type'] == 'message':
event = json.loads(message['data'])
# Skip own messages
if event['source'] != self.instance_id:
handler(event)
# Usage: cache invalidation across instances
broadcaster = ServiceBroadcaster('api-service', 'instance-1')
# Broadcast cache invalidation
broadcaster.broadcast('cache.invalidate', {'keys': ['user:123', 'user:456']})
# Listen for invalidation events
def on_invalidate(event):
if event['event_type'] == 'cache.invalidate':
for key in event['data']['keys']:
local_cache.delete(key)
print(f"Invalidated: {key}")
broadcaster.listen(on_invalidate)
5. Pub/Sub with Redis Streams Fallback
import redis
import json
class ReliableEventBus:
"""Pub/Sub with Redis Streams for persistence — subscribers that
reconnect can read missed events from the stream."""
def __init__(self, host: str = 'localhost'):
self.redis = redis.Redis(host=host, port=6379, db=0, decode_responses=True)
def publish(self, channel: str, message: dict):
# Publish to pub/sub for real-time subscribers
self.redis.publish(channel, json.dumps(message))
# Also append to a stream for persistence
stream_key = f'stream:{channel}'
self.redis.xadd(stream_key, {'data': json.dumps(message)})
def subscribe_realtime(self, channel: str, handler):
pubsub = self.redis.pubsub()
pubsub.subscribe(channel)
for message in pubsub.listen():
if message['type'] == 'message':
handler(json.loads(message['data']))
def subscribe_replay(self, channel: str, handler, last_id: str = '0'):
"""Read missed events from the stream after reconnection."""
stream_key = f'stream:{channel}'
events = self.redis.xread({stream_key: last_id}, block=0)
for _stream, messages in events:
for msg_id, fields in messages:
handler(json.loads(fields['data']))
# Update last read ID for next call
6. Threaded Subscriber
import redis
import json
import threading
import logging
logger = logging.getLogger(__name__)
class ThreadedSubscriber:
def __init__(self, host: str = 'localhost'):
self.redis = redis.Redis(host=host, port=6379, db=0, decode_responses=True)
self._threads = []
self._running = True
def subscribe(self, channel: str, handler):
def listen():
pubsub = self.redis.pubsub()
pubsub.subscribe(channel)
logger.info(f"Listening on {channel}")
for message in pubsub.listen():
if not self._running:
break
if message['type'] == 'message':
try:
handler(json.loads(message['data']))
except Exception as e:
logger.error(f"Handler error: {e}")
pubsub.unsubscribe(channel)
pubsub.close()
thread = threading.Thread(target=listen, daemon=True)
thread.start()
self._threads.append(thread)
def stop(self):
self._running = False
for t in self._threads:
t.join(timeout=5)
# Usage
subscriber = ThreadedSubscriber()
def on_user_event(data):
print(f"User event: {data}")
def on_order_event(data):
print(f"Order event: {data}")
subscriber.subscribe('user.events', on_user_event)
subscriber.subscribe('order.events', on_order_event)
# Main thread continues doing other work
# subscriber.stop() when shutting down
Pub/Sub vs Streams vs RabbitMQ
The first decision is not how to use Pub/Sub — it’s whether Pub/Sub is the right tool. Messages here are fire-and-forget: Redis delivers to whoever is listening right now and keeps nothing.
| Pub/Sub | Redis Streams | RabbitMQ | |
|---|---|---|---|
| Persistence | None | Append-only log | Durable queues |
| Missed messages | Lost | Replayable | Requeued |
| Fan-out to many listeners | Yes, trivially | Via consumer groups | Via exchanges |
| Backpressure handling | Buffer, then disconnect | Consumer groups | Built-in |
| Throughput | ~100k+ msg/s | High, with overhead | Lower, more features |
Rule of thumb: notifications, cache invalidation, and live dashboards → Pub/Sub. Anything you can’t afford to lose → Streams. Complex routing or cross-language durability → RabbitMQ.
Backpressure and Slow Subscribers
Redis pushes messages to each subscriber as fast as they arrive. A slow consumer doesn’t slow the publisher — instead Redis buffers messages in the client’s output buffer. When that buffer exceeds client-output-buffer-limit (default 32MB for pub/sub clients), Redis kills the connection and the subscriber misses everything since.
That makes the handler the bottleneck to watch. Do the slow work — database writes, API calls — off the listen loop: push events onto an in-process queue and let a worker pool consume them, or the listen thread falls behind until Redis drops it.
Channel Naming
Flat channel names get messy fast. A convention that holds up in multi-service systems:
service.eventfor domain events:user.created,order.shippedservice.broadcastfor fan-out within one service’s instancesenv.channelprefixing (prod.,staging.) when environments share a Redis
Pattern subscriptions follow the same scheme — user.* catches every user event, *.broadcast catches every service’s internal fan-out.
How It Works
- Channels: Publishers send messages to named channels. Subscribers listen on channels. Redis routes messages from publishers to all active subscribers on that channel.
- Pattern subscriptions:
psubscribetakes glob-style patterns —*for any run of chars,?for one. Souser.*grabsuser.created,user.updated— the whole family. - No persistence: Pub/Sub keeps nothing on disk. If nobody’s tuned in at that instant, it’s gone for good. For durability, use Redis Streams alongside Pub/Sub.
- Fire-and-forget: The publisher doesn’t know if any subscribers received the message.
publish()does hand you back the count of subscribers it hit, but it never waits to hear whether they did anything with it. - Connection isolation: Each subscriber needs its own Redis connection. The
redis-pypubsub object blocks onlisten(), so it can’t share a connection with other operations.
Variants
Sharded Pub/Sub (Redis 7.0+)
Classic Pub/Sub broadcasts every message to every cluster node, which wastes bandwidth as the cluster grows. Sharded pub/sub routes messages through shard slots instead — worth switching to once you’re actually on a cluster.
# Sharded pub/sub uses cluster shard slots for message routing
# This ensures messages stay within the shard, reducing network overhead
r = redis.RedisCluster(host='localhost', port=7000)
r.spublish('user.events', json.dumps({'type': 'created', 'id': '123'}))
Pub/Sub with Sentinel for HA
If your Redis sits behind Sentinel for failover, don’t connect subscribers to a fixed host — ask Sentinel for the current master, or a failover silently drops your listeners onto a dead address.
from redis.sentinel import Sentinel
sentinel = Sentinel([
('localhost', 26379),
('localhost', 26380),
], socket_timeout=0.5)
master = sentinel.master_for('mymaster', socket_timeout=0.5)
master.publish('events', json.dumps({'type': 'test'}))
slave = sentinel.slave_for('mymaster', socket_timeout=0.5)
pubsub = slave.pubsub()
pubsub.subscribe('events')
Rate-Limited Publisher
Some consumers — webhook receivers, external APIs — can’t absorb bursts. A simple interval check throttles publishes without a full rate-limiting system.
import time
import redis
class RateLimitedPublisher:
def __init__(self, redis_client, max_per_second: int = 100):
self.redis = redis_client
self.max_per_second = max_per_second
self.min_interval = 1.0 / max_per_second
self._last_publish = 0
def publish(self, channel: str, message: str):
now = time.time()
elapsed = now - self._last_publish
if elapsed < self.min_interval:
time.sleep(self.min_interval - elapsed)
self.redis.publish(channel, message)
self._last_publish = time.time()
Best Practices
- Use Pub/Sub for fire-and-forget: notifications, cache invalidation, live dashboards — that’s where it shines. The moment you need a delivery guarantee, reach for Redis Streams or RabbitMQ instead.
- Serialize as JSON: boring, readable, and every language already speaks it. Only look at MessagePack once throughput actually becomes a problem.
- Use separate connections for pub and sub: the listener sits blocked inside
listen(), so grab a second Redis connection for publishing or it’ll deadlock on itself. - Handle reconnection: If the subscriber disconnects, it misses messages. Use Redis Streams as a fallback to replay missed events on reconnection.
- Use pattern subscriptions wisely:
psubscribe('*')subscribes to everything — it can overwhelm the subscriber. Stick to narrow patterns likeuser.*orservice.*.events. - Clean up on shutdown: Always
unsubscribeand close the pubsub connection when shutting down. Leaked connections consume Redis resources. - For the wider architecture picture — event storms, sagas, schema evolution — see the Complete Guide to Event-Driven Systems.
Common Mistakes
Before the list, one habit worth building: test message loss on purpose. Kill a subscriber mid-stream and watch what your system does — if the answer surprises you, fix it before production does.
- Expecting message persistence: Pub/Sub doesn’t store messages. Subscriber down? Those messages never existed, as far as Pub/Sub is concerned. Use Streams for durability.
- Sharing one connection for pub and sub: The subscriber blocks the connection. Publish calls from the same connection will block or fail.
- Not handling deserialization errors: one malformed message and
json.loadsblows up your listener. Wrap it in try/except so a bad payload doesn’t kill the loop. - Subscribing to too many channels: every extra subscription eats memory and CPU for no benefit. Trim that list down to what you actually use.
- Not testing message loss: pull the plug on a subscriber and see what breaks. If message loss is unacceptable, don’t use Pub/Sub — use Streams.
- Blocking work inside the handler: A handler that runs a slow query holds up every message behind it; offload to a queue or pool as shown in the threaded variant.
Further Reading
- Redis Pub/Sub documentation — delivery semantics and the fire-and-forget contract
- Sharded Pub/Sub —
SPUBLISH/SSUBSCRIBEfor Redis Cluster in 7.0+ - Redis Streams introduction — the durable alternative shown in the fallback variant
- Event-driven systems guide — the cluster guide for the architecture this fits into
Frequently Asked Questions
What's the difference between Redis Pub/Sub and Redis Streams?
Pub/Sub is fire-and-forget — no persistence, no consumer groups, gone if nobody's listening. Streams are an append-only log with persistence, consumer groups, and replay. Use Pub/Sub for live notifications; Streams when losing an event is a bug.
Can multiple subscribers listen on the same channel?
Yes — every subscriber on a channel gets every message, which is exactly what you want for fan-out like cache invalidation across service instances. Each one still needs its own Redis connection, though — that's the part people tend to forget.
What happens if a subscriber is slow?
Instead, Redis stashes them in that client's output buffer until it catches up. When it exceeds client-output-buffer-limit, Redis disconnects the subscriber and it misses everything from that point. Keep handlers fast and offload slow work to a queue or thread pool.
How do I recover messages after a reconnect?
You don't — plain Pub/Sub keeps nothing. The ReliableEventBus variant above shows the usual fix: publish to Pub/Sub for live delivery and also XADD to a stream, so reconnecting clients can replay what they missed.
Is Redis Pub/Sub suitable for high-throughput messaging?
Throughput is a non-issue on one box — think 100k+ messages a second. On a cluster, classic Pub/Sub broadcasts to all nodes — switch to sharded Pub/Sub (SPUBLISH/SSUBSCRIBE) in Redis 7.0+ to keep messages inside a shard.
Related Resources
Build a RabbitMQ Consumer with Python and Pika
Create a RabbitMQ consumer and producer in Python using pika with durable queues, work dispatching, acknowledgments, dead-letter exchanges, and prefetch tuning.
RecipeImplement Redis Cache Invalidation in Node.js
Invalidate Redis cache entries in Node.js with TTL expiry, explicit deletion, pattern-based clearing, and pub/sub-based distributed invalidation.
RecipeDistributed Locking with Redis and Redlock
Implement distributed locks with Redis for mutual exclusion across processes, using SET NX with TTL and the Redlock algorithm for reliability
GuideComplete Guide to Event-Driven Systems
Design event-driven backends: event sourcing, CQRS, sagas, outbox pattern, idempotency, eventual consistency, and production patterns.
RecipeConnect to Redis
How to connect to Redis in Python, JavaScript, and Java — with AUTH, TLS, pooling, and the core data types you'll actually use.