Learn Labs
Persistence

RDB Snapshots

Point-in-time snapshots, fork and copy-on-write, and what they can lose

Redis keeps everything in memory, so without persistence a restart empties it. Redis has two persistence mechanisms, and this repo runs both. The first, RDB, writes a compact binary snapshot of the whole dataset to dump.rdb from time to time.

When snapshots happen

save 3600 1 300 100 60 10000
# snapshot if >= 1 change in 3600s, OR >= 100 changes in 300s, OR >= 10000 changes in 60s

Also on demand, and on a clean shutdown:

BGSAVEsnapshot in the background (what 'save' rules trigger)SAVEsnapshot in the FOREGROUND: blocks every client. Don't.LASTSAVEUnix time of the last successful snapshotSHUTDOWNsaves first (if save rules exist), then exitsINFO persistencerdb_changes_since_last_save, rdb_last_bgsave_status, ...

How BGSAVE works: fork and copy-on-write

fork()Redis (parent)keeps serving clientswrites continuetouched pages copied (COW)childfrozen view at forktemp-1234.rdbwritten + fsyncdump.rdbatomic rename()

fork() creates a child process that sees the dataset exactly as it was at that instant. The OS doesn't copy the memory. Parent and child share the same physical pages, marked copy-on-write: only when the parent modifies a page does the kernel copy it, so the child keeps its frozen view. The child serialises its view to a temp file, fsyncs it, and renames it over dump.rdb, so a crash mid-save never corrupts the previous snapshot.

INFO persistence | grep cow
rdb_last_cow_size:1282048         # bytes copied because the parent wrote during the last save

What RDB can lose

Everything written since the last successful snapshot. With the rules above and low traffic, that can be up to an hour of writes. RDB on its own is a good fit for:

  • caches, where losing recent data only costs some misses
  • backups: one compact file, easy to copy and restore
  • fast restarts: loading an RDB file is much faster than replaying a log

It's a bad fit, on its own, for anything where losing minutes of writes matters. That's what AOF is for.

The file

docker exec redis ls -la /data
-rw------- 1 redis redis 9103 Oct 12 08:05 dump.rdb

# check a file's integrity
docker exec redis redis-check-rdb /data/dump.rdb

RDB files are compressed (LZF) and versioned. Newer Redis versions read older RDB files, but not the other way round, which matters when you restore a backup onto an older server.

Lab

  1. INFO persistence and note rdb_changes_since_last_save.
  2. BGSAVE, then LASTSAVE and ls -la /data.
  3. Check rdb_last_cow_size and latest_fork_usec (in INFO stats).
  4. Restart Redis (docker restart redis) and watch the log: DB loaded from append only file (AOF takes priority when enabled) and how long loading took.

On this page