Reading — step 1 of 3
Pub/Sub Messaging
~1 min readAdvanced Features
SUBSCRIBE & PUBLISH — Pub/Sub Messaging
Redis Pub/Sub lets clients communicate through message channels without knowing about each other — the publish-subscribe pattern.
How It Works
- Subscriber calls
SUBSCRIBE channel— starts listening - Publisher calls
PUBLISH channel message— sends to all subscribers - Subscriber receives:
message <channel> <message>
Real-World Uses
- Chat rooms: each room is a channel
- Live notifications: subscribe to
notifications:user:123 - Cache invalidation: publish when data changes, subscribers flush their cache
- Event-driven architecture: microservices communicate via channels
Fire and Forget
Pub/Sub is fire-and-forget — if no one is subscribed when a message is published, it's lost forever. This is NOT a queue (use Redis Streams for that).
Our Simplified Model
Since stdin/stdout is single-client, we simulate it: when PUBLISH is called and the client is subscribed to that channel, output the message. PUBLISH returns the number of matching subscriptions.
Implementation
Track subscriptions as a set of channel names. On PUBLISH, check if the channel is in the set.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…