Key Management
Key expiration
- Redis allows you to set a time-to-live (TTL) on keys.
- After the TTL expires, the key is automatically deleted from Redis.
- This is useful for:
- Caching temporary data
- Session management
- Limiting memory usage
The main commands are:
EXPIRE→ Set TTL on a keyTTL→ Check remaining time to livePERSIST→ Remove TTL (make key permanent)
EXPIRE
- Sets a time-to-live in seconds on a key.
- Alternative:
PEXPIRE→ TTL in milliseconds.
TTL
- Returns the remaining time-to-live in seconds.
- Returns:
- Positive integer → seconds remaining
-1→ key exists but has no TTL (persistent)-2→ key does not exist
PERSIST
Removes the TTL from a key, making it permanent.
SET temp:key "value"
EXPIRE temp:key 30
TTL temp:key
# Output: 30
PERSIST temp:key
TTL temp:key
# Output: -1
The key will no longer expire.
Pattern matching
-
Pattern matching allows you to find keys based on a pattern (like wildcards).
-
Useful for operations like:
- Cleaning up keys
- Querying specific sets of keys
- Debugging or monitoring
-
Redis provides two main commands:
KEYS→ returns all keys matching a patternSCAN→ iteratively returns keys matching a pattern (safe for production)
KEYS
Pattern supports wildcards:
-
*→ matches any number of characters -
?→ matches exactly one character -
[abc]→ matches one character in the set -
[a-z]→ matches one character in rangeSET user:1 "Masum"
SET user:2 "Billah"
SET session:101 "active"
KEYS user:*
# Output:
# 1) "user:1"
# 2) "user:2"
KEYS session:?
# Output:
# 1) "session:1" -
KEYSscans the entire keyspace. -
Not recommended in production if you have millions of keys → can block Redis.
SCAN
Iterative key scanning command.
SCAN cursor [MATCH pattern] [COUNT count]
cursor→ iteration position (start with 0)MATCH pattern→ optional, only return keys matching patternCOUNT count→ optional, hints how many keys to return per call
Key Differences: KEYS vs SCAN
| Feature | KEYS | SCAN |
|---|---|---|
| Blocking? | Yes (blocks Redis) | No (non-blocking) |
| Pattern | Yes | Yes |
| Use Case | Small keyspaces, debugging | Production, large keyspaces |
| Return Type | All matching keys | Partial keys + cursor |
For production environments, always use SCAN instead of KEYS to avoid performance issues while performing pattern matching or key management tasks.
Key naming conventions
1. Use Namespaces with Colons
-
Use : to create logical namespaces.
-
Format:
namespace:entity:iduser:101:name → "Masum"
user:101:email → "masum@example.com"
session:2021-09-01 → "active"
cache:homepage → "<html>...</html>" -
Groups related keys together
-
Simplifies pattern matching:
2. Be Descriptive but Concise
-
Include meaningful information in the key.
-
Avoid cryptic abbreviations unless widely understood.
# Good
cart:user:101:item:202 → quantity of item 202 in user 101's cart
# Bad
c:u101:i202 → hard to read
3. Avoid Using Spaces
- Redis keys cannot contain spaces reliably.
- Use
:or_instead.
4. Keep Key Length Reasonable
Redis stores keys in memory → longer keys = more memory used. Recommended: < 64 bytes if possible.
5. Use Consistent Case
-
Use lowercase consistently to avoid confusion.
-
Mixed-case keys can lead to mistakes:
# Consistent
user:101:profile
# Inconsistent (bad)
user:101:Profile
6. Use Suffixes for Type Clarity
Include type in key name when useful:
user:101:hash → hash type
user:101:list → list type
user:101:set → set type
Helps during debugging or migrations.
7. Use Versioning If Needed
For cached data or keys that may evolve:
cache:v1:homepage
cache:v2:homepage
Allows safe updates without overwriting existing data.
8. Avoid Special Characters
- Stick to letters, numbers, colons, underscores.
- Avoid *
? [] { }unless used intentionally for SCAN/KEYS patterns.
Example of Well-Structured Keyspace
# User data
user:101:name → "Masum"
user:101:email → "masum@example.com"
user:101:cart → list of item IDs
# Sessions
session:101 → "active"
session:102 → "expired"
# Cache
cache:v1:homepage → HTML content
cache:v1:products → JSON list of products
# Counters
counter:logins:2025-09-04 → 120
counter:signups:2025-09-04 → 15
Deleting data
- Redis allows you to delete one or more keys when they are no longer needed.
- Two main commands:
DEL→ Synchronous delete (blocking)UNLINK→ Asynchronous delete (non-blocking)
- Choosing the right command is important for performance, especially in production with large datasets.
DEL
-
Deletes one or more keys immediately.
-
Returns the number of keys actually deleted.
DEL key [key ...] -
Synchronous: Redis frees memory immediately.
-
Blocking: For large keys (like big hashes or lists), deletion can block other clients temporarily.
UNLINK
UNLINK key [key ...]
- Deletes keys asynchronously:
- Redis removes references immediately.
- Actual memory freeing happens in background threads.
Key Differences: DEL vs UNLINK
| Feature | DEL | UNLINK |
|---|---|---|
| Operation | Synchronous | Asynchronous |
| Blocking? | Yes | No |
| Use Case | Small keys, scripts | Large keys, production |
| Memory freeing | Immediate | Background thread |
Summary
| Command | Operation Type | Blocking | Use Case |
|---|---|---|---|
| DEL | Synchronous delete | Yes | Small keys, scripts |
| UNLINK | Asynchronous delete | No | Large keys, production, non-blocking |
| SCAN + UNLINK | Iterative pattern deletion | No | Safe bulk deletion of multiple keys |