Redis Key Management and Expiration
🎯 Introduction
By the end of this article, you will be able to design distinct keys for different queries, inspect their remaining lifetime, and safely scan and delete practice data.
🧱 Key Naming and Common Commands
Key names should identify the application and the data's purpose so modules do not overwrite each other's data by using the same key.
Use cases: prefixes help modules sharing Redis avoid collisions. For example, course:dev:user:v1:42 identifies the project, environment, data category, format version, and user ID. Colons are a naming convention; they do not create directories.
If a record has different language versions, include the language in its key. Private data also needs to distinguish authenticated user identities. v1 identifies the data structure version; it does not change automatically when the database changes.
This article uses Node.js 22.9.0, redis 5.9.0, and Redis 7.4.2, reusing redis.mjs from the introduction. Add the following blocks to keys.mjs in order:
import { redis } from './redis.mjs';
await redis.connect();
const key = 'course:keys:user:42';
await redis.set(key, 'Lin');
This exercise operates only on the course:keys:* prefix, making the cleanup scope easy to verify.
🛠 Check, Delete, and Scan Keys
Existence checks tell you whether a key is still present. Type checks help you choose the right commands, scanning locates matching keys, and deletion makes the specified data immediately unavailable.
These operations are useful for troubleshooting data, cleaning practice keys, and invalidating old cache entries. First, check whether the key exists and what type it uses:
console.log(await redis.exists(key));
console.log(await redis.type(key));
The outputs are 1 and string. For a missing key, they are 0 and none.
Scan in batches to inspect a group of keys:
for await (const keys of redis.scanIterator({ MATCH: 'course:keys:*', COUNT: 100 })) {
console.log(keys);
}
In redis 5.9.0, each iteration returns a batch of key names. MATCH filters by prefix; COUNT hints at the amount of scan work, rather than guaranteeing exactly 100 keys per batch. A scan is not a consistent snapshot: keys that change during the scan may appear more than once or not at all. Do not treat it as exact pagination.
Delete the known key and check again:
console.log(await redis.del(key));
console.log(await redis.exists(key));
The outputs are 1 and 0. del returns the number deleted; deleting the same key again returns 0. Avoid KEYS *, which scans all keys in one operation, on large production databases. For large values, UNLINK moves most memory reclamation work to the background.
🧰 EXPIRE, TTL, and SET EX
Expiration defines how long a key remains valid; reads treat it as missing after that deadline. EXPIRE sets a lifetime in seconds on an existing key, TTL reports the remaining seconds, and the EX option on SET sets the lifetime as part of the write.
Use cases: temporary verification codes, short-lived sessions, and cached copies need bounded lifetimes. Set a 60-second lifetime, writing the value and its expiration in one command:
await redis.set(key, 'Lin', { EX: 60 });
console.log(await redis.ttl(key));
The output is an integer close to 60. Use PX instead of EX for milliseconds.
| TTL result | Meaning |
|---|---|
| Nonnegative integer | Remaining seconds; may be 0 just before expiration |
-1 | The key exists with no expiration |
-2 | The key does not exist |
Adjust an existing key's lifetime:
console.log(await redis.expire(key, 120));
console.log(await redis.ttl(key));
The outputs are 1 and a number close to 120. expire returns 0 for a missing key. Normal reads do not renew the lifetime. A regular set overwrite clears the old expiration, so explicitly pass EX when updating cached data.
⚙️ Expiration: Passive and Active Deletion
Redis checks expiration when a key is accessed and treats expired keys as missing. This is passive expiration. It also periodically samples keys with expiration times and removes expired data. This is active expiration.
Expired data can no longer be read normally, but memory usage may not drop at that exact moment. When investigating memory, distinguish between a key becoming invalid and its memory being reclaimed.
See the EXPIRE documentation for the detailed behavior.
Verify reads after expiration:
await redis.set(key, 'temporary', { PX: 200 });
await new Promise(resolve => setTimeout(resolve, 300));
console.log(await redis.get(key));
console.log(await redis.ttl(key));
The outputs are null and -2, confirming that normal reads treat the expired key as missing.
Finally, close the connection and run the script:
await redis.close();
node keys.mjs
❓ Questions and Answers
Q1: Does a 60-second lifetime guarantee the key stays for all 60 seconds?
No. The application may delete it, or memory eviction may remove it earlier.
Q2: Does deleting a Redis key also delete the MySQL record?
No. They are separate systems. Cache expiration and deletion do not automatically modify the authoritative record.
Q3: Can scan results provide an exact real-time count?
There is no guarantee. Data can change during the scan, and duplicate keys may be returned. Maintain separate counting logic when the application requires an exact count.
🧪 Exercise
Design separate keys for the Chinese and English versions of a user profile. Set different lifetimes and verify that the values do not overwrite each other.
// Write your code here
🎉 You now know how to name keys, inspect them, and manage their lifecycles!
