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.