Video in progress

Strong Middle ⚡ Redis and caching

Why is AOF rewrite needed, and how does the appendfsync setting affect data safety and speed?

AOF appends every write and grows without limit; a rewrite writes the current state as a minimal set of commands to a new file and replaces the old one. appendfsync always is the safest and slowest, everysec is the practical balance with about 1 s of loss, and no leaves fsync to the OS.

📖 Answer

Why rewrite: if you INCR a counter a million times, the AOF has a million lines, while the current state is a single SET counter 1000000. A rewrite calls fork(), the child process writes a new base file from the in-memory state, and the writes that arrive in the meantime are collected separately.

appendonly yes
appendfsync everysec
auto-aof-rewrite-percentage 100   # when the file doubles since the last rewrite
auto-aof-rewrite-min-size 64mb
no-appendfsync-on-rewrite no

The fsync options:

appendfsync Loss on a crash Cost
always nearly none a disk fsync on every write, throughput drops sharply
everysec about 1 s (up to 2 s if the disk is slow) done in the background, not noticeable
no whenever the OS writes it, tens of seconds fastest

A subtle point: with everysec, if the disk is busy (for example, while a rewrite is writing in parallel), the fsync is delayed and after 2 seconds Redis makes the main thread wait for the write; the log shows "Asynchronous AOF fsync is taking too long". no-appendfsync-on-rewrite yes softens this, but widens the loss window during the rewrite.

After a crash the end of the AOF may be incomplete; by default Redis truncates the incomplete tail and loads (aof-load-truncated yes). If the middle of the file is corrupted, you'll need redis-check-aof --fix.