Advertisement
Intermediate Redis, Keyspace Notifications

How do you subscribe to and handle a specific type of keyspace notification, such as being alerted whenever a key expires?

Short answer

You subscribe to the special channel named __keyevent@0__:expired, where zero represents the database number, using a regular Pub/Sub SUBSCRIBE command, and your application then receives a message containing the name of the key each time one expires in that particular database.

Save Redis mock interview
Advertisement
AModel answer
You subscribe to the special channel named __keyevent@0__:expired, where zero represents the database number, using a regular Pub/Sub SUBSCRIBE command, and your application then receives a message containing the name of the key each time one expires in that particular database.
Example

SUBSCRIBE __keyevent@0__:expired -- Your application receives a message -- containing the key name each time a key expires

Real-world example
A cache warming system subscribes to expired key events, automatically triggering a background job to refresh a piece of cached data the moment it actually expires, rather than waiting for the next request to trigger a slow regeneration.
Likely follow-ups
  • Does this notification tell you what the expired key's value was before it expired?
  • How do you subscribe to notifications for a database other than the default one?
Related topics