Redis Persistence
Redis stores data in memory for speed, but it provides two primary mechanisms to ensure data isn't lost if the server restarts.
1. RDB (Redis Database Backup)
RDB performs point-in-time snapshots of your dataset at specified intervals.
- Pros: Compact file, fast restarts for large datasets, minimal impact on performance (forks a child process).
- Cons: Potential data loss between snapshots. If Redis crashes, you lose all data since the last snapshot.
Configuration (redis.conf):
save 900 1 # Save after 900s if 1 key changed
save 300 10 # Save after 300s if 10 keys changed
dbfilename dump.rdb2. AOF (Append Only File)
AOF logs every write operation received by the server. It replays these operations at startup.
- Pros: Much more durable (can be configured to
fsyncevery second), no data loss. - Cons: Larger file size than RDB, slightly slower performance due to continuous writing.
Configuration (redis.conf):
appendonly yes
appendfsync everysec # Options: always, everysec, no3. Which one to use?
| Feature | RDB | AOF |
|---|---|---|
| Durability | Lower (Snapshot intervals) | Higher (Every second) |
| Performance | High (Writes happen in bg) | Slightly Slower (Continuous I/O) |
| File Size | Optimized/Compact | Large (Grows over time) |
| Recovery Speed | Fast | Slower (Replaying logs) |
[!TIP] Best Practice: Use both. AOF provides durability, while RDB provides a fast way to restart and perform backups. Redis will use AOF to rebuild the state since it is more complete.
4. AOF Rewrite
To prevent the AOF file from growing indefinitely, Redis has a background task that "rewrites" the AOF by creating the shortest sequence of commands needed to rebuild the current dataset.
auto-aof-rewrite-percentage 100
auto-aof-rewrite-min-size 64mb