Configuring Redis Keyspace Notifications: Catch Key Expirations (TTL Expire) and Real-Time Data Changes

Database tutorial - IT technology blog
Database tutorial - IT technology blog

Quick start: Enable and test in 5 minutes

It’s 2 AM, and your PagerDuty alarm is blaring nonstop. The flash sale system is completely deadlocked because thousands of orders past their 15-minute window failed to auto-cancel. In the background, a cron job repeatedly scanning the orders table is locking tables and driving database CPU to 100%. The instant firefighting fix: offload TTL monitoring to Redis using Keyspace Notifications.

By default, Redis disables this feature to conserve CPU cycles. You can safely enable it on the fly on a live server without restarting the service.

Step 1: Enable the feature via redis-cli

Open a terminal, connect to your Redis instance, and activate events for expired keys:

# Connect to Redis
redis-cli

# Check the current configuration (defaults to an empty string "")
127.0.0.1:6379> CONFIG GET notify-keyspace-events
1) "notify-keyspace-events"
2) ""

# Enable key expiration notifications (Ex = Keyevent events + expired events)
127.0.0.1:6379> CONFIG SET notify-keyspace-events Ex
OK

Step 2: Test listening for events via terminal

Open two side-by-side terminal windows to verify the response.

Terminal 1 (Listen for expired events on DB 0):

redis-cli --csv PSUBSCRIBE '__keyevent@0__:expired'

Terminal 2 (Create a test key with a 5-second TTL):

redis-cli SET order:pending:100293 "processing" EX 5

Exactly 5 seconds later, Terminal 1 immediately receives the message:

"pmessage","__keyevent@0__:expired","__keyevent@0__:expired","order:pending:100293"

Step 3: Write a Python worker to handle events

The script below demonstrates a background worker capturing expired keys to restore inventory or cancel orders:

import redis

r = redis.Redis(host='localhost', port=6379, db=0, decode_responses=True)
pubsub = r.pubsub()

# Listen to the expired channel on DB 0
pubsub.psubscribe('__keyevent@0__:expired')

print("Worker is waiting for expired keys...")
for message in pubsub.listen():
    if message['type'] == 'pmessage':
        expired_key = message['data']
        print(f"[ALERT] Key just expired: {expired_key}")
        
        # Handle inventory rollback logic
        if expired_key.startswith("order:pending:"):
            order_id = expired_key.split(":")[-1]
            print(f"=> Rolling back order: {order_id}")

How Keyspace Notifications Work Under the Hood

This mechanism operates on Redis’s internal Pub/Sub architecture. Whenever data changes or a key reaches its TTL, Redis automatically publishes a message to the corresponding channel.

1. Keyspace Channels vs. Keyevent Channels

Redis separates notifications into two distinct perspectives:

  • Keyspace channel (K) – Key-centric monitoring: Use this when you want to track what actions occurred on a specific key like user:1 (set, del, expire…). Channel format: __keyspace@<db>__:<key>. The received payload is the command name that was executed (e.g., set, del).
  • Keyevent channel (E) – Event-centric monitoring: Use this when you want to know which keys were affected when a specific event like expired occurred. Channel format: __keyevent@<db>__:<event>. The received payload is the key name itself (e.g., order:pending:100293).

Production environments almost always use Keyevent. The reason is simple: workers usually only need the key name to run cleanup logic.

2. Configuration flags for notify-keyspace-events

You can combine characters depending on your monitoring requirements:

  • K: Keyspace events (channel format __keyspace@<db>__).
  • E: Keyevent events (channel format __keyevent@<db>__).
  • g: Generic commands not type-specific (DEL, EXPIRE, RENAME…).
  • $: String commands.
  • l: List commands.
  • s: Set commands.
  • h: Hash commands.
  • z: Sorted Set commands.
  • x: Expired events.
  • e: Evicted events (keys evicted due to maxmemory policies).
  • A: Alias for g$lshzxe (all events, excluding K and E).

For example, KEA enables all notifications across both channels, whereas Ex strictly publishes key expiration events via Keyevent channels.

Advanced: The Shadow Key Pattern and High-Load Challenges

When implementing this in real-world projects, you will immediately run into a major pitfall: How do you read the data of an expired key?

Data loss upon key expiration

The moment Redis publishes the expired event, the key has already been wiped from RAM. The message returned via Pub/Sub contains nothing more than the key name string. If you stored the entire order payload in that key, your data is completely gone.

Solution: Implement the Shadow Key Pattern

To retain metadata, the standard design pattern is to split the workload across two separate keys:

  1. Data key (Stores actual payload): order:data:100293 — set with no TTL or a generous TTL (e.g., 24 to 48 hours to prevent memory leaks).
  2. Shadow key (Trigger countdown): order:ttl:100293 — stores only an empty string or timestamp, configured with the exact 15-minute TTL.
# 1. Store order details
SET order:data:100293 '{"user_id": 456, "amount": 250000, "status": "pending"}' EX 86400

# 2. Create a 15-minute (900 seconds) shadow countdown key
SET order:ttl:100293 "" EX 900

When order:ttl:100293 expires, the worker extracts order_id = 100293. Next, the worker fetches the full payload from order:data:100293 to complete the rollback. Once finished, the worker proactively invokes DEL order:data:100293 to free up RAM.

Beware of performance collapse from overusing KEA

Enabling the KEA flag blindly is a classic mistake. On a Redis cluster handling 50,000 QPS, every single write operation instantly doubles into publish streams sent to thousands of connected subscribers. As a result, CPU usage can spike from 20% to 90% in minutes, accompanied by local network interface saturation from a flood of Pub/Sub packets.

Golden rule: Only enable what you actually need. If you only care about expirations, stick to Ex. Never enable KEA in production.

Crucial Lessons for Production Deployments

  • Expiration events are not strictly real-time: Redis does not maintain an individual timer per key. It removes expired keys in two ways: passively (when a client queries an expired key) and actively (randomly sampling 20 keys every 100ms in the background). If a key remains unaccessed and memory pressure is low, the notification can be delayed from a few hundred milliseconds to several seconds. Never rely on this mechanism for financial transactions that demand sub-millisecond precision.
  • Pub/Sub is At-Most-Once (fire-and-forget): Redis Pub/Sub has no message buffer and does not store historical messages. If a worker drops network connectivity or restarts for even 3 seconds, all expiration events fired during that window are permanently lost. Need 100% reliability? Use a Redis Sorted Set (ZSET with score as epoch timestamp) combined with a polling worker, or migrate to Redis Streams or RabbitMQ.
  • Persist configurations in redis.conf: The CONFIG SET command only applies to runtime RAM. Upon restarting the server, Redis reloads its configuration file and wipes out your runtime settings. Persist it directly in /etc/redis/redis.conf:
# Add to redis.conf to persist configuration across reboots
notify-keyspace-events "Ex"
Share: