From Redis Keyspace Notifications

Keyspace notifications allow clients to subscribe to Pub/Sub channels in order to receive events affecting the Redis data set in some way.

Examples of events that can be received are:

All the commands affecting a given key.
All the keys receiving an LPUSH operation.
All the keys expiring in the database 0.

Events are delivered using the normal Pub/Sub layer of Redis, so clients implementing Pub/Sub are able to use this feature without modifications.

So, if you need just pub/sub, there is no need of extra configuration regarding Keyspace Notifications

Answer from usuario on Stack Overflow
🌐
GitHub
github.com › redis-developer › keyspace-notifications-node-redis
GitHub - redis-developer/keyspace-notifications-node-redis: Keyspace Notifications demo with Node Redis 4 · GitHub
This is a small project using Redis and Redis Keyspace Notifications. Keyspace notifications allow clients to subscribe to Pub/Sub channels in order to receive events affecting the Redis data set in some way.
Starred by 7 users
Forked by 2 users
Languages   Python 70.2% | JavaScript 29.8%
🌐
Medium
medium.com › @micah1powell › using-redis-keyspace-notifications-for-a-reminder-service-with-node-c05047befec3
Redis Keyspace Notifications for a Reminder Service with Node | by Micah Powell | Medium
January 13, 2018 - First, it sets a key and value into redis. This is the data that I need for my reminder notification and I will retrieve this data when I am ready to create the notification (this could be an hmset if you wanted to store multiple keys and values under a hash ).
Top answer
1 of 2
2

From Redis Keyspace Notifications

Keyspace notifications allow clients to subscribe to Pub/Sub channels in order to receive events affecting the Redis data set in some way.

Examples of events that can be received are:

All the commands affecting a given key.
All the keys receiving an LPUSH operation.
All the keys expiring in the database 0.

Events are delivered using the normal Pub/Sub layer of Redis, so clients implementing Pub/Sub are able to use this feature without modifications.

So, if you need just pub/sub, there is no need of extra configuration regarding Keyspace Notifications

2 of 2
0

key-space-notifications and pub/sub are 2 different concepts.

PUB/SUB: It's usual method publishing data to a channel and other clients can subscribe to the same channel by it's name. published messages are characterised into channels, without knowledge of what (if any) subscribers there may be.

This is enabled by default. messages are not persisted here, and once delivered/lost, messages cannot be retrieved.

key-space-notifications: This also a way of subscribing to Pub/Sub channels in order to receive events by the clients.

This we need to enable manually as this consumes little more CPU. Use below code to enable this

redisClient.configSet("notify-keyspace-events", "Ex");

we can subscribe to 2 different channels

  1. Key-space channel: receives the name of the event as message.
  2. Key-event channel: receives the name of the key as message.

example: To subscribe to key expired events, use the below code

export const subscribeForExpiry = () => {
  //.: Subscribe to the "notify-keyspace-events" 
  // channel used for expired type events
  client.configSet("notify-keyspace-events", "Ex");
  const sub = client.duplicate();
  sub.connect();

  sub.subscribe(
    `__keyevent@${process.env.REDIS_DATABASE_INDEX}__:expired`,
    (key) => {
      console.log("key=> ", key);
      // do something with key, can't retrieve value here
    }
  );
};
🌐
Redis
redis.io › docs › latest › develop › pubsub › keyspace-notifications
Redis keyspace notifications | Docs
1 day ago - Setting the parameter to the empty string disables notifications. In order to enable the feature a non-empty string is used, composed of multiple characters, where every character has a special meaning according to the following table: K Keyspace events, published with __keyspace@<db>__ prefix.
Top answer
1 of 1
17

You forgot to subscribe the subscriber client to a specific channel. Furthermore, if you want to watch for all events, you need to use pattern-based subscription.

You may want to do something like this (untested):

subscriber.on("pmessage", function (pattern, channel, message) {
    console.log("("+  pattern +")" + " client received message on " + channel + ": " + message);
    switch (channel) {
        // blah blah blah
        // ...
    }
});
subscriber.psubscribe(''__key*__:*')

See more information in the Redis documentation, and in node_redis examples.

Update:

Here is an example to illustrate the difference between channel subcription and pattern subscription. Proper error handling is omitted for brevity sake.

var redis = require("redis");

var client = redis.createClient('6379','127.0.0.1');
var subscriber1 = redis.createClient('6379','127.0.0.1');
var subscriber2 = redis.createClient('6379','127.0.0.1');

// First subscriber listens only to events occurring for key mykey
function S1(next) {
    subscriber1.on('message', function(channel, msg) {
        console.log( "S1: received on "+channel+" event "+msg )
    });
    subscriber1.subscribe( "__keyspace@0__:mykey", function (err) {
        next();
    });
}

// Second subscriber listens to events occuring for ALL keys
function S2(next) {
    subscriber2.on('pmessage', function(pattern,channel, msg) {
        console.log( "S2: received on "+channel+" event "+msg )
    });
    subscriber2.psubscribe( "__keyspace@0__:*", function (err) {
        next();
    });
}

// Do something with keys mykey and anotherkey
function do_something() {
    client.set("mykey","example", function( err ) {
        client.set("mykey", "another example", function( err ) {
            client.del("mykey", function( err ) {
                client.set("anotherkey","example", function( err ) {
                    client.del("anotherkey");
                });
            });
        });
    });
}

// Here we go
S1( function () {
    S2( function () {
        do_something();
    });
});

The result of this script is:

S1: received on __keyspace@0__:mykey event set
S2: received on __keyspace@0__:mykey event set
S2: received on __keyspace@0__:mykey event set
S1: received on __keyspace@0__:mykey event set
S1: received on __keyspace@0__:mykey event del
S2: received on __keyspace@0__:mykey event del
S2: received on __keyspace@0__:anotherkey event set
S2: received on __keyspace@0__:anotherkey event del

You can see that first subscriber received only events for mykey, while second subscriber receives events for all keys.

🌐
w3tutorials
w3tutorials.net › blog › redis-keyspace-notifications-nodejs
Redis Keyspace Notifications with Node.js — w3tutorials.net
For example, when a key is deleted, a message is sent to the channel __keyspace@<db>__:<key>. Keyevent Notifications: These are sent when a specific type of event occurs across all keys.
🌐
npm
npmjs.com › package › redular
redular - npm
May 25, 2015 - config set notify-keyspace-events Ex · Alternatively you can set autoConfig to true in the Redular options to attempt to automatically configure Redis.
      » npm install redular
    
Published   May 25, 2015
Version   1.2.0
Author   Patt-tom McDonnell
Find elsewhere
🌐
Redis
redis.io › docs › latest › operate › oss_and_stack › stack-with-enterprise › deprecated-features › triggers-and-functions › concepts › triggers › keyspace_triggers
Keyspace triggers | Docs
February 26, 2026 - {"categories":["docs","develop","stack","oss","rs","rc","oss","kubernetes","clients"],"description":"Execute a JavaScript function based on a keyspace notification","duplicateOf":"head:data-ai-metadata","location":"body","title":"Keyspace triggers","tableOfContents":{"sections":[{"id":"trigger-guarantees","title":"Trigger guarantees"},{"id":"upgrades","title":"Upgrades"},{"id":"advanced-usage","title":"Advanced usage"}]},"codeExamples":[]}
🌐
GitHub
github.com › toygame › nodejs-redis-keyspace-notifications
GitHub - toygame/nodejs-redis-keyspace-notifications
April 13, 2014 - $ git clone https://github.com/toygame/nodejs-redis-keyspace-notifications.git $ cd nodejs-redis-keyspace-notifications $ npm install
Author   toygame
🌐
npm
npmjs.com › package › redis-notifier
redis-notifier - npm
December 14, 2015 - Using NPM + Package.json, simply just run npm install · If you are using node_redis pre v0.11.0 checkout the tag v0.1.2 · Start Redis Server : redis-server CONF --notify-keyspace-events KExe
      » npm install redis-notifier
    
Published   Dec 14, 2015
Version   1.0.0
Author   Chris Miller
🌐
GitHub
github.com › redis-developer › keyspace-notifications-node-redis › blob › main › README.md
keyspace-notifications-node-redis/README.md at main · redis-developer/keyspace-notifications-node-redis
This is a small project using Redis and Redis Keyspace Notifications. Keyspace notifications allow clients to subscribe to Pub/Sub channels in order to receive events affecting the Redis data set in some way.
Author   redis-developer
🌐
Fgribreau
redis-knowledge.fgribreau.com › resource › 08f84e1668ccc79732e30039f3b3b6b4 › redular-node-js-event-scheduling-system-powered-by-redis-keyspace-notifications
redular - Node.js event scheduling system powered by Redis keyspace notifications - Redis Knowledge Base
There are a few caveats with this: the data is stored in Redis as a JSON string so you cannot send functions to handlers. Data is passed through a JSON.stringify() before being saved to Redis, bear this in mind.
🌐
DEV Community
dev.to › katpadi › til-redis-keyspace-notifications-3eca
TIL: Redis Keyspace Notifications - DEV Community
March 19, 2018 - The said notifications are enabled using the notify-keyspace-events of redis.conf or via the CONFIG SET.
🌐
DEV Community
dev.to › bensooraj › ossa-a-node-js-server-side-module-powered-by-redis-for-sending-scheduled-messages-1dhp
Ossa: A node.js server-side module (powered by Redis) for sending scheduled messages - DEV Community
May 12, 2020 - const Ossa = require('ossa'); const ossa = new Ossa({ namespace: "ossa", // Default redis: { host: 'localhost', // Default port: 6379 // Default }, debug: false, // Default mode: 0 // 0 => Send and receive (Default) | 1 => Send only }); ... try { const notificationID = await ossa.sendNotification({ in: '10s', // on: moment().utc().add(30, 'seconds'), // on: '2020-05-02 03:23:00', // on: '2020-05-01T21:59:16Z', message: JSON.stringify({ name: "Ben", age: 1000, }) }); console.log("notificationID: ", notificationID) } catch (error) { throw new Error(error); } // Output: // notificationID: ossa::f1799e87-6740-4394-bf5e-d6e55eae3914