Skip to content

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

bash
# 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
LASTSAVE
bash
OK
1704067200

5.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

bash
# 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
BGREWRITEAOF
bash
OK

5.3 RDB vs AOF Comparison

FeatureRDBAOF
Persistence methodPeriodic full snapshotAppend write command log
Data safetyMay lose minutes of dataAt most 1 second (everysec)
File sizeCompact (compressed)Larger (text log)
Recovery speedFastSlow (command replay)
Performance impactBrief blocking during forkDepends on write policy
Best forBackup, disaster recoveryHigh 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.

bash
# Enable hybrid persistence
aof-use-rdb-preamble yes

💡 Tip: In production, it's strongly recommended to enable hybrid persistence + appendfsync everysec to balance data safety and recovery speed.