Persistence: RDB and AOF

RDB — Point-in-Time Snapshots

The core problem: serializing gigabytes takes seconds, and the main thread can't freeze that long. The solution: fork() + Copy-on-Write.

  1. fork() — the kernel creates a child process sharing the same physical pages. Only the page table (address → RAM map) is copied — fast (~ms). The parent resumes serving clients immediately.
  2. Child serializes to disk — walks its COW snapshot, writes dump.rdb.tmp. It sees a frozen view of memory from the moment of fork().
  3. Parent keeps serving writes — a client writes key X; the page holding X is read-only and shared, so the kernel detects the write and copies just that 4 KB page for the parent. The child still reads the original.
  4. Child finishes — fsync(), then an atomic rename dump.rdb.tmp → dump.rdb. Child exits.
fork() + copy-on-write — one page copied per page written
fork() + copy-on-write — one page copied per page written

What you gain: a consistent snapshot at fork time with nearly zero overhead on the main thread. What you lose: every write between the last snapshot and a crash — potentially minutes.

save 900 1      ← auto-save if ≥1 key changed in 900s
save 300 10     ← or ≥10 keys changed in 300s
BGSAVE          ← manual, non-blocking
SAVE            ← manual, BLOCKS EVERYTHING — never in production

Each snapshot is a full rewrite, not an append. You always have exactly one recovery point.

What Is a RAM Page?

RAM isn't managed byte-by-byte — that would mean tracking billions of tiny slots. The OS divides RAM into fixed-size chunks called pages, typically 4 KB.

Page 0:   [ byte 0    ... byte 4095   ]   ← 4 KB chunk
Page 1:   [ byte 4096 ... byte 8191   ]
Page 2:   [ byte 8192 ... byte 12287  ]

A page is just raw bytes — it has no concept of what's stored in it. Large objects span multiple pages; small objects share one:

Redis key "session:abc" = 5000-byte value
Page 11:  [ ...other keys... | first 1000 bytes of "session:abc" ]
Page 12:  [ next 3000 bytes of "session:abc"                     ]
Page 13:  [ last 1000 bytes of "session:abc" | ...other data...  ]

Page 7:   [ dictEntry A | dictEntry B | dictEntry C | ... ~128 of them ]

The Page Table

Every process uses virtual addresses, not physical RAM locations. The page table is the CPU's translation map: virtual address → physical RAM page. At fork() the kernel copies this map and marks every shared page read-only in both processes. No data is copied — just the index.

Before fork():                     After fork():
Redis process                      Parent              Child
page table:                        page table:         page table:
0x1000 → Page 7  [writable]   →   0x1000 → Page 7    0x1000 → Page 7
0x2000 → Page 12 [writable]   →   0x2000 → Page 12   0x2000 → Page 12
                                   (both marked read-only)

Parent writes to virtual address 0x1000
→ Page 7 is read-only → CPU raises a page fault
→ Kernel copies Page 7 → new Page 7'
→ Parent's map: 0x1000 → Page 7' [writable]
→ Child's map:  0x1000 → Page 7  [original, read-only]

Only written pages get copied — 4 KB at a time. Everything else stays shared at zero cost.

AOF — The Write-Ahead Command Log

appendonly yes   → AOF ON  — every write logged, ≤1s data loss on crash
appendonly no    → AOF OFF — RDB is the only persistence, ≤15min data loss

If AOF is off, the only recovery point is the last completed RDB snapshot — under default save triggers that can be up to 15 minutes stale. Typical production setup: both (appendonly yes + RDB enabled). AOF handles durability; RDB provides a compact fast-loading backup.

The three stages and the appendfsync policies are covered in the What Is Redis part. The key line: a crash between Stage 2 (write() to page cache) and Stage 3 (fsync()) loses whatever is still in the page cache. Default and recommendation: everysec — a background thread handles fsync so the main thread never blocks on disk.

AOF Rewrite — Keeping the Log from Growing Forever

The problem: SET k v called 9,999 times = 9,999 lines in the AOF; only the last one matters. The file grows forever and replay slows on every restart. The fix: BGREWRITEAOF produces a compacted AOF from current in-memory state — one command per key.

  1. fork() — child gets a COW snapshot; parent continues serving writes normally.
  2. Child builds the compacted file — iterates every key in its snapshot, writes one command per key to aof.tmp. It never reads the old AOF: memory is the source of truth.
  3. Parent tracks new writes in TWO places — the live AOF (safety net: if the rewrite fails, nothing is lost) and the rewrite buffer (the delta of what changed while the child worked).
  4. Child signals done — parent appends the rewrite buffer to aof.tmp, then atomically renames aof.tmp → aof.
BufferLifetimePurpose
Regular AOF bufferAlways exists; drains every event-loop tick via write()+fsync()Throughput optimization — batches syscalls
Rewrite bufferOnly during BGREWRITEAOF; accumulates the whole delta for as long as the child takesCorrectness mechanism — brings aof.tmp up to present state before the rename

What Redis Loads on Restart

appendonly yes  → load AOF (replay commands top-to-bottom)
appendonly no   → load dump.rdb
both files exist, appendonly no → RDB wins
AOF corrupt mid-file → redis-check-aof --fix truncates at last valid command

Redis 7.0+ multi-part AOF restart: read manifest → learn which base + incr files are active → load base (RDB format — fast, no command replay) → replay incr files in order. Far faster than replaying the entire command history since the beginning of time.

fork() Latency Trap

Transparent Huge Pages (THP) make COW far worse:

4 KB pages: one write → 4 KB copied2 MB pages: one write → 2 MB copied (512× worse)

✓ Disable THP — mandatory in production

echo never > /sys/kernel/mm/transparent_hugepage/enabled

✓ Avoid outright fork() failure

# "Can't save in background:
#  fork: Cannot allocate memory"
sysctl vm.overcommit_memory=1