Key-based Publish/Subscribe in Redis
System Design practice on Codemia
Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.
Redis is an advanced key-value store, widely used for its support of diverse data structures, high availability, and low-latency performance. One of its compelling features is the support for a pub/sub (publish-subscribe) messaging paradigm. This enables clients to subscribe to, and receive events or messages published to specific channels. Here, we'll dive into a specialized aspect of Redis pub/sub known as key-based publish/subscribe.
Understanding Key-based Publish/Subscribe
Key-based publish/subscribe extends the basic functionality where subscribers listen to messages on a channel. It allows clients to subscribe to all keys matching a given pattern. Whenever events of interest occur on these keys (such as updates or deletions), notifications are dispatched to the subscribers.
Technical Setup
Key-based notifications in Redis are not turned on by default to preserve efficiency. To enable them, you need to modify the notify-keyspace-events setting in the Redis configuration or use the CONFIG SET command:
Here, different flags enable notifications for different types of events:
K: Keyspace eventsE: Keyevent eventsA: Alias for all events
For instance, if you're interested only in key expiration and deletion events, you would set it as:
Listening to Key Events
To subscribe to key events, you use special channel names that Redis supports:
__keyspace@<db>__: This prefix allows you to listen to events about keys. For example,__keyspace@0__:mykeywould enable you to receive notifications about changes tomykeyin database 0.__keyevent@<db>__: This prefix helps listen to specific types of commands affecting keys. For instance,__keyevent@0__:setlets you monitor allsetoperations in database 0.
Subscribing via Redis CLI would look like:
Practical Example
Let's assume an application needs to monitor changes to a user session key in a Redis store. Here’s how this could be accomplished:
- Enabling Notifications: First, enable notifications for key expiration (
x) and set commands (s):
- Creating a Subscription: Setting up subscription to the key and the event:
- Handling Events: Your application or service needs to handle messages received from these subscriptions, typically using a Redis client library in your programming language of choice. The client will receive messages that include the type of event and the key it pertained to.
Implementation Considerations
When implementing key-based notifications:
- Performance: Always consider the impact of enabling notifications as they can lead to increased I/O, CPU usage, and network traffic.
- Security: Ensure that only authorized subscribers can listen to key events, especially in environments handling sensitive data.
- Scalability: Make sure your subscriber logic can handle the volume of notifications without becoming a bottleneck.
Summary Table
| Feature | Key-based Pub/Sub | General Pub/Sub |
| Subscription Criteria | Key patterns | Channel names |
| Utility | High for specific key events monitoring | Broad for generic message broadcasting |
| Setup Complexity | Moderate (requires configuration change) | Low |
| Performance Consideration | High impact potential | Moderate |
| Use Case | Real-time monitoring and triggering based on key events | Chat systems, real-time updates, etc. |
Key-based publish/subscribe in Redis offers a powerful way to monitor and react to changes in database keys in real-time, making it ideal for scenarios requiring responsive, event-driven functionality. By understanding and effectively using this feature, developers can build highly interactive and dynamic applications.
Related reading
- Key-Value storage with realtime multimaster replication
- Knex.js - node process never exits, how to close it gracefully - but only when all queries are resolved?
- KSQL table not showing data but Stream with same structure returning data
- Kubernetes - Pod which encapsulates DB is crashing
- Kubernetes MongoDB operator - Invalid featureCompatibilityVersion document in admin.system.version
- Kubernetes MySql image persistent volume is non empty during init
- Kubernetes pod cannot connect to external Database
- Kubernetes rolling deployments and database migrations

System Design Fundamentals
Build a strong foundation in designing scalable, reliable distributed systems.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
System Design practice on Codemia
Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.