Redis is best known as a fast, in-memory key-value data store that supports various data types and advanced features like automatic expiration and persistence. At the heart of Redis lies the concept of storing and manipulating data using keys and values.
This article will explore:
- Key-Value Operations in Redis
- Expiration: Automatic Key Management
- Persistence: Saving Data to Disk
Redis keys can be associated with different types of values, such as strings, hashes, lists, sets, or sorted sets. The key is always a binary-safe string, and it acts as the identifier for accessing or modifying the associated value.
- Keys are case-sensitive and can be up to 512 MB.
- Values can be of various data types.
- Every operation is atomic.
- You can overwrite an existing key by using
SET
again.
Command | Description |
---|---|
SET key value |
Store a key with a string value |
GET key |
Retrieve the value of a key |
DEL key |
Delete a key |
EXISTS key |
Check if a key exists |
TYPE key |
Get the type of value stored |
RENAME oldkey newkey |
Rename a key |
KEYS pattern |
Find keys matching a pattern |
FLUSHALL / FLUSHDB |
Delete all keys (global or current DB) |
SET user:1001 "Jenil"
GET user:1001 # "Jenil"
EXISTS user:1001 # 1 (true)
DEL user:1001
EXISTS user:1001 # 0 (false)
Pattern | Matches |
---|---|
* |
Any number of characters |
? |
Exactly one character |
[abc] |
a, b, or c |
user:* |
All keys starting with user: |
KEYS user:* # Returns all user-related keys
KEYS
in production on large datasets — use SCAN
for safer iteration.
Redis allows you to set expiration times on keys, meaning they will be automatically deleted after a certain duration.
This is especially useful for:
- Session storage
- Temporary caches
- One-time passwords (OTP)
- API rate limiting
Method | Description |
---|---|
EXPIRE key seconds |
Set a timeout in seconds |
PEXPIRE key milliseconds |
Set timeout in ms |
TTL key |
Get time-to-live in seconds |
PTTL key |
Time-to-live in ms |
SET key value EX seconds |
Set + expiration in one |
SET key value PX milliseconds |
Set + ms expiration |
SET otp:123456 "793421" EX 300 # OTP expires in 5 min
TTL otp:123456 # Returns time left
EXPIRE session:krishna 1800 # 30 min session
-
Use
PERSIST key
to remove a key's expiration:PERSIST otp:123456
-
You can reset TTL by using
EXPIRE
again or re-setting the key.
- Redis does not immediately delete expired keys.
- It uses lazy deletion (access time check) and periodic scanning (10 keys at a time in a loop).
- This strategy avoids performance spikes but keeps memory under control.
Even though Redis is an in-memory store, it provides multiple options for persistence, so your data can survive server restarts or crashes.
Redis supports two primary forms of persistence:
Creates point-in-time snapshots of your data at specified intervals.
In redis.conf
, you can define:
save 900 1 # 1 change in 15 minutes
save 300 10 # 10 changes in 5 minutes
save 60 10000 # 10,000 changes in 1 minute
- Stored in binary format:
dump.rdb
- Lightweight, but may lose recent changes on crash.
SAVE # Blocking save
BGSAVE # Non-blocking, recommended
Logs every write operation to a file (appendonly.aof
) in sequential order.
- More durable than RDB (can recover every command).
- Slower than RDB due to logging every write.
- You can configure how often it syncs data to disk:
appendfsync always # Every command (slowest but safest) appendfsync everysec # Once per second (balanced) appendfsync no # OS decides (fastest, least safe)
Over time, the file grows. Redis can compact it:
BGREWRITEAOF
Yes. Redis allows using both together to strike a balance:
- Use RDB for fast recovery on full data dumps.
- Use AOF for durability of recent changes.
In case of a restart, Redis will prefer AOF if both exist.
Feature | RDB | AOF |
---|---|---|
Durability | Medium | High |
File Size | Small | Large |
Performance | High | Slower |
Recovery Speed | Fast | Slower |
Use-case | Backup | Reliability |
Redis’s key-value model is extremely powerful thanks to:
- Flexible operations on keys
- Optional time-to-live (TTL) for temporary data
- Persistence mechanisms to ensure data safety
Whether you’re building a cache, message queue, real-time leaderboard, or session store, understanding how to manage key lifecycles and persistence options is crucial for designing reliable systems with Redis.