Overview
Redis pub/sub enables real-time messaging between different parts of your application. The Upstash Redis SDK provides aSubscriber class that handles channel subscriptions and message delivery over HTTP using Server-Sent Events (SSE).
Pub/sub in Upstash Redis uses HTTP streaming with Server-Sent Events, not the traditional Redis protocol. This makes it compatible with serverless and edge environments.
Basic Usage
Subscribe to a Channel
Subscribe to Multiple Channels
Publishing Messages
Type Safety
Specify the message type when creating a subscriber:Event Listeners
Message Events
Listen for all messages across subscribed channels:Channel-Specific Events
Listen to messages from a specific channel:Subscription Events
Handle subscription lifecycle events:Error Events
Handle errors during subscription:Pattern Subscriptions
Subscribe to channels matching a pattern usingpsubscribe:
Multiple Patterns
Pattern-Specific Events
Managing Subscriptions
Unsubscribe from Channels
Get Subscribed Channels
Remove All Listeners
Practical Examples
Real-Time Chat
Notification System
Event Broadcasting
Multi-Channel Monitoring
Message Serialization
Automatic Deserialization
By default, messages are automatically deserialized from JSON:Disable Automatic Deserialization
To receive raw message strings:Important Notes
Connection Management
- Subscriptions use HTTP Server-Sent Events (SSE) for real-time updates
- Each subscription maintains a persistent HTTP connection
- Properly clean up subscriptions when done to avoid resource leaks
Performance Considerations
- Pattern subscriptions (
psubscribe) are more expensive than exact matches - Limit the number of concurrent subscriptions per client
- Use channel-specific event handlers for better performance