# Keyspace Notifications — Redis Pub/Sub & Streams

Source: https://www.skillbyai.com/en/redis-streams/a-keyspace

> Subscribe to key changes and expirations, and know their limits.

## Events about your keys

Redis can publish Pub/Sub events when keys change, called **keyspace notifications**. They are **disabled by default** because they cost CPU; enable them with the `notify-keyspace-events` setting, choosing classes of events: for example `E` (keyevent channels) plus `x` (expired events) gives `Ex`. Events are published on two channel families: **keyspace** channels (`__keyspace@0__:mykey`, message is the event name such as `set` or `del`) and **keyevent** channels (`__keyevent@0__:expired`, message is the key name). A common use is reacting to **expirations**, such as ending a reservation hold. Two important caveats: they are ordinary Pub/Sub, so they are **lost** if no client is connected; and an expired event is generated when Redis **actually deletes** the key, either when it is accessed or when the background expiry cycle finds it, which can be some time after the TTL ran out. In a cluster, each node emits events only for its own keys, so subscribers must listen on every node.

## Reacting to expired keys

Enable expiration events, then subscribe to the keyevent channel.

```bash
redis-cli CONFIG SET notify-keyspace-events Ex

# subscriber: receives the names of keys as they expire in database 0
redis-cli PSUBSCRIBE '__keyevent@0__:expired'

# elsewhere: a 10-minute seat hold
redis-cli SET hold:seat:12A user:42 EX 600
# about 10 minutes later the subscriber receives "hold:seat:12A"
# (possibly a little later, when Redis actually evicts the expired key)
```

## Do not build critical timers on expiry events

Because expiry events can be delayed or lost, use them as a hint, not the source of truth. For reliable delayed jobs, store due times in a sorted set or database and poll, or use a scheduler.

**Quiz:** Why might an expired-key notification arrive later than the key's TTL?

- [ ] Redis batches notifications hourly
- [ ] Notifications are stored on disk first
- [ ] Expired keys are never notified
- [x] The event fires when Redis actually removes the key, which can happen after the TTL elapses

*Answer:* The event fires when Redis actually removes the key, which can happen after the TTL elapses. Expiry is lazy or periodic, so the notification is emitted when deletion happens.
