Redis Persistence
Redis keeps its data in memory, but it can also write it to disk so that a restart or a crash does not wipe everything. There are two mechanisms, RDB snapshots and the AOF (append-only file), and you can use either, both, or neither. Choosing between them is a trade-off between performance, disk usage and how much data you can afford to lose.
RDB: point-in-time snapshots
An RDB file (dump.rdb) is a compact binary snapshot of the whole dataset at one moment. Redis creates it in the background: the main process forks, and the child writes the snapshot while the parent keeps serving clients. Thanks to the operating system's copy-on-write, the fork is cheap at first, but memory use grows if many keys change during the snapshot.
Snapshots are triggered by save rules in the configuration ("after N seconds if at least M keys changed"), or by hand:
# redis.conf
save 3600 1 # snapshot after 1 hour if at least 1 key changed
save 300 100 # after 5 minutes if at least 100 keys changed
save 60 10000 # after 1 minute if at least 10000 keys changed
dbfilename dump.rdb
dir /var/lib/redisThe playground server is started with snapshots and AOF switched off (every example starts empty anyway), which you can check with CONFIG GET. BGSAVE still works and starts a background snapshot:
CONFIG GET save
CONFIG GET appendonly
SET order:1001 paid
BGSAVEredis> CONFIG GET save
1) "save"
2) ""
redis> CONFIG GET appendonly
1) "appendonly"
2) "no"
redis> SET order:1001 paid
OK
redis> BGSAVE
Background saving started
SAVE does the same in the foreground, blocking every client until it finishes, so it is only for maintenance scripts. LASTSAVE returns the Unix time of the last successful snapshot.
AOF: a log of every write
The append-only file records every write command as it happens. On restart Redis replays the log and rebuilds the dataset. How often the log is flushed to the physical disk with fsync decides how much you can lose:
appendfsync |
Behaviour | Worst-case loss |
|---|---|---|
always |
fsync after every write | almost nothing, but slow |
everysec (default) |
fsync once per second in the background | about 1 second of writes |
no |
let the operating system decide | up to ~30 seconds on Linux |
Because the log keeps growing (a counter incremented a million times means a million entries), Redis rewrites it in the background, replacing the history with the shortest commands that recreate the current state. Since Redis 7 the AOF is a directory with a base file (in RDB or AOF format) plus incremental files and a manifest.
A model of AOF replay and rewrite
This Python model logs write commands, replays them to rebuild the data, and then rewrites the log to its minimal form:
log = []
data = {}
def write(*cmd):
"""Execute a write and append it to the log, like Redis with AOF on."""
op, key, *args = cmd
if op == "SET":
data[key] = args[0]
elif op == "INCR":
data[key] = str(int(data.get(key, "0")) + 1)
elif op == "DEL":
data.pop(key, None)
log.append(" ".join(cmd))
write("SET", "user:1", "Ada")
for _ in range(5):
write("INCR", "visits")
write("SET", "temp", "x")
write("DEL", "temp")
print("log entries:", len(log))
def replay(entries):
state = {}
for line in entries:
op, key, *args = line.split()
if op == "SET":
state[key] = args[0]
elif op == "INCR":
state[key] = str(int(state.get(key, "0")) + 1)
elif op == "DEL":
state.pop(key, None)
return state
print("after restart:", replay(log))
rewritten = [f"SET {k} {v}" for k, v in sorted(data.items())]
print("rewritten log:", rewritten)
print("same data:", replay(rewritten) == data)log entries: 8
after restart: {'user:1': 'Ada', 'visits': '5'}
rewritten log: ['SET user:1 Ada', 'SET visits 5']
same data: True
Eight log entries shrink to two, and replaying either log gives the same data.
Comparing the options
| RDB | AOF | RDB + AOF | |
|---|---|---|---|
| File size | small, compact | larger | both |
| Restart speed | fast | slower (replay) | fast (base file is RDB) |
| Data loss on crash | everything since the last snapshot (minutes) | about 1 second (everysec) |
about 1 second |
| Impact on performance | periodic fork | constant small writes | both |
| Good for | backups, disaster recovery, caches you can rebuild | data you cannot lose | most production systems |
Typical choices:
- Pure cache: no persistence at all (
save "",appendonly no). After a restart the cache warms up again from the database. - Important data (sessions, queues, counters): AOF with
everysec, plus RDB snapshots copied off the machine as backups. - Analytics you can recompute: RDB every few minutes.
# redis.conf for "important data"
appendonly yes
appendfsync everysec
aof-use-rdb-preamble yes # base file in RDB format: faster restarts
save 900 1 # still take snapshots for backupsBackups
An RDB file is safe to copy while Redis is running, because Redis writes a new file and then renames it atomically. A simple backup job:
redis-cli BGSAVE
# wait until INFO persistence shows rdb_bgsave_in_progress:0, then:
cp /var/lib/redis/dump.rdb /backups/redis-$(date +%F).rdbNote: Persistence protects against restarts and crashes of one machine. It does not protect against losing the machine itself. For that you need replication to other servers and backups stored elsewhere, which the next lesson covers.
Test yourself
With appendfsync everysec, roughly how much data can be lost in a crash?
- Nothing
- About one second of writes
- Everything since the last snapshot
- The whole dataset
How does Redis create an RDB snapshot without stopping clients?
- It locks each key in turn
- It forks a child process that writes the snapshot
- It copies memory to another server
- It cannot: BGSAVE blocks clients
What does an AOF rewrite do?
- Deletes old keys
- Replaces the command history with a minimal set of commands that recreates the current data
- Converts AOF to JSON
- Encrypts the file