AOF (Append Only File)
While RDB is great for backups, it lacks the durability required for critical applications. For that, Redis provides AOF (Append Only File) Persistence.
1. How AOF Works
AOF doesn’t save the state of the memory; it saves every Write Operation as a command log.
- Whenever a client runs
SET key val, Redis appends that command to the AOF file on disk. - If Redis crashes, it can replay the entire log to reconstruct the exact state of the database.
2. The fsync Strategy
Writing to disk is expensive. You can control how often Redis flushes the AOF buffer to disk:
- appendfsync always: Fsync after every write. Max durability, but very slow.
- appendfsync everysec: Fsync every second. Recommended. Lost maximum of 1 second of data.
- appendfsync no: Let the OS decide when to flush. Fastest, but least safe.
3. AOF Rewrite (Compaction)
Over time, the AOF file grows infinitely large. To prevent this, Redis uses AOF Rewrite.
- Imagine you set
counterto 1, then 2, then 3. The AOF has three commands. - A Rewrite will read the current value in memory (
3) and write a single command:SET counter 3. - This significantly reduces the file size without losing any current data.
4. Interactive: Log Replayer
Simulate a server crash and watch the AOF replay the log.
AOF File
SET key1 val1
INCR count
SET user:1 foo
➡️
REDIS UP
5. RDB vs AOF: Which to choose?
- Use RDB if you can tolerate a few minutes of data loss and want the fastest possible recovery.
- Use AOF if you need high durability.
- Use BOTH (Recommended): Redis is designed to work with both at once. RDB provides the foundation for backups, while AOF provides the safety net for the most recent changes.