Redis Persistence
🎯 Introduction
By the end of this article, you will be able to distinguish RDB from AOF and verify whether Redis data can be recovered after a restart.
🪤 Why Redis Data Can Be Lost
Persistence saves in-memory data to disk so it can be recovered after the process restarts. Without persistence, memory contents disappear when the process exits. Even with persistence enabled, writes after the last save may be lost during a failure.
Caches can usually reload from the database; assess the impact of losing sessions, messages, and counts separately. Recovery files kept inside a container without a mounted volume may still be lost when the container is deleted and recreated.
🧱 RDB Snapshots
RDB persists Redis data as a snapshot of a point in time. Recovery reads that file to rebuild the saved state. Background saves usually run in a child process while the main process continues serving requests; saving still consumes CPU, disk, and additional memory.
Use cases: periodically retain a data copy and recover saved state after restarting. Because snapshots capture points in time, changes between them may be lost. For example, save 60 1 triggers saving when the time and change-count conditions are met; it does not persist every write immediately.
🧰 AOF Logging
AOF persists data by continuously recording modifying operations. Redis appends writes to a log and rebuilds data from the saved log on restart. Log writes also need to be synchronized to disk; the synchronization frequency affects how many recent changes may be lost during failure.
Use cases: AOF can save changes more frequently than periodic snapshots. The common appendfsync everysec setting synchronizes roughly once per second. A failure can typically lose about the last second of writes, though disk problems and system scheduling affect actual behavior.
always synchronizes every write at higher cost; no leaves synchronization timing to the operating system. AOF rewriting reduces the historical operations needed for recovery. Redis 7 AOF can contain multiple files; do not back up just one fragment that appears to be the main file.
⚖️ Choosing RDB and AOF
| Method | Main use | Costs or limitations |
|---|---|---|
| RDB | Point-in-time backups and relatively compact recovery files | Changes after the latest snapshot may be lost |
| AOF | Save changes more frequently | Log writing, synchronization, and rewriting overhead |
| Both enabled | Combine log recovery and snapshot backups as needed | Monitor both persistence workflows and disk capacity |
| Neither enabled | Fully rebuildable caches | An empty cache after restart can send many requests to the data source |
When both are enabled, Redis generally prefers AOF for recovery. Persistence is not a backup: accidental deletions are persisted too. Keep separate backups you can restore and practice recovery. See Redis persistence.
🛠 Write Data from Node.js and Verify Restart Recovery
This section uses Node.js 22.9.0, redis 5.9.0, and Redis 7.4.2. Create compose.persistence.yml in your practice directory. The two instances use separate ports and volumes:
services:
rdb:
image: redis:7.4.2
ports:
- "127.0.0.1:6382:6379"
command: ["redis-server", "--save", "60 1", "--appendonly", "no"]
volumes:
- rdb-data:/data
aof:
image: redis:7.4.2
ports:
- "127.0.0.1:6383:6379"
command: ["redis-server", "--save", "", "--appendonly", "yes", "--appendfsync", "everysec"]
volumes:
- aof-data:/data
volumes:
rdb-data:
aof-data:
Port 6382 is for RDB and 6383 for AOF. Volumes keep the files outside the containers. Start both:
docker compose -f compose.persistence.yml up -d
Save this script as persist-write.mjs to write a value without a short expiration:
import { redis } from './redis.mjs';
await redis.connect();
console.log(await redis.set('course:persist:message', 'saved'));
await redis.close();
Run it against each instance. Both runs should print OK:
REDIS_URL=redis://127.0.0.1:6382 node persist-write.mjs
REDIS_URL=redis://127.0.0.1:6383 node persist-write.mjs
Create rdb-save.mjs to explicitly generate a snapshot on the RDB instance:
import { redis } from './redis.mjs';
await redis.connect();
console.log(await redis.bgSave());
The output indicates that background saving has started. Read the persistence status; if saving is still in progress, wait 100 milliseconds and check again until it finishes:
let info = await redis.info('persistence');
while (info.includes('rdb_bgsave_in_progress:1')) {
await new Promise(resolve => setTimeout(resolve, 100));
info = await redis.info('persistence');
}
console.log(info.split('\r\n').find(line => line.startsWith('rdb_last_bgsave_status:')));
await redis.close();
A successful save prints rdb_last_bgsave_status:ok. On failure, check disk space, permissions, and logs before treating the exercise as successful.
REDIS_URL=redis://127.0.0.1:6382 node rdb-save.mjs
docker compose -f compose.persistence.yml restart
Create the read script, persist-read.mjs:
import { redis } from './redis.mjs';
await redis.connect();
console.log(await redis.get('course:persist:message'));
await redis.close();
After the containers finish restarting, read from both instances:
REDIS_URL=redis://127.0.0.1:6382 node persist-read.mjs
REDIS_URL=redis://127.0.0.1:6383 node persist-read.mjs
Both runs should print saved. This verifies recovery after a normal restart, not after sudden power loss or disk corruption. Do not clean up with down -v and then expect recovery from the deleted volumes.
❓ Questions and Answers
Q1: Does enabling persistence restart a key's TTL?
No. Saved data includes expiration information. Keys already expired at recovery do not become fresh again.
Q2: What should I verify after changing persistence settings?
Write data to a separate practice instance, confirm a successful save, then restart and read it. Also verify that the actual data directory or volume matches the configuration.
Q3: Why does restarting after an incorrect update not restore the old value?
Persistence saves the modified state. Recovering an earlier state requires usable historical backups and a recovery procedure.
🧪 Exercise
Modify a test value in a separate RDB instance, manually generate a snapshot, and confirm it succeeded. Restart and verify that the modified value is recovered.
// Write your code here
🎉 You now know the basics of RDB, AOF, and verifying recovery after restart!
