Redis Key Management
Keys are the fundamental unit of data in Redis. This lesson covers key management operations.
Basic Key Operations
Setting Keys
REDIS
# Set a string
SET user:1 "Alice"
# Set a hash
HSET user:2 name "Bob" age 30
# Set a list
LPUSH articles "article1" "article2"
# Set a set
SADD tags:article1 "redis" "database"
# Set a sorted set
ZADD leaderboard 100 "player1"
Getting Keys
REDIS
# Get a string
GET user:1
# Get a hash
HGETALL user:2
# Get a list
LRANGE articles 0 -1
# Get a set
SMEMBERS tags:article1
# Get a sorted set
ZRANGE leaderboard 0 -1 WITHSCORES
Deleting Keys
REDIS
# Delete a single key
DEL user:1
(integer) 1 # Returns the number of deleted keys
# Delete multiple keys
DEL user:2 user:3
(integer) 2
# Delete a non-existent key
DEL notexist
(integer) 0
Checking if a Key Exists
REDIS
SET mykey "hello"
EXISTS mykey
(integer) 1 # Exists
EXISTS notexist
(integer) 0 # Does not exist
# Check multiple keys (returns count of existing keys)
EXISTS mykey mykey2 mykey3
(integer) 1 # Only mykey exists
Checking Key Type
REDIS
SET mystring "hello"
TYPE mystring # string
HSET myhash field "value"
TYPE myhash # hash
LPUSH mylist "a"
TYPE mylist # list
SADD myset "a"
TYPE myset # set
ZADD myzset 1 "a"
TYPE myzset # zset
TYPE notexist # none
Key Naming Conventions
Good key naming makes data management clearer.
Recommended Format
business:object:ID[:property]
Examples
REDIS
# User info
user:1 # User 1 basic info
user:1:profile # User 1 detailed profile
user:1:settings # User 1 settings
# Articles
article:123 # Article 123 content
article:123:comments # Article 123 comment list
article:123:views # Article 123 view count
# Shopping cart
cart:user:1 # User 1's shopping cart
# Sessions
session:token:abc123 # Session token
# Cache
cache:api:user:1 # API cache for user 1 info
cache:page:home # Page cache for home page
# Locks
lock:order:123 # Lock for order 123
Naming Suggestions
| Suggestion | Example | Description |
|---|---|---|
| Use colons as separators | user:1:profile |
Clear hierarchy |
| Use meaningful prefixes | cache:, session:, lock: |
Distinguish different purposes |
| Stay consistent | user:1, user:2 |
Unified format |
| Avoid being too long | u:1:p |
Too short is unclear, too long uses memory |
| Avoid special characters | user-1 |
Use hyphens or colons, avoid spaces |
💡 Key length: Key names take up memory. Balance clarity with conciseness. Frequently used keys can be shorter.
Expiration
Redis can set a TTL (time-to-live) for keys, automatically deleting them when they expire.
Setting Expiration
REDIS
SET session:token123 "user_data"
# Method 1: EXPIRE (seconds)
EXPIRE session:token123 3600 # Expires after 1 hour
# Method 2: EXPIREAT (timestamp, seconds)
EXPIREAT session:token123 1700000000
# Method 3: PEXPIRE (milliseconds)
PEXPIRE session:token123 3600000
# Method 4: PEXPIREAT (timestamp, milliseconds)
PEXPIREAT session:token123 1700000000000
# Method 5: Set expiration with SET
SET cache:key "value" EX 60 # Expires after 60 seconds
SET cache:key "value" PX 60000 # Expires after 60000 milliseconds
Checking Expiration
REDIS
# TTL: returns remaining time (seconds)
TTL session:token123
(integer) 3500 # 3500 seconds remaining
# PTTL: returns remaining time (milliseconds)
PTTL session:token123
(integer) 3500000
# Special return values
TTL noexpire
(integer) -1 # Key exists but has no expiration
TTL notexist
(integer) -2 # Key does not exist
Removing Expiration
REDIS
# PERSIST: remove expiration, making the key persistent
PERSIST session:token123
(integer) 1 # Successfully removed
PERSIST notexist
(integer) 0 # Key does not exist
Expiration Use Cases
| Scenario | TTL | Example |
|---|---|---|
| Session | 30 minutes | SET session:token "data" EX 1800 |
| Verification code | 5 minutes | SET code:phone:138xxxx "123456" EX 300 |
| Cache | 1 hour | SET cache:api:user:1 "data" EX 3600 |
| Rate limiting | 1 minute | SET limit:user:1 "10" EX 60 |
| Distributed lock | 10 seconds | SET lock:resource "locked" NX EX 10 |
⚠️ Note: Expiration precision is in milliseconds, but actual deletion may be delayed (lazy deletion + periodic deletion).
Key Renaming
RENAME: Rename a Key
REDIS
SET oldkey "value"
RENAME oldkey newkey
OK
GET newkey
"value"
GET oldkey
(nil) # oldkey no longer exists
⚠️ Note: If newkey already exists, RENAME will overwrite it!
RENAMENX: Rename Only if New Key Doesn't Exist
REDIS
SET key1 "value1"
SET key2 "value2"
RENAMENX key1 key2
(integer) 0 # key2 already exists, rename failed
GET key1
"value1" # key1 still exists
GET key2
"value2" # key2 was not overwritten
Key Migration
MOVE: Move a Key to Another Database
REDIS
# In DB 0
SET mykey "value"
# Move to DB 1
MOVE mykey 1
(integer) 1 # Success
# Switch to DB 1
SELECT 1
OK
GET mykey
"value"
⚠️ Note: MOVE is not available in cluster mode.
DUMP + RESTORE: Serialization and Deserialization
REDIS
# Serialize a key
SET mykey "hello"
DUMP mykey
# Returns serialized binary data
# Restore to a new key
RESTORE newkey 0 "\x00\x05hello\t\x00\xf5\xbd\xba\xab\xdc\xa6\xdec"
OK
MIGRATE: Migrate a Key to Another Redis Instance
REDIS
# Migrate mykey to 192.168.1.100:6379
MIGRATE 192.168.1.100 6379 mykey 0 5000
OK
# Parameter explanation
# MIGRATE host port key destination-db timeout
Key Sorting
The SORT command can sort lists, sets, and sorted sets.
Basic Sorting
REDIS
# Sort a list
LPUSH mylist 3 1 4 1 5 9 2 6
SORT mylist
# 1) "1"
# 2) "1"
# 3) "2"
# 4) "3"
# 5) "4"
# 6) "5"
# 7) "6"
# 8) "9"
# Descending sort
SORT mylist DESC
# 1) "9"
# 2) "6"
# 3) "5"
# ...
# Sort a set
SADD myset 5 2 8 1 9
SORT myset
# 1) "1"
# 2) "2"
# 3) "5"
# 4) "8"
# 5) "9"
Sorting by External Values
REDIS
# Student ID list
LPUSH students "student1" "student2" "student3"
# Student scores
SET student1:score 85
SET student2:score 92
SET student3:score 78
# Sort by score
SORT students BY *:score
# 1) "student3" # 78 points
# 2) "student1" # 85 points
# 3) "student2" # 92 points
# Get external values
SORT students BY *:score GET *:score
# 1) "78"
# 2) "85"
# 3) "92"
Saving Sort Results
REDIS
# Sort and save to a new key
SORT mylist DESC STORE sorted_list
(integer) 8
LRANGE sorted_list 0 -1
# 1) "9"
# 2) "6"
# ...
Finding Keys
KEYS: Find Matching Keys
REDIS
# Set some test data
SET user:1 "Alice"
SET user:2 "Bob"
SET user:3 "Charlie"
SET product:1 "iPhone"
SET product:2 "iPad"
# Find all keys
KEYS *
# 1) "user:1"
# 2) "user:2"
# 3) "user:3"
# 4) "product:1"
# 5) "product:2"
# Find keys matching a pattern
KEYS user:*
# 1) "user:1"
# 2) "user:2"
# 3) "user:3"
KEYS *:1
# 1) "user:1"
# 2) "product:1"
KEYS user:[1-2]
# 1) "user:1"
# 2) "user:2"
⚠️ Warning: KEYS scans the entire database. It is very slow with large datasets — do not use in production!
SCAN: Iterate Through Keys (Recommended)
SCAN is a safe alternative to KEYS, using cursor-based iteration.
REDIS
# Start iteration, returns cursor and key list
SCAN 0
1) "5" # Cursor for the next iteration
2) 1) "user:1"
2) "user:2"
# Continue iteration
SCAN 5
1) "0" # Cursor of 0 means iteration is complete
2) 1) "user:3"
2) "product:1"
# Match pattern
SCAN 0 MATCH user:*
1) "3"
2) 1) "user:1"
2) "user:2"
# Specify count per iteration
SCAN 0 COUNT 100
SCAN Family Commands
REDIS
# Iterate set elements
SSCAN myset 0
# Iterate hash fields
HSCAN myhash 0
# Iterate sorted set elements
ZSCAN myzset 0
💡 SCAN advantage: Does not block the server; can process large numbers of keys in batches.
Keyspace Notifications
Redis can notify clients about key change events.
Configuring Keyspace Notifications
REDIS
# View configuration
CONFIG GET notify-keyspace-events
1) "notify-keyspace-events"
2) "" # Disabled by default
# Enable all notifications
CONFIG SET notify-keyspace-events AKE
OK
Notification Types
| Character | Notification Type | Description |
|---|---|---|
| K | Keyspace | Keyspace notification (keyspace@ |
| E | Keyevent | Key event notification (keyevent@ |
| A | All | All notifications (equivalent to KE$glsh) |
| $ | String | String commands |
| l | List | List commands |
| s | Set | Set commands |
| h | Hash | Hash commands |
| z | Sorted Set | Sorted set commands |
| x | Expired | Expiration events |
| e | Evicted | Eviction events (memory eviction) |
Subscribing to Notifications
REDIS
# Subscribe to keyspace notifications (all events for a key)
SUBSCRIBE __keyspace@0__:mykey
# Subscribe to keyevent notifications (a specific event for all keys)
SUBSCRIBE __keyevent@0__:set
Example: Monitoring Expired Keys
REDIS
# Configure: enable expiration notifications
CONFIG SET notify-keyspace-events Ex
OK
# Client 1: subscribe to expired events
SUBSCRIBE __keyevent@0__:expired
# Client 2: set a key with expiration
SET temp "value" EX 5
# Client 1 receives:
# 1) "message"
# 2) "__keyevent@0__:expired"
# 3) "temp" # The expired key name
Key Information
OBJECT Command
REDIS
SET mykey "hello"
# View key's internal encoding
OBJECT ENCODING mykey
"embstr"
# View reference count
OBJECT REFCOUNT mykey
(integer) 1
# View idle time (seconds)
OBJECT IDLETIME mykey
(integer) 10
MEMORY Command (Redis 4.0+)
REDIS
SET mykey "hello world hello world hello world"
# View key's memory usage
MEMORY USAGE mykey
(integer) 56 # Bytes
# View memory allocation details
MEMORY STATS
STRLEN: Get String Length
REDIS
SET mykey "Hello Redis"
STRLEN mykey
(integer) 11
Batch Operations
Batch Setting
REDIS
MSET key1 "value1" key2 "value2" key3 "value3"
OK
Batch Getting
REDIS
MGET key1 key2 key3
1) "value1"
2) "value2"
3) "value3"
# Including non-existent keys
MGET key1 key2 notexist key3
1) "value1"
2) "value2"
3) (nil)
4) "value3"
Batch Deletion
REDIS
# Delete multiple keys
DEL key1 key2 key3
(integer) 3
❓ FAQ
Q Why is the KEYS command slow?
A KEYS scans the entire database with O(N) time complexity. It blocks Redis when the dataset is large. Use SCAN instead.
Q When are expired keys deleted?
A Redis uses lazy deletion + periodic deletion. It checks expiration when a key is accessed, and periodically checks a random sample of keys in the background.
Q How do I batch delete keys matching a pattern?
A
BASH
redis-cli --scan --pattern "prefix:*" | xargs redis-cli DEL
Q: What's the maximum key name length? A: Theoretically unlimited, but keeping them short is recommended (they take up memory).
Q How do I count keys of a specific type?
A There is no direct command. You need to iterate with SCAN and check with TYPE.
📖 Summary
- Basic key operations: SET, GET, DEL, EXISTS, TYPE
- Key naming: use colons as separators with meaningful prefixes
- Expiration: EXPIRE, TTL, PERSIST
- Key finding: KEYS (use with caution), SCAN (recommended)
- Key migration: MOVE, MIGRATE, DUMP/RESTORE
- Key sorting: SORT command
- Keyspace notifications: listen to key change events
📝 Exercises
- Naming practice: Design key naming conventions for an e-commerce site (users, products, orders, shopping carts)
- Expiration practice: Set a key with a TTL, check remaining time with TTL, and verify after expiration
- SCAN practice: Create 100 keys and use SCAN to iterate through them all
- Batch operations: Use MSET to set 10 keys and MGET to retrieve them
Next Lesson
In the next lesson, we will learn Redis Strings (Part 1), diving deeper into basic string operations.



