Redis Persistence in Depth
Tested 2026-11-26 on macOS 14.1, Apple M3 Pro; Docker Desktop 4.27.2 (Engine 25.0.3), 11 CPUs and 8 GB for the Docker VM · with Redis 8.10.3 (official Docker image), Docker Desktop 4.27.2 (Engine 25.0.3, macOS), Go 1.26.11, go-redis v9.23.0 · by the fromzero project · CC BY 4.0
Your app sends every new order, session or job to Redis, and Redis keeps all of it in memory.
Then the container is killed: an out-of-memory kill, a crashed host, a docker kill. On Redis’s default settings
it comes back empty: 50 orders written, 0 left.
Turn on snapshots every 10 seconds and kill it again: this time 467 writes that Redis had acknowledged to your app are gone.
A log of every write loses less, and costs more disk work. Which to use, and how much you can lose, is a decision you can measure instead of guess.
This course has you crash Redis on purpose, count what was lost, and read why from Redis’s own counters and files.
You should already have used Redis a little: SET, GET, redis-cli, and run a container with Docker.
Lesson 1 recaps only what persistence depends on (the process, the kernel’s cache, the disk).
By the end you’ll be able to:
- say what a crash, a clean stop and a power cut each take from Redis, and why;
- read
INFO persistenceand the logs to tell what the next crash would lose, and why a save failed; - configure RDB snapshots, the append-only file, or both, with an fsync policy you chose on purpose;
- prove your choice: crash Redis under load, count the lost writes and time the restart.
How it works
Each lesson opens with the problem, then an animated, step-by-step picture (press Play, or step with the
arrow keys), then the mechanism in plain words, with optional Go deeper sections at production depth. Each
practical has you write the config and a small Go program yourself in ~/redis-persistence/: requirements, a
hint, a hidden solution, a “predict first” question and a part where you break it on purpose. One script,
./lab, does the plumbing:
./lab setup p0starts Redis 8.10.3 in a Docker container with its data in a volume, and gives you a startingredis.confwith persistence off. It prints one line per step (every command goes tolab.log) and keeps what you already have../lab check pNtells you whether your work is right. It only reads../lab reset pNstarts you at a practical with a fresh container. It asks first and never touches your files../lab updatefetches the newest script, with the next practical’s checks.
You need Docker and Go 1.21 or newer (Go fetches the newer toolchain the Redis client needs by itself) on macOS or Linux.
Path
| Lesson | Practical | You’ll be able to |
|---|---|---|
| 1 · Why a restart empties Redis | say where a write lives between OK and the disk | |
| 2 · RDB snapshots | 0 · Your Redis, crashed | turn on snapshots, predict a crash’s loss from INFO, fix a MISCONF |
| 3 · The append-only file and fsync | choose an fsync policy, knowing what a process crash and a power cut each lose | |
| 4 · Persistence in production | 1 · Prove your setting | measure lost writes and restart time for your config, and recover a damaged AOF |
What your folder will look like
~/redis-persistence/
├── lab the lab script: ./lab setup|check|reset pN
├── lab.log every command ./lab ran, with its output
├── conf/
│ └── redis.conf the config your container starts with (mounted into it)
├── writer/ your Go program: numbered writes, prints the last one Redis acknowledged
│ ├── go.mod
│ └── main.go
├── crashtest/ your crash harness: writes, kills, restarts, reports lost writes and restart time
│ ├── go.mod
│ └── main.go
├── results.md your numbers for each setting, and your choice
└── aof-backup.tgz the copy of the AOF you make before fixing it
1 · Why a restart empties Redis
In one sentence: Redis answers
OKonce a write is in its memory, and memory dies with the process, so anything Redis hasn’t copied to disk is lost when it’s killed.
The problem
Start Redis 8.10.3 from the official image with no config of your own, write 50 keys, and kill the container:
docker run -d --name demo redis:8.10.3
docker exec demo sh -c 'for i in $(seq 1 50); do redis-cli SET order:$i paid >/dev/null; done; redis-cli DBSIZE'
docker kill demo
docker start demo
docker exec demo redis-cli DBSIZE
50
...
0
All 50 are gone. Every one of them got an OK, so the program that wrote them believes they’re safe.
Now do the same, but stop the container with docker stop instead of docker kill. This time all 50 come back, and
Redis’s log says why:
1:signal-handler (1795677253) Received SIGTERM scheduling shutdown...
1:M 26 Nov 2026 07:14:13.558 * User requested shutdown...
1:M 26 Nov 2026 07:14:13.558 * Saving the final RDB snapshot before exiting.
1:M 26 Nov 2026 07:14:13.560 * DB saved on disk
So Redis can write its data to disk. The kill just never gave it the chance.
Why the kill lost everything
The two commands send different signals:
| Signal | What Redis can do | |
|---|---|---|
docker stop | SIGTERM, then SIGKILL after 10 s if it’s still running | catch it, save a final snapshot, exit |
docker kill | SIGKILL | nothing: the kernel removes the process at once; SIGKILL can’t be caught |
A crash, the kernel’s out-of-memory killer and a power cut are all like the kill: no warning. So the only data that survives them is what Redis had already copied to disk while it was running.
By default it does copy, on a schedule. Ask the fresh container:
docker exec demo redis-cli CONFIG GET save
save
3600 1 300 100 60 10000
These are three save rules, as pairs of seconds and changes: save after an hour if at least 1 key changed, after 5 minutes if at least 100 changed, after 60 seconds if at least 10,000 changed. Fifty writes in a few seconds match none of them yet. Just before the kill, Redis’s own counters said so:
rdb_changes_since_last_save:50
rdb_saves:0
No save had happened, and ls /data after the restart showed an empty directory. Lesson 2 is about these rules.
Two ways to keep a copy
There are only two ideas, and Redis has both:
| Snapshot (RDB) | Log (AOF, the append-only file) | |
|---|---|---|
| What’s written | the whole dataset as it is at one moment, into dump.rdb | every write command, appended as it happens |
| When | by the save rules, or when you ask (BGSAVE) | continuously |
| A crash loses | everything since the last snapshot | only what hadn’t reached the file yet |
| Restart | load one compact file | replay the log |
Think of a bank: a snapshot is the end-of-day balance sheet; a log is the list of every transaction. The balance sheet is small and quick to read, but a fire at 4 pm loses the day. The list loses almost nothing, but it grows and takes longer to replay. Lessons 2 to 4 measure both.
What both rest on: the page cache and fsync
Writing a file is two steps, and the gap between them decides what a power cut takes:
Redis's memory ──write()──▶ page cache (kernel memory) ──fsync() or later──▶ disk
write()hands bytes to the kernel. It returns as soon as they’re in the kernel’s page cache, memory the kernel uses to hold file data before it reaches the disk. The kernel writes them out a little later, on its own schedule.fsync()makes the program wait until the file’s data is actually on the device.
This gives two kinds of crash:
- Redis dies (a kill, a bug, the out-of-memory killer): the kernel is still running, so whatever Redis had passed
to
write()is safe in the page cache and still reaches the disk. - The machine dies (a power cut, a kernel panic): the page cache is lost too. Only what was fsynced survives.
docker kill kills a process, never the kernel, so it’s always the first kind. This course measures that one, and
lesson 3 shows what the second would add.
One more building block, fork(), gets its own explanation in lesson 2: it’s how Redis writes a snapshot
without pausing for it.
Try it
Practical 0, after lesson 2, has you start your own Redis with persistence off, write to it from a Go program, kill it, and count what’s gone; then turn snapshots on and count again.
Go deeper: what Redis does on SIGTERM
SIGTERM (and SIGINT, Ctrl-C) start the same sequence as the SHUTDOWN command: wait up to shutdown-timeout
(10 s) for lagging replicas, stop all clients, run a blocking save if at least one save rule is configured, flush
the append-only file if it’s on, then exit.
A Redis with no save rules and no AOF (a pure cache) skips the save on
purpose, so shutting down doesn’t block. SHUTDOWN NOSAVE skips it on demand; SHUTDOWN SAVE forces one even with
no rules. (SHUTDOWN,
signal handling)
Two consequences: a big dataset makes docker stop slow (the save is blocking), and if the save takes longer than
Docker’s 10 s grace period, SIGKILL arrives mid-save. docker stop -t 60 gives it longer;
stop_grace_period in Compose and terminationGracePeriodSeconds in Kubernetes do the same.
Common misunderstandings
- “
OKmeans it’s on disk.”OKmeans it’s in Redis’s memory. Whether it’s on disk depends on the persistence settings, which is what this course is about. - “The default Redis doesn’t persist.” It does: the default has three save rules. It just saves rarely when there are few writes, and never between the last save and a kill.
- “A restart is a restart.”
docker restartanddocker stopsend SIGTERM first and get a final snapshot if a save rule is set (and an AOF flush if the AOF is on); a crash gets neither. Test with a kill.
Check yourself
1. A Redis with the default rules has had 80 writes since its last save, 10 minutes ago. The kernel's out-of-memory killer kills it. How many of those writes come back?
None. 80 is below the 100 of the 5-minute rule, and the 1-hour rule hasn't come due, so no snapshot holds them, and an out-of-memory kill is a SIGKILL: no final save.2. Redis passed a write to write() but hadn't fsynced it, and then the Redis process crashed. Is the write lost?
No. It's in the kernel's page cache, and the kernel is still running, so it still reaches the disk. It would be lost
if the whole machine had lost power before the kernel wrote it out.
3. Your Redis is a cache you can rebuild from the database. It has no save rules and no AOF. What does docker stop save?
Nothing: with no save rule and no AOF, shutdown skips the save on purpose. For a cache that's the point: it restarts
empty and quickly.
Next: lesson 2 · RDB snapshots.
2 · RDB snapshots
In one sentence: Redis forks a child process that writes the dataset, as it was at the fork, into
dump.rdb, while the parent keeps serving clients; a crash loses every write since that fork.
The problem it solves
Data only survives a kill if it’s already on disk. The simplest way to put it there is to stop, write everything,
and carry on: the SAVE command. On a Redis holding 4,445,566 keys, a PING sent half a second into a SAVE:
docker exec $N redis-cli PING 0.03s user 0.02s system 2% cpu 1.993 total
docker exec $N redis-cli SAVE 0.03s user 0.01s system 1% cpu 2.500 total
The PING, 0.121 s on its own (mostly docker exec), took 1.993 s: Redis runs commands one at a time, so every
client waits for the whole save. A snapshot has to happen beside the work, not in front of it.
How it works: fork, write, rename
BGSAVE (background save) does it in three steps:
- fork. Redis calls
fork(), which creates a child process that is a copy of Redis. The copy is cheap because the kernel doesn’t copy the memory: parent and child share the same pages (4,096-byte blocks of memory). - write. The child walks the dataset and writes it, compressed, into
temp-<pid>.rdb. The parent goes on answering clients. - rename. When the file is complete, the child renames it to
dump.rdb(replacing the old one in one step) and exits. A crash in the middle leaves the previousdump.rdbuntouched.
The log shows all three, here for a million keys:
1:M 26 Nov 2026 07:14:58.146 * Background saving started by pid 73
73:C 26 Nov 2026 07:14:58.555 * BGSAVE done, 1000000 keys saved, 0 keys skipped, 35777608 bytes written.
73:C 26 Nov 2026 07:14:58.560 * DB saved on disk
73:C 26 Nov 2026 07:14:58.560 * Fork CoW for RDB: current 0 MB, peak 0 MB, average 0 MB
1:M 26 Nov 2026 07:14:58.655 * Background saving terminated with success
1:M is the parent (pid 1, the main process), 73:C the child. 152 MB of memory became a 36 MB file in about
0.41 s.
What if a client writes during the save? The kernel uses copy-on-write (CoW): before the parent changes a
shared page, the kernel copies it, so the child keeps seeing the old one. The child’s view stays frozen at the fork,
which is what a snapshot should be. Fork CoW counts the copies: 0 MB here, as nobody was writing.
Save rules: when Redis snapshots by itself
# in redis.conf: save <seconds> <changes> [<seconds> <changes> ...]
save 3600 1 300 100 60 10000 # the default (lesson 1)
save 10 1 # every 10 s if anything changed (Practical 0)
save "" # no automatic snapshots
When a rule’s time has passed and its count of changes is reached, Redis starts a BGSAVE and logs which rule
fired with the rule’s own numbers (not how many keys changed):
1 changes in 10 seconds. Saving.... redis-cli BGSAVE starts one by hand.
What a crash loses, before it happens
The count of changes since the last snapshot is in INFO persistence, and it’s the number a kill would lose right
now. Here is a writer doing about 100 numbered writes a second against save 10 1, then the INFO line and a
kill:
rdb_changes_since_last_save:462
rdb_last_bgsave_status:ok
...
last acknowledged write: 2539
...
2072
The writer’s last acknowledged write was 2539; after the restart the counter read 2072: 467 lost, against 462 predicted. The 5 extra are the writes acknowledged between reading INFO and the kill.
The fields worth knowing:
| Field | Means |
|---|---|
rdb_changes_since_last_save | writes not in any snapshot: what a crash loses now |
rdb_last_bgsave_status | ok or err: did the last save work? |
rdb_last_cow_size | bytes copied by copy-on-write during the last save |
latest_fork_usec (in INFO stats) | how long the last fork() blocked Redis, in microseconds |
What a snapshot costs
fork() itself pauses Redis: the kernel copies the process’s page tables (the map of its memory), which grows
with memory. Copy-on-write costs memory for every page touched during the save. Measured on this course’s
machine:
| Dataset | During the save | Fork pause | Pages copied (CoW peak) |
|---|---|---|---|
| 1,000,000 keys, 152 MB | no writes | 2.5 ms | 0 MB |
| 5,000,000 keys, 771 MB | no writes | 6.4 ms | 1 MB |
| 4,261,469 keys (634 MB just before the writes began) | random SETs from redis-benchmark | 24.6 ms | 690 MB |
Plan for the last row: writes spread over the whole keyspace touched nearly every page, so the save briefly needed about twice the dataset’s memory. Leave room for that.
When a save fails
If a background save fails (full disk, no permission), Redis by default refuses writes with a MISCONF error
until a save succeeds again (stop-writes-on-bgsave-error yes): loud on purpose, so persistence can’t stop silently.
Try it
Practical 0 · Your Redis, crashed: kill Redis under your own Go
writer, turn on save 10 1, predict the next loss from INFO, and break the snapshot on purpose.
Go deeper: how a save rule fires, and retries
Redis checks the rules in serverCron, its periodic task (10 times a second by default), and only when no child is
running. A rule fires when changes >= N and more than the rule’s seconds have passed since the last successful
save. After a failed save, it waits at least 5 seconds (CONFIG_BGSAVE_RETRY_DELAY) before trying again, which is
why fixing the cause of a MISCONF lets writes back in within seconds, without a restart.
(server.c,
persistence docs)
DEBUG POPULATE, used for the measurements above, doesn’t count as changes, which is why
rdb_changes_since_last_save stayed 0 after loading a million keys with it: counters track client writes.
Common misunderstandings
- “
BGSAVEdoesn’t block at all.” The fork does; watchlatest_fork_usec. - “A snapshot finished at 12:00:10 holds the writes up to 12:00:10.” It holds the dataset as it was at the fork.
- “Snapshots always need twice the memory.” Only the pages written during the save are copied.
Check yourself
1. save 60 1000. Your app writes 10 keys a second, steadily. Roughly how much can a crash lose?
About 1,000. At 10 a second, the 1,000 changes take 100 s, so snapshots come about every 100 s, not 60: the count
can delay a save well past its seconds.
2. INFO persistence says rdb_bgsave_in_progress:1 and rdb_changes_since_last_save:300. Redis is killed now. What survives?
The previous complete `dump.rdb`. The save in progress was writing a temp file that never got renamed, so it's
ignored, and all 300 changes are lost. The counter only drops when a save **finishes**: then Redis subtracts the
changes that save held, which is why it counted 830 and then 1 in the animation.
([rdb.c](https://github.com/redis/redis/blob/8.10.3/src/rdb.c), `dirty_before_bgsave`)
3. Your app suddenly gets MISCONF Redis is configured to save RDB snapshots... on every write. Where do you look first?
The Redis log, for why the background save failed (`Permission denied`, `No space left on device`, a fork error),
and `INFO persistence` for `rdb_last_bgsave_status:err`. Fix that cause; Redis retries the save by itself and
accepts writes again once it succeeds.
Next: Practical 0 · Your Redis, crashed, then lesson 3 · The append-only file and fsync.
3 · The append-only file and fsync
In one sentence: with the append-only file (AOF) on, Redis writes every write command to a log before it replies, so killing Redis loses nothing it acknowledged;
appendfsyncdecides how much a dead machine would lose.
The problem it solves
In Practical 0’s example run, save 10 1 lost 467 acknowledged writes on a kill: everything since the last snapshot. Snapshotting
more often means forking more often, and a snapshot writes the whole dataset to save a few changes. The writes
themselves are small. Write them down, one after another, and replay them on restart: that’s the log from
lesson 1’s bank, the list of every transaction.
The log, on disk
Start a Redis with the log on, and snapshots off so only the log is at work:
docker run -d --name demo -v demo-data:/data redis:8.10.3 redis-server --appendonly yes --save ""
docker exec demo redis-cli SET order:1 paid
docker exec demo redis-cli INCR writes
docker exec demo redis-cli INCR writes
docker exec demo ls -l /data/appendonlydir
-rw------- 1 redis redis 89 Nov 26 10:38 appendonly.aof.1.base.rdb
-rw------- 1 redis redis 111 Nov 26 10:39 appendonly.aof.1.incr.aof
-rw------- 1 redis redis 102 Nov 26 10:38 appendonly.aof.manifest
Three files, in a directory of their own (appenddirname, default appendonlydir):
| File | Holds |
|---|---|
…base.rdb | the dataset as of the last rewrite (below); empty here, 89 bytes of header |
…incr.aof | every write since then, appended as it happens |
…manifest | which base and incr files make up the log, in order |
The incr file is the commands themselves, in the protocol clients use to talk to Redis (RESP: *2 = a command
of 2 parts, $4 = the next part is 4 bytes):
*2
$6
SELECT
$1
0
*3
$3
SET
$7
order:1
$4
paid
*2
$4
INCR
$6
writes
The two INCRs are logged as INCR, not as their results. On restart Redis runs the commands again, in order.
What a kill loses now
The writer from Practical 0, at 1,000 writes a second, against appendonly yes with each appendfsync policy,
killed after 10 seconds, twice each:
appendfsync | Last acknowledged | After the restart | Lost |
|---|---|---|---|
always | 9215 · 10027 | 9216 · 10027 | −1 · 0 |
everysec | 10019 · 10000 | 10019 · 10000 | 0 · 0 |
no | 10042 · 10082 | 10042 · 10082 | 0 · 0 |
Nothing lost, under any policy. Redis appends each write to a buffer, and writes the buffer to the file “before
replying to the client” (aof.c). The bytes are then in the kernel’s page cache, and a kill doesn’t touch the
kernel. appendfsync no never calls fsync() and still lost nothing, so the reason is the write(), not the
fsync().
And −1, 9216 for 9215? That last INCR reached the file; its reply never reached the writer, which saw EOF. A failed
write is unknown, not undone: retry only writes that are safe to repeat.
appendfsync: what a power cut adds
A dead machine takes the page cache with it (lesson 1), so what survives is what was fsynced. docker kill
can’t show this (it never kills the kernel), so the losses come from the Redis documentation; the costs are
measured, with redis-benchmark doing SETs inside the container:
appendfsync | fsync() | A power cut loses | SETs/s, 1 client | SETs/s, 50 clients |
|---|---|---|---|---|
always | before every reply | nothing acknowledged (“very very slow, very safe”) | 3,296 | 77,882 |
everysec (default) | once a second, in a background thread | about the last second (“you may lose 1 second of data”) | 26,116 | 318,471 |
no | never: the kernel writes when it likes | what the kernel hadn’t written (“normally Linux will flush data every 30 seconds”) | 25,813 | 341,297 |
| AOF off | 26,976 | 342,466 |
everysec costs almost nothing here. always makes one client about 8 times slower, because every write waits for
the disk; 50 clients lose less (about 4 times), because one fsync() covers all the writes Redis gathered in one pass.
The 30 seconds is this kernel’s dirty_expire_centisecs (3000, in hundredths of a second).
These numbers are from Docker Desktop’s virtual disk on a laptop. The cost of fsync() is the disk’s, so it differs
from disk to disk: measure yours (Practical 1 does).
Rewrite: keeping the log short
The log only grows. 100,000 INCR writes later:
-rw------- 1 redis redis 89 Nov 26 10:38 appendonly.aof.1.base.rdb
-rw------- 1 redis redis 2600111 Nov 26 10:39 appendonly.aof.1.incr.aof
2.6 MB, 26 bytes per INCR, to hold one number. BGREWRITEAOF rewrites it:
-rw------- 1 redis redis 121 Nov 26 10:39 appendonly.aof.2.base.rdb
-rw------- 1 redis redis 0 Nov 26 10:39 appendonly.aof.2.incr.aof
-rw------- 1 redis redis 107 Nov 26 10:39 appendonly.aof.manifest
Like BGSAVE, it forks: the child writes the current dataset as a new base file (in RDB format, since
aof-use-rdb-preamble yes is the default), while the parent sends new writes to a new incr file. When the
child is done, Redis switches the manifest to the new pair and deletes the old files. The log says each step:
1:M 26 Nov 2026 10:39:13.438 * Creating AOF incr file appendonly.aof.2.incr.aof on background rewrite
1:M 26 Nov 2026 10:39:13.438 * Background append only file rewriting started by pid 105
1:M 26 Nov 2026 10:39:13.501 * Successfully renamed the temporary AOF base file temp-rewriteaof-bg-105.aof into appendonly.aof.2.base.rdb
1:M 26 Nov 2026 10:39:13.503 * Removing the history file appendonly.aof.1.incr.aof in the background
Redis rewrites by itself when the log has grown by auto-aof-rewrite-percentage (100: doubled) since the last
rewrite and is at least auto-aof-rewrite-min-size (64 MB). A rewrite costs a fork, like a snapshot (lesson 2).
The fields to watch, in INFO persistence:
| Field | Means |
|---|---|
aof_last_write_status | ok or err: can Redis write the log? |
aof_rewrite_in_progress | 1 while a rewrite’s child runs |
aof_current_size / aof_base_size | the log now / right after the last rewrite |
aof_delayed_fsync | times everysec had to wait for a slow disk (Go deeper) |
Try it
Practical 1, after lesson 4, has you write a Go program that crashes Redis under load, and run it against
snapshots, everysec and always on a dataset you size yourself.
Go deeper: everysec when the disk is slow
With everysec, the fsync() runs in a background thread, so the main thread never waits for it. But on Linux a
write() to a file that’s being fsynced can block. So if the previous fsync() is still running, Redis
postpones its write(), for up to 2 seconds. After that it writes anyway,
logs Asynchronous AOF fsync is taking too long (disk is busy?), and adds 1 to aof_delayed_fsync.
So on a struggling disk, everysec can lose up to about 2 seconds in a power cut, not 1, and aof_delayed_fsync
growing is your sign. (aof.c, flushAppendOnlyFile)
A related setting, no-appendfsync-on-rewrite yes, skips fsyncs while a rewrite or snapshot child is writing, to
avoid that contention; redis.conf warns it can lose up to 30 seconds of log in the worst case. The default is no.
(redis.conf,
persistence docs)
Common misunderstandings
- “
alwaysprotects against a crash better thaneverysec.” Against a crash of Redis, both lose nothing. The difference is a crash of the machine. - “A rewrite reads the old log.” It writes the dataset from memory, like a snapshot.
Check yourself
1. appendonly yes, appendfsync no. The out-of-memory killer kills Redis. How many acknowledged writes are lost?
None. Every acknowledged write was passed to `write()` before its reply, so it's in the page cache, and the kernel
(still running) writes it out. `fsync()` would only matter if the machine had died.
2. Your writer gets EOF on an INCR during a kill. After the restart, has that INCR happened?
You can't tell from the client: it may be in the log (the reply was lost) or not (it never arrived). Read the value
after the restart, or make the write safe to repeat.
3. aof_current_size is 130 MB, aof_base_size is 60 MB, the defaults are in place. Will Redis rewrite by itself?
Yes: 130 MB is more than double 60 MB (100 % growth) and over the 64 MB minimum.
Next: lesson 4 · Persistence in production.
4 · Persistence in production
In one sentence: with the AOF on, the AOF is what Redis loads, so you switch to it on the live server; a restart takes as long as reading the files; the machine must let Redis fork; and a damaged log is checked, backed up, then fixed.
The problem
Lessons 2 and 3 measured what each mechanism loses. Running them for real raises other questions: which file
does Redis load when both are on? How long is a restart’s outage? What does fork() need from the machine? What if
the log is damaged? Which setting should you choose?
Both on: the AOF wins
With save rules and appendonly yes, Redis loads only the AOF on start, “since it is guaranteed to be the
most complete” (persistence docs). Snapshots still make dump.rdb, handy for backups.
That rule has a trap. A Redis with snapshots only, holding 1000 keys, restarted with appendonly yes added to its
config:
$ docker exec demo redis-cli DBSIZE
0
$ docker exec demo ls -l /data/dump.rdb
-rw------- 1 redis redis 22095 Nov 26 11:10 /data/dump.rdb
There was no AOF, so Redis created an empty one and loaded it. The old dump.rdb sat there, ignored, until one
new write made the next snapshot replace it: 22,095 bytes became 109. All 1000 keys gone.
The safe way, on the running server:
docker exec demo redis-cli CONFIG SET appendonly yes
docker exec demo redis-cli INFO persistence | grep -E 'aof_rewrite_in_progress|aof_rewrite_scheduled|aof_last_bgrewrite_status'
CONFIG SET makes Redis rewrite its memory into a new AOF. When both counters are 0 and the status is ok, put
appendonly yes in redis.conf too (or the next restart goes back to the old config), then restart: 1000 keys.
How long a restart takes
Until it has loaded everything, Redis answers every command with LOADING Redis is loading the dataset in memory: for your app, a restart is that long an outage. The same 3,160,831 keys (506 MB in memory, written by
5,000,000 SETs of 100-byte values on random keys), loaded four ways, two restarts each:
| What Redis loads | Size on disk | Loaded in |
|---|---|---|
dump.rdb (AOF off) | 379 MB | 1.49 s, 1.53 s |
| AOF after a rewrite: base in RDB format (the default) | 379 MB | 1.54 s, 1.37 s |
AOF after a rewrite with aof-use-rdb-preamble no: base as commands | 455 MB | 2.26 s, 2.15 s |
AOF before any rewrite: the 5,000,000 SETs | 720 MB | 4.16 s, 3.85 s |
An RDB file loads in about the same time, whether it’s dump.rdb or the AOF’s base. Commands are slower, because each is run again:
3,160,831 (one per key) took about 2.2 s, 5,000,000 for the same keys about 4 s. So the rewrite (lesson 3) also
decides restart time: it turns the commands into an RDB base.
These are small strings on a laptop: measure yours (Practical 1 does).
What the machine needs for fork
Snapshots and rewrites both fork (lesson 2), and the Redis documentation asks for two Linux settings on the host:
vm.overcommit_memory = 1. The child could in theory need a copy of every page, so with the default (0) Linux refuses the fork “unless there is as much free RAM as required to really duplicate all the parent memory pages” (FAQ), and the failed save becomesMISCONF(lesson 2). Set it withsysctl vm.overcommit_memory=1, and in/etc/sysctl.conf.- Transparent huge pages (THP) set to
never(ormadvise, which Redis’s own check accepts). With huge pages, a few writes after a fork can copy “almost the whole process memory”: “big latency and big memory usage” (latency docs).
Redis checks both for you:
docker run --rm --entrypoint redis-server redis:8.10.3 --check-system
[overcommit]...OK
[THP]...WARNING:
You have Transparent Huge Pages (THP) support enabled in your kernel. This will create latency and memory usage issues with Redis. To fix this issue run the command 'echo madvise > /sys/kernel/mm/transparent_hugepage/enabled' as root, and add it to your /etc/rc.local in order to retain the setting after a reboot. Redis must be restarted after THP is disabled (set to 'madvise' or 'never').
That’s Docker Desktop’s virtual machine. Redis 8.10.3 turns THP off for its own process anyway (disable-thp yes;
/proc/1/status shows THP_enabled: 0), but on your servers, run the check and fix what it reports.
(admin docs,
FAQ,
latency docs)
A damaged log
The end cut short (a crash in the middle of a write(), a full disk): Redis drops the half command and starts.
After 1000 INCRs with the last 3 bytes cut off:
# !!! Warning: short read while loading the AOF file appendonly.aof.1.incr.aof!!!
# !!! Truncating the AOF appendonly.aof.1.incr.aof at offset 25997 !!!
# AOF appendonlydir/appendonly.aof.1.incr.aof loaded anyway because aof-load-truncated is enabled
GET writes said 999. That’s aof-load-truncated yes, the default.
Damage in the middle (here, 2 bytes overwritten at offset 10007): Redis refuses to start, and the container exits:
# Bad file format reading the append only file appendonlydir/appendonly.aof.1.incr.aof at offset 10007. make a backup of your AOF file, then use ./redis-check-aof --fix <filename.manifest>. Alternatively you can set the 'aof-load-corrupt-tail-max-size' configuration option to 16016 and restart the server.
redis-check-aof (in the image) finds the same place: ok_up_to=10007, diff=16016. With --fix it cuts the file
there, and everything after the damage goes with it: GET writes said 384, not 1000. That’s why the message
says back up first: once cut, the 616 commands after the damage can’t be recovered, even by hand.
Backups
dump.rdbcan be copied at any time: Redis writes a temp file and renames it (lesson 2), so the file you copy is always complete.- The AOF is several files: copy the whole
appendonlydir, but not during a rewrite. The docs’ recipe:CONFIG SET auto-aof-rewrite-percentage 0, wait foraof_rewrite_in_progress:0, copy, then set it back.
Keeping save rules next to the AOF gives you the simple one. Redis 8.10 also adds a BACKUP command family
(persistence docs, “Backing up Redis data”).
Choosing
| You need | Setting | You pay |
|---|---|---|
| a cache you can rebuild | save "", appendonly no | an empty Redis after any restart |
| to lose at most minutes | save rules only | everything since the last finished snapshot |
| to lose nothing when Redis crashes, and about 1 s in a power cut | appendonly yes, appendfsync everysec, plus save rules for backups | a log to rewrite; almost no speed (lesson 3) |
| to lose nothing acknowledged, even in a power cut | appendfsync always | 7 to 8 times fewer writes a second per client (lesson 3) |
Try it
Practical 1 · Prove your setting: write a Go program that crashes Redis under load, run it against three settings on a dataset you size, and choose one with your own numbers.
Go deeper: what restarts and loads cost in a container platform
Orchestrators stop Redis with SIGTERM, then SIGKILL after a grace period: give it room for the final save (lesson 1’s Go deeper).
A readiness check that sends PING sees LOADING until the dataset is in memory, so traffic only comes back once
Redis can serve it. A liveness check that also fails on LOADING can kill Redis mid-load, again and again, when the
dataset takes longer to load than the check allows.
(SHUTDOWN)
Common misunderstandings
- “With both on, Redis loads whichever is newer.” It loads the AOF, always.
- “
redis-check-aof --fixrepairs the file.” It cuts it at the first damage.
Check yourself
1. A Redis with save rules only holds your data. A colleague adds appendonly yes to redis.conf and runs docker restart. What happens, and what should they have done?
It starts with 0 keys (from a new, empty AOF), and the next snapshot overwrites the old `dump.rdb`. Stop writes
and copy `dump.rdb` now, if it's not too late. The right way: `CONFIG SET appendonly yes` on the running server,
wait for the rewrite, then edit redis.conf.
2. After a power cut, Redis won't start: Bad file format reading the append only file. What are your first three commands?
`redis-check-aof` without `--fix`, to see where the damage is and how much comes after it; a copy of the whole
`appendonlydir`; then `--fix`, knowing it drops everything after the damage.
3. Your Redis has appendonly yes but auto-aof-rewrite-percentage 0. Restarts got slower every week. Why?
Rewrites are off, so the incr file only grows, and a restart replays every command in it. Turn rewrites back on (or
run `BGREWRITEAOF`): the base becomes an RDB, which loads fastest.
Next: Practical 1 · Prove your setting.
Practical 0 · Your Redis, crashed
Goal: a Redis you control, a Go program that counts what Redis acknowledged, a crash that loses everything, snapshots that lose only what
INFOpredicted, and aMISCONFyou cause, diagnose and fix.Time: ~40 minutes. Where: your own computer: files in
~/redis-persistence/, commands in two terminals in that folder. Needs Docker, Go 1.21 or newer, andcurl. Read lesson 1 and lesson 2 first.
Task 1 · Get the lab
mkdir -p ~/redis-persistence
cd ~/redis-persistence
curl -fo lab http://localhost:8800/redis-persistence-deep/tools/lab
chmod +x lab
./lab setup p0
It prints one line per step:
✓ conf/redis.conf in your workspace: persistence off
starting Redis 8.10.3 (a few seconds; longer the first time, while Docker downloads redis:8.10.3)…
✓ Redis 8.10.3 in a container named ...
✓ Go ... (Go fetches the 1.26 toolchain go-redis needs by itself)
Your Redis is the container redis-persist, reachable from your computer at localhost:6390. Its config is your
file conf/redis.conf: open it, it’s three settings, and snapshots are off (save "").
What setup did
It downloaded conf/redis.conf, created a Docker volume redis-persist-data, and ran:
docker run -d --name redis-persist --label fromzero.course=redis-persistence-deep \
-p 127.0.0.1:6390:6379 -v redis-persist-data:/data \
-v "$HOME/redis-persistence/conf:/usr/local/etc/redis" \
redis:8.10.3 redis-server /usr/local/etc/redis/redis.conf
| Part | Why |
|---|---|
-p 127.0.0.1:6390:6379 | your Go program connects from your computer; 6390, not Redis’s usual 6379, so it can’t collide with a Redis you already run; 127.0.0.1 keeps it off your network |
-v redis-persist-data:/data | Redis writes dump.rdb in /data; a named volume keeps it across docker rm |
-v .../conf:/usr/local/etc/redis | your folder, mounted: edit conf/redis.conf on your computer, then docker restart redis-persist |
--label | marks it as this course’s, so ./lab reset removes only what setup made |
Port 6390 taken? REDIS_PORT=6400 ./lab setup p0, then run your writer with REDIS_ADDR=localhost:6400. Running
setup again keeps your container and your redis.conf. Every command is in lab.log.
Task 2 · Write the writer
Create a Go module in ~/redis-persistence/writer/ with a program that:
- connects to the address in
REDIS_ADDR, orlocalhost:6390when it’s not set, with go-redis v9.23.0 (newest release) - runs
INCR writesabout 100 times a second (a flag-rate, default 100), so each acknowledged write has a number - prints
acknowledged Neach time N is a multiple of the rate (once a second) - on the first error, prints
write failed: <the error>, thenlast acknowledged write: N, and exits with status 1 - does not retry: go-redis retries failed commands 3 times by default, which would hide the crash
Hint
go mod init writer, then go get github.com/redis/go-redis/v9@v9.23.0. redis.NewClient(&redis.Options{Addr: ..., MaxRetries: -1}) turns retries off. A time.NewTicker(time.Second / time.Duration(rate)) paces the loop;
rdb.Incr(ctx, "writes").Result() returns the new value.
Solution
mkdir -p ~/redis-persistence/writer && cd ~/redis-persistence/writer
go mod init writer
go get github.com/redis/go-redis/v9@v9.23.0
// writer: numbered writes to Redis at a steady rate; prints the last one Redis acknowledged.
package main
import (
"context"
"flag"
"fmt"
"os"
"time"
"github.com/redis/go-redis/v9"
)
func main() {
rate := flag.Int("rate", 100, "writes per second")
key := flag.String("key", "writes", "the counter to INCR")
flag.Parse()
addr := os.Getenv("REDIS_ADDR")
if addr == "" {
addr = "localhost:6390"
}
rdb := redis.NewClient(&redis.Options{Addr: addr, MaxRetries: -1})
ctx := context.Background()
var last int64
tick := time.NewTicker(time.Second / time.Duration(*rate))
for range tick.C {
n, err := rdb.Incr(ctx, *key).Result()
if err != nil {
fmt.Printf("write failed: %v\nlast acknowledged write: %d\n", err, last)
os.Exit(1)
}
last = n
if n%int64(*rate) == 0 {
fmt.Printf("acknowledged %d\n", n)
}
}
}
Run it from ~/redis-persistence/writer with go run . for a few seconds, then press Ctrl-C. You should see
acknowledged 100, acknowledged 200, …
With a Go older than 1.26, go get says switching to go1.26.11, and the first go run . pauses
while Go downloads the toolchain go.mod now asks for; that happens once.
Task 3 · Crash it with persistence off
Predict first: the writer runs for 20 seconds, then the container is killed. After a restart, what’s in
writes?
Terminal 1, in ~/redis-persistence/writer: go run . Terminal 2, about 20 seconds later:
docker kill redis-persist
Terminal 1 ends with write failed: EOF and the last acknowledged number. Now:
docker start redis-persist
docker exec redis-persist redis-cli GET writes
What you see
An empty line: the key doesn’t exist. Every acknowledged write is gone. Try docker restart instead of the kill
(start the writer again first): with save "" there’s no rule, so the clean shutdown skips its final save too, as
lesson 1’s Go deeper says, and the key is gone again.
Task 4 · Turn on snapshots and predict the loss
Change conf/redis.conf so Redis snapshots every 10 seconds when at least one key changed, then restart and
confirm Redis took it:
docker restart redis-persist
docker exec redis-persist redis-cli CONFIG GET save
Solution
Replace save "" with save 10 1. CONFIG GET save then prints save and 10 1.
Start the writer again in terminal 1 and let it run for 20 to 30 seconds.
Predict first: read the counter and kill Redis in one command, so as little time as possible passes between them. How many writes will be lost?
docker exec redis-persist redis-cli INFO persistence | grep rdb_changes_since_last_save; docker kill redis-persist
docker start redis-persist
docker exec redis-persist redis-cli GET writes
What you see
Lost = the writer’s last acknowledged write minus GET writes, and it’s the rdb_changes_since_last_save you read,
plus the few writes acknowledged between that read and the kill. In the run this course was written from:
rdb_changes_since_last_save:462
...
last acknowledged write: 2539
...
2072
2539 − 2072 = 467 lost, 462 predicted. Yours depends on where in the 10-second cycle the kill landed: anything from
a handful to about 1,000. The counter now continues from what survived: the next go run . starts from there.
Task 5 · Break it: a disk Redis can’t write to
Start the writer in terminal 1, then in terminal 2 take away Redis’s permission to write in /data (-u root
runs the command as root in the container):
docker exec -u root redis-persist chmod 555 /data
Within 10 seconds or so (as soon as the next snapshot is due) the writer stops:
write failed: MISCONF Redis is configured to save RDB snapshots, but it's currently unable to persist to disk. Commands that may modify the data set are disabled, because this instance is configured to report errors during writes if RDB snapshotting fails (stop-writes-on-bgsave-error option). Please check the Redis logs for details about the RDB error.
Investigate in this order, as you would in production:
-
Is it persistence?
docker exec redis-persist redis-cli INFO persistence | grep -E 'bgsave_status|failures'showsrdb_last_bgsave_status:errandrdb_saves_consecutive_failures:1. -
Why did the save fail? The log says:
docker logs redis-persist 2>&1 | grep -E 'Failed|error' | tail -256:C 26 Nov 2026 07:54:32.064 # Failed opening the temp RDB file temp-56.rdb (in server root dir /data) for saving: Permission denied 1:M 26 Nov 2026 07:54:32.165 # Background saving error -
Fix the cause, not the symptom:
docker exec -u root redis-persist chmod 755 /data. Wait 5 to 10 seconds (Redis retries the save by itself), then checkrdb_last_bgsave_statusisokagain and start the writer: it works, with no restart.
Why not just turn the check off?
CONFIG SET stop-writes-on-bgsave-error no makes the error go away, and with it the only sign that nothing is
being saved: the next crash would lose everything since the last good snapshot, however long ago. Turn it off only
when something else (monitoring of rdb_last_bgsave_status) would page you.
Check your work
Your redis.conf should still say save 10 1, and Redis should be running with it.
./lab check p0
All 15 checks should pass. The checker reads your container, conf/redis.conf, writer/ (it builds it), the
writes counter, and whether Redis’s last start loaded your keys from a snapshot (Task 4); it changes nothing.
Next: lesson 3 · The append-only file and fsync.
Practical 1 · Prove your setting
Goal: a Go program of your own that crashes Redis under load and measures what was lost and how long the restart took; your numbers for snapshots,
everysecandalwayson a dataset you size; a damaged log you diagnose and recover; and a written choice of setting, backed by those numbers.Time: ~60 minutes. Where: your computer, in
~/redis-persistence/, with the container from Practical 0. Read lesson 3 and lesson 4 first.
cd ~/redis-persistence
./lab update # this practical's checks
./lab setup p1 # makes sure redis-persist is running; keeps your files and data
Skipped Practical 0, or your lab is in a state you don’t trust? ./lab reset p1 makes the container and its
volume again (your data goes; your files stay). Then put save 10 1 and appendonly no in conf/redis.conf and
docker restart redis-persist.
Task 1 · Size the dataset
Restart time depends on what Redis has to read, so measure on data the size of yours. Fill Redis with
redis-benchmark (it comes with the image): -n writes in all, on -r random keys, of -d bytes each.
Predict first: 3,000,000 writes of 100 bytes on 3,000,000 random keys. How many keys, and how much memory?
docker exec redis-persist redis-benchmark -q -t set -n 3000000 -r 3000000 -d 100 -P 50
docker exec redis-persist redis-cli DBSIZE
docker exec redis-persist redis-cli INFO memory | grep used_memory_human
What you see
SET: 2130681.75 requests per second, p50=1.007 msec
1896042
used_memory_human:302.21M
Fewer keys than writes: random picks repeat, so some writes overwrite a key already set. For your own app, change
-n, -r and -d until used_memory_human is close to your Redis in production (or as much as your Docker can
hold: Docker Desktop’s settings show its memory).
Task 2 · Write the crash harness
Create a Go module in ~/redis-persistence/crashtest/ whose program, run with go run .:
- connects like your writer (
REDIS_ADDR, elselocalhost:6390; go-redis v9.23.0, retries off) - uses a new key for each run (for example
crashtest:<unix time>), set to 0 first - runs
INCRon it about 1,000 times a second (-rate), remembering the last acknowledged number - after 10 seconds (
-for), runsdocker kill redis-persist(-containerfor another name), then waits for the writer to fail - runs
docker start redis-persistand times how long until aGETof the key works (it fails while Redis starts and while it answersLOADING); a key that’s missing (redis.Nil) counts as 0 - prints the number of keys before the kill, the last acknowledged number, the number after the restart, the
difference (
lost), and the restart time in seconds
Hint
Run the writer in a goroutine that sends its last acknowledged number on a channel when a write fails; main
sleeps, kills, then receives from the channel. exec.Command("docker", "kill", name).CombinedOutput() runs Docker.
For the restart: loop rdb.Get(ctx, key).Int64() every 10 ms; go-redis reconnects by itself.
Why a new key: a key left over from an earlier run would look like data that survived.
Solution
mkdir -p ~/redis-persistence/crashtest && cd ~/redis-persistence/crashtest
go mod init crashtest
go get github.com/redis/go-redis/v9@v9.23.0
// crashtest: write numbered INCRs, kill the Redis container mid-stream, start it again,
// and report how many acknowledged writes were lost and how long Redis took to answer again.
package main
import (
"context"
"flag"
"fmt"
"os"
"os/exec"
"time"
"github.com/redis/go-redis/v9"
)
func main() {
rate := flag.Int("rate", 1000, "writes per second")
dur := flag.Duration("for", 10*time.Second, "how long to write before the kill")
name := flag.String("container", "redis-persist", "the Docker container to kill")
flag.Parse()
// a new key each run: a value left by an earlier run can't pass for one that survived this one
key := fmt.Sprintf("crashtest:%d", time.Now().Unix())
addr := os.Getenv("REDIS_ADDR")
if addr == "" {
addr = "localhost:6390"
}
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{Addr: addr, MaxRetries: -1})
if err := rdb.Set(ctx, key, 0, 0).Err(); err != nil {
fmt.Println("can't reach Redis:", err)
os.Exit(1)
}
keys, _ := rdb.DBSize(ctx).Result()
// the writer: one INCR per tick until a write fails; sends the last acknowledged number
lastAck := make(chan int64)
go func() {
var last int64
tick := time.NewTicker(time.Second / time.Duration(*rate))
for range tick.C {
n, err := rdb.Incr(ctx, key).Result()
if err != nil {
lastAck <- last
return
}
last = n
}
}()
time.Sleep(*dur)
if out, err := exec.Command("docker", "kill", *name).CombinedOutput(); err != nil {
fmt.Printf("docker kill failed: %v %s\n", err, out)
os.Exit(1)
}
acked := <-lastAck
start := time.Now()
if out, err := exec.Command("docker", "start", *name).CombinedOutput(); err != nil {
fmt.Printf("docker start failed: %v %s\n", err, out)
os.Exit(1)
}
var got int64
for {
n, err := rdb.Get(ctx, key).Int64() // fails while Redis starts or loads (LOADING)
if err == nil {
got = n
break
}
if err == redis.Nil { // Redis is up, and the key isn't there at all
break
}
if time.Since(start) > 5*time.Minute {
fmt.Println("Redis didn't answer within 5 minutes:", err)
os.Exit(1)
}
time.Sleep(10 * time.Millisecond)
}
restart := time.Since(start)
fmt.Printf("key: %s, keys before the kill: %d\n", key, keys)
fmt.Printf("acknowledged: %d\n", acked)
fmt.Printf("after restart: %d\n", got)
fmt.Printf("lost: %d\n", acked-got)
fmt.Printf("restart: %.2f s (docker start to the first answer)\n", restart.Seconds())
}
Task 3 · Your snapshots
Your conf/redis.conf from Practical 0 says save 10 1 and appendonly no: snapshots only.
Predict first: at 1,000 writes a second, killed after 10 seconds, with a snapshot due every 10 seconds. What’s the most a run can lose? The least?
From ~/redis-persistence/crashtest, run it three times, a few seconds apart, and note each lost and restart:
go run .
What you see
Three runs on the dataset from Task 1:
key: crashtest:1795690741, keys before the kill: 1896044
acknowledged: 10069
after restart: 3
lost: 10066
restart: 1.08 s (docker start to the first answer)
...
lost: 4550
...
lost: 4803
The first run lost almost everything: the last snapshot to finish had started 3 writes into it. A snapshot of
1.9 million keys takes about a second here (docker logs redis-persist shows Saving... and Background saving terminated 1.2 s apart), and one still running at the kill counts for nothing: its half-written
temp-<pid>.rdb is left in /data, never renamed.
So the most is all 10,000. The least is about 1,200: even a snapshot that finishes just before the kill misses the writes made while it ran (1.2 s here). Plan for the worst you saw.
Task 4 · The log: everysec, then always
Turn the AOF on the safe way (lesson 4): on the running server first, then in the file.
docker exec redis-persist redis-cli CONFIG SET appendonly yes
docker exec redis-persist redis-cli INFO persistence | grep -E 'aof_rewrite_in_progress|aof_rewrite_scheduled|aof_last_bgrewrite_status'
When it shows 0, 0 and ok, change conf/redis.conf to appendonly yes and appendfsync everysec (keep
save 10 1), docker restart redis-persist, and check DBSIZE still shows your dataset.
Predict first: how many writes does a kill lose now? Will the restart be slower than with snapshots?
Run go run . three times. Then measure what the policy costs one client:
docker exec redis-persist redis-benchmark -q -t set -n 100000 -c 1
Now change appendfsync to always in conf/redis.conf, docker restart redis-persist, and do the same: three
runs, one benchmark.
What you see
lost: 0
restart: 0.94 s (docker start to the first answer)
...
SET: 25879.92 requests per second, p50=0.039 msec
That’s everysec: 0 lost in all three runs, and restarts about as fast as the snapshots (about 1 s), because the
AOF’s base is an RDB file. With always, also 0 lost (here one run said lost: -1: one more write in the log than
was acknowledged, lesson 3), and:
SET: 3435.01 requests per second, p50=0.295 msec
About 7 times fewer writes a second for one client (7.5 here; 6.6 in a second walk-through on the same machine). What always buys over everysec is a power cut, which a
docker kill can’t show: that part comes from the documentation (lesson 3).
Task 5 · Break it: a damaged log
Simulate a crash in the middle of a write: stop Redis, cut the last 3 bytes off the incr file, start it again.
cd ~/redis-persistence
docker stop redis-persist
docker run --rm -v redis-persist-data:/data redis:8.10.3 sh -c "cd /data/appendonlydir && ls -l && truncate -s -3 appendonly.aof.*.incr.aof"
docker start redis-persist
docker logs redis-persist 2>&1 | grep -E 'short read|Truncating|loaded anyway'
The log says short read, Truncating the AOF, and loaded anyway because aof-load-truncated is enabled: one
command dropped, Redis up. Now damage it in a way Redis won’t forgive, with garbage after the last command:
docker stop redis-persist
docker run --rm -v redis-persist-data:/data redis:8.10.3 sh -c 'echo garbage >> "/data/appendonlydir/$(ls /data/appendonlydir | grep "[0-9].incr.aof$")"'
docker start redis-persist
Your app would now get connection errors. Investigate in this order:
-
Is Redis running?
docker ps -a --filter name=redis-persist --format "{{.Names}} {{.Status}}"saysExited (1). -
Why?
docker logs redis-persist 2>&1 | tail -n 3:Bad file format reading the append only file ... at offset .... -
How much is damaged? Check without changing anything:
docker run --rm -v redis-persist-data:/data --entrypoint redis-check-aof redis:8.10.3 /data/appendonlydir/appendonly.aof.manifest | tail -n 3Read
ok_up_to(where the damage starts) anddiff(how many bytes after it--fixwould remove). -
Back up, then fix:
docker run --rm -v redis-persist-data:/data redis:8.10.3 tar -C /data -czf - appendonlydir > aof-backup.tgz docker run --rm -it -v redis-persist-data:/data --entrypoint redis-check-aof redis:8.10.3 --fix /data/appendonlydir/appendonly.aof.manifest docker start redis-persist docker exec redis-persist redis-cli DBSIZE
What you see
AOF analyzed: filename=appendonly.aof.1.incr.aof, size=11458584, ok_up_to=11458576, ok_up_to_line=1699851, diff=8
This will shrink the AOF appendonly.aof.1.incr.aof from 11458584 bytes, with 8 bytes, to 11458576 bytes
Continue? [y/N]: Successfully truncated AOF appendonly.aof.1.incr.aof
diff=8: exactly garbage and its newline, so --fix (type y) lost nothing and DBSIZE is back. Had the
damage been near the start, diff would have been most of the file: that’s the number to read before you type
y. Your file names and sizes differ.
Task 6 · Choose, and write it down
Create ~/redis-persistence/results.md with one row per setting you measured (the worst lost of three runs,
the restart time, the one-client SETs a second), then a line that starts with choice:, names the setting you’d run for your app first, then says why. Put that setting in conf/redis.conf and docker restart redis-persist.
Example
| setting | worst lost (kill) | restart | SETs/s, 1 client | power cut loses |
|---|---|---|---|---|
| save 10 1 | 10066 | 1.08 s | | everything since the last finished snapshot |
| appendonly yes, everysec | 0 | 1.02 s | 25880 | about 1 s |
| appendonly yes, always | 0 | 1.06 s | 3435 | nothing acknowledged |
choice: appendonly yes, appendfsync everysec, with save 10 1 for backups: loses nothing on a crash of Redis,
about a second in a power cut, and costs almost no speed; always would cut my writes per client about 7 times.
Check your work
./lab check p1
It reads your container and its live config, conf/redis.conf, crashtest/ (it builds it), the dataset’s size,
and results.md, and checks that the setting your choice: line names is the one running. It changes nothing.
Go deeper: make the harness answer more questions
- Add
-for 60sand compareaof_current_sizebefore and after: how fast does your log grow, and how soon wouldauto-aof-rewrite-percentagerewrite it? - Run with
CONFIG SET auto-aof-rewrite-percentage 0and a few million writes, then restart: lesson 4’s 720 MB log took about 4 s to replay. - Send
SIGTERMinstead (docker stop) and watch the restart: withsaverules, shutdown writes a blocking final snapshot first (lesson 1), whichdocker stopwaits for up to its 10 s.
Next: you’ve finished the course. Back to the front page.