5. Persistence
Redis data lives in memory — once the server crashes, data is lost. Persistence is like "taking a photo archive" of memory data and saving it to disk.
5.1 RDB (Redis Database Snapshot) — Full Snapshot
📸 Analogy: RDB is like taking a "full-color snapshot" of the database, saving the complete data at a specific moment into a compressed binary file (dump.rdb).
Pros: Compact file, fast recovery, doesn't affect main process performance
Cons: Data between two snapshots may be lost
# RDB configuration in redis.conf
save 900 1 # Snapshot if 1 modification in 900 seconds
save 300 10 # Snapshot if 10 modifications in 300 seconds
save 60 10000 # Snapshot if 10000 modifications in 60 seconds
dbfilename dump.rdb # Snapshot filename
dir /var/lib/redis # Snapshot file directory
# Manually trigger snapshot
SAVE # Blocking (not recommended for production)
BGSAVE # Background async snapshot (recommended)
# Check last snapshot status
LASTSAVEOK
17040672005.2 AOF (Append Only File) — Append Log
📝 Analogy: AOF is like an "operation log" that records every write command. During recovery, it replays all logs to restore data.
Pros: Safer data (at most 1 second of data loss), human-readable logs
Cons: Larger files, slower recovery
# AOF configuration in redis.conf
appendonly yes # Enable AOF
appendfilename "appendonly.aof"
# Sync policy (choose one of three)
appendfsync always # Sync every command (safest, slowest)
appendfsync everysec # Sync every second (recommended! balance of safety & performance)
appendfsync no # Let OS decide (fastest, least safe)
# AOF rewrite configuration
auto-aof-rewrite-percentage 100 # Trigger rewrite when AOF file grows 100%
auto-aof-rewrite-min-size 64mb # AOF must be at least 64MB before rewriting
# Manually trigger rewrite
BGREWRITEAOFOK5.3 RDB vs AOF Comparison
| Feature | RDB | AOF |
|---|---|---|
| Persistence method | Periodic full snapshot | Append write command log |
| Data safety | May lose minutes of data | At most 1 second (everysec) |
| File size | Compact (compressed) | Larger (text log) |
| Recovery speed | Fast | Slow (command replay) |
| Performance impact | Brief blocking during fork | Depends on write policy |
| Best for | Backup, disaster recovery | High data safety requirements |
5.4 Hybrid Persistence (Redis 4.0+)
Combines the advantages of RDB and AOF: during AOF rewrite, the first part is RDB-format snapshot data, and the second part is incremental AOF commands.
# Enable hybrid persistence
aof-use-rdb-preamble yes💡 Tip: In production, it's strongly recommended to enable hybrid persistence +
appendfsync everysecto balance data safety and recovery speed.