Configure Redis AOF
Set up Append-Only File persistence in Redis step by step. Learn how to enable AOF, tune fsync policies, compare durability and performance trade-offs, and troubleshoot common edge cases. Hands-on exercise included.
Focus: configure redis persistence aof
You’ve built a Redis cache that’s fast and responsive—until the server restarts and every carefully stored key vanishes. Without persistence, Redis keeps all data in memory, which means any crash, reboot, or failover wipes your state. That’s fine for ephemeral caching, but once you need durability—session stores, counters, job queues—you must configure persistence. This lesson walks you through Append-Only File (AOF) persistence, the most granular and safest way to keep your data safe without sacrificing the write performance you expect from Redis.
The problem this lesson solves
Redis runs entirely in RAM to achieve sub-millisecond latency. When the process dies or the machine restarts, that RAM contents disappear unless you’ve explicitly saved them somewhere. The default snapshot-based persistence (RDB) saves a point-in-time dump, but if your Redis crashes between snapshots, you lose all writes since the last save. For workloads where every write matters—order confirmations, live leaderboards, real-time analytics—RDB alone isn’t enough. This is the exact problem Append-Only File (AOF) persistence solves: it logs every write operation to disk as it happens, giving you a replayable record that can recover data with second (or even sub-second) granularity.
Core concept / mental model
Think of AOF as a write-ahead log (WAL) like the one databases such as PostgreSQL use. Every time a client sends a SET, INCR, or LPUSH command, Redis appends that command to a file—usually appendonly.aof. On restart, Redis replays every command in the AOF file verbatim to reconstruct the dataset.
The durability knob is the appendfsync policy, which controls when Redis forces data from the kernel buffer to persistent storage:
- always: fsync after every write — safest, slowest.
- everysec: fsync once per second — good durability with modest overhead.
- no: let the OS decide — fastest, least durable.
Pro tip: In production,
appendfsync everysecis the sweet spot. It limits data loss to at most 1 second of writes and avoids the throughput hit of per-command fsync.
The AOF file grows over time, so Redis includes a rewrite mechanism: it forks a child process that builds a new compact AOF from the current in-memory state, then atomically replaces the old file. This keeps AOF size manageable.
How it works step by step
- Enable AOF – Set
appendonly yesinredis.confor runCONFIG SET appendonly yesat runtime. - Choose fsync policy – Pick
appendfsync always|everysec|nobased on your durability/latency needs. - Configure rewrite triggers – The defaults (
auto-aof-rewrite-percentage 100andauto-aof-rewrite-min-size 64mb) work well; adjust if you have large datasets or want less frequent rewrites. - Load existing data – On restart, Redis automatically reads and executes the commands in
appendonly.aof. - Handle corruption – If the AOF file becomes truncated or corrupted (e.g., disk full during a write), use
redis-check-aof --fixto repair it.
The sequence matters: you enable AOF first, then tune the fsync policy, then confirm the file path (appenddirname for Redis 7.x+, or the old appendonly filename). Always test on a non-production instance before rolling to production.
Hands-on walkthrough
Let’s get your hands dirty. Start a Redis CLI and server in two terminals.
Step 1 – Enable AOF at runtime (non-persistent until config file change)
redis-cli
Inside the CLI:
127.0.0.1:6379> CONFIG SET appendonly yes
OK
127.0.0.1:6379> CONFIG SET appendfsync everysec
OK
Expected output: both commands return OK. Your AOF is now active for this session. Run INFO PERSISTENCE to verify:
127.0.0.1:6379> INFO PERSISTENCE
# Persistence
loading:0
rdb_changes_since_last_save:0
rdb_bgsave_in_progress:0
rdb_last_save_time:1678901234
...
aof_enabled:1
aof_rewrite_in_progress:0
aof_last_rewrite_time_sec:-1
...
Look for aof_enabled:1.
Step 2 – Write data and check AOF file
127.0.0.1:6379> SET user:1001 "Alice"
OK
127.0.0.1:6379> INCR counter:orders
(integer) 1
Exit the CLI. Check the AOF file (default location depends on dir in config):
cat /var/lib/redis/appendonly.aof | head -20
You should see raw Redis protocol commands:
*2
$6
SELECT
$1
0
*3
$3
SET
$10
user:1001
$7
Alice
*2
$4
INCR
$14
counter:orders
Step 3 – Trigger an AOF rewrite
redis-cli BGREWRITEAOF
Check status: INFO PERSISTENCE shows aof_rewrite_in_progress:0 when done. The rewritten file is much smaller than the raw log if you had many commands.
Step 4 – Simulate a crash and recover
If you kill and restart Redis, it automatically replays the AOF. Test by killing the process:
pkill redis-server
# wait 2 seconds
redis-server /etc/redis/redis.conf &
redis-cli
Then verify your keys still exist:
127.0.0.1:6379> GET user:1001
"Alice"
127.0.0.1:6379> GET counter:orders
"1"
If the AOF file was truncated (partial write), Redis refuses to start by default. Use redis-check-aof --fix appendonly.aof to recover—though you’ll lose the last incomplete command.
Compare options / when to choose what
| Persistence | Durability | Performance | Use case |
|---|---|---|---|
| RDB only | Point-in-time snapshots (lost writes between saves) | Excellent for reads, write overhead minimal | Caching, read-heavy workloads, can tolerate some data loss |
AOF always |
Maximum – each write fsynced | Slower writes (up to 3×) | Financial transactions, critical counters |
AOF everysec |
Up to 1 second data loss | Good – typical 10-20% write overhead | General production (caches with state, leaderboards, queues) |
AOF no |
Unpredictable (OS decides) | Fastest | Batch jobs, ephemeral data, test environments |
| AOF + RDB combined | Best of both – fast restart from RDB, durability via AOF | Moderate overhead | Highly recommended for most production setups |
When to choose what:
- If you can lose 5-15 minutes of writes, RDB only is fine.
- If you need recovery within seconds of a crash, use AOF with everysec.
- If you run financial data where not a single write can vanish, pair appendfsync always with a journaling filesystem (XFS or ext4).
- For high-throughput event ingestion (millions of writes/second), everysec with a separate disk for the AOF file reduces latency spikes.
Pro tip: Enable both RDB and AOF in production. Redis loads the AOF first (it’s more complete), but RDB gives you a faster restart if the AOF becomes very large.
Troubleshooting & edge cases
AOF file too large – Auto-rewrite kicks in when the file grows to double the size of the last rewrite (default 100%) and at least 64 MB. If rewrites cause latency, increase auto-aof-rewrite-percentage to 200 or manually run BGREWRITEAOF during low traffic.
Background rewrite fails – Check the log for AOF rewrite: fork failed. Usually because of memory limits or overcommit. Set vm.overcommit_memory = 1 in /etc/sysctl.conf. Also ensure maxmemory leaves room for the fork copy-on-write.
Redis won’t start after crash – Reads “Bad file format” or “Unexpected end of file”. Fix with:
redis-check-aof --fix /var/lib/redis/appendonly.aof
This trims the last incomplete command. Startup should work after. Always back up the file before fixing.
fsync spikes – If appendfsync always causes periodic 300ms pauses on SSDs, switch to everysec. If you need every-write durability, use a dedicated fast disk (NVMe) and isolate AOF writes from data directories.
AOF replay is slow on huge files – On very large AOFs (tens of GB), restart can take minutes. Combine RDB + AOF: Redis loads the RDB first, then replays only the AOF delta, cutting restart time dramatically.
Edge case: If
appendonlyis enabled after data already exists in memory, those existing keys are not automatically written to AOF until you triggerBGREWRITEAOF. Always issue a rewrite after enabling AOF on a hot instance.
What you learned & what's next
You now know how to configure Redis AOF persistence — from enabling it and choosing appendfsync policies to triggering rewrites and recovering from corruption. You understand the trade-off between always (most durable), everysec (balanced), and no (fastest). You’ve seen how AOF complements RDB and how to safely combine them for production durability.
Next lesson: Once persistence is solid, you’ll want to back up and restore your Redis data — covering RDB snapshots, AOF file management, and point-in-time recovery in a failure scenario. You’re ready to move to Lesson 31: Redis Backup and Restore Strategies.
Practice recap
Start a fresh Redis instance. Enable AOF with appendfsync everysec, write 100 keys, then kill and restart the server. Verify all keys exist. Next, simulate AOF corruption by truncating the last 10 bytes of appendonly.aof with dd, then repair it with redis-check-aof --fix and restart successfully.
Common mistakes
- Enabling AOF at runtime with
CONFIG SET appendonly yesbut never adding the directive toredis.conf— the setting reverts after restart, leaving you unprotected. - Using
appendfsync alwaysunder heavy write load without understanding that it can degrade throughput by 3× and cause latency spikes on SSDs. - Forgetting to run
BGREWRITEAOFafter enabling AOF on a dataset that already has thousands of keys — the AOF file only logs commands issued after the enable. - Assuming AOF alone is enough for disaster recovery — if the only copy of
appendonly.aoflives on the same disk as Redis data, a disk failure loses everything.
Variations
- Use
aof-use-rdb-preamble yes(default in Redis 5+) to combine an RDB snapshot at the start of an AOF file, giving faster reload times while keeping AOF durability. - For ultra-high throughput, consider disabling AOF rewrites entirely and scheduling periodic
BGREWRITEAOFduring off-peak hours using a cron job. - If you need cross-region durability, stream every write command to a separate replication node with its own AOF — not a direct AOF variation, but it avoids single-disk failure.
Real-world use cases
- A real-time leaderboard for a gaming platform — any crash must lose at most 1 second of score updates to prevent player disputes.
- A session store for an e-commerce checkout flow — losing session data after a restart would log logged-in users out mid-purchase.
- A job queue for image processing — AOF guarantees that queued tasks are never silently dropped after a Redis restart.
Key takeaways
- AOF logs every write command to an append-only file on disk, enabling replay-based recovery with second-level granularity.
- Choose
appendfsync everysecfor the best balance of durability (≤1s data loss) and performance (10-20% writes overhead). - AOF rewrites prevent unbounded file growth by compacting the log into the current in-memory state.
- Combine AOF with RDB in production: Redis starts faster from RDB and fills gaps from AOF.
- Use
redis-check-aof --fixto repair truncated AOF files; always back up before fixing. - Enable AOF in
redis.conf, not just at runtime, to survive restarts.
Keep learning
Related tutorials, quizzes, and articles for this topic.
Discussion
Questions, corrections, and tips help everyone reading this page.
0 comments
Add a comment
No comments yet — start the thread.