Pub/Sub
Redis Pub/Sub is fire-and-forget messaging — PUBLISH delivers to all subscribers currently connected; no persistence, no ack, no replay.
Introduction
Redis Pub/Sub is fire-and-forget messaging — PUBLISH delivers to all subscribers currently connected; no persistence, no ack, no replay. WhatsApp-style live notifications and config push use it when subscribers must react in real time and missed messages are acceptable.
SUBSCRIBE blocks the connection for message delivery — use dedicated subscriber connections, not your command pool. Pattern subscribe PSUBSCRIBE matches channels with globs.
Need message retention or consumer groups — use Streams instead.
Understanding the topic
Key concepts
- SUBSCRIBE channel — receive messages on channel.
- PUBLISH channel message — fan-out to subscribers.
- PSUBSCRIBE pattern — wildcard channels.
- No message stored if no subscriber online.
- At-most-once delivery semantics.
- Separate connection required for subscribe mode.
flowchart LRPublisher -->|PUBLISH| ChannelChannel --> SubAChannel --> SubB
Step-by-step explanation
- Publisher sends PUBLISH with channel and payload.
- Redis looks up subscriber list for channel.
- Message pushed to each subscriber socket buffer.
- Subscriber client reads message in push format.
- Unsubscribe removes client from channel list.
Syntax reference
Common commands
- Subscriber connection cannot run normal commands easily.
- Messages not persisted — subscriber offline = lost.
- Keep payloads small JSON.
# Terminal 1SUBSCRIBE orders:created# Terminal 2PUBLISH orders:created '{"id":99}'# PatternPSUBSCRIBE events:*
Informative example
Publish order event from redis-cli after DB commit:
# After successful INSERT in migration scriptredis-cli PUBLISH notifications:order \'{"orderId":12345,"status":"PAID","userId":42}'
Spring RedisMessageListenerContainer wraps SUBSCRIBE in managed threads. WebSocket gateway subscribes and pushes to browsers.
Real-world use
Real-world use cases
- Live dashboard metric push.
- Cache invalidation broadcast to all app nodes.
- Chat room message fan-out (with DB as source of truth).
- Config change notify restart hooks.
- Presence change notifications.
Best practices
- Dedicated subscriber connections per service.
- Keep messages idempotent on receiver — duplicates possible on reconnect storms.
- Use Streams when replay needed.
- Monitor client output buffer limits — slow subscribers dropped.
- Channel naming: service:event:entity.
- Don't pub/sub for critical financial events alone.
Common mistakes
- Expecting at-least-once or persistence.
- SUBSCRIBE on shared Lettuce connection used for GET/SET.
- Huge messages saturating output buffers.
- No handler for subscriber reconnect.
Advanced interview questions
Q1BeginnerPub/Sub delivery guarantee?
Q2BeginnerPUBLISH vs XADD?
Q3IntermediateWhy separate subscriber connection?
Q4IntermediateSlow subscriber problem?
Q5AdvancedReplace Kafka with Pub/Sub?
Summary
Pub/Sub = realtime fan-out, no persistence.