Maintenance

Site is under maintenance — quizzes are still available.

Go to quizzes

Configure Redis RDB persistence

Learn how to configure RDB (Redis Database) persistence — snapshot-based data durability. Understand configuration, triggers, and trade-offs with practical examples.

Focus: configure redis persistence (rdb)

Sponsored

Imagine your Redis instance holds session data, a leaderboard, or queued jobs — then the server crashes. Without persistence, all that data vanishes the moment the process stops. RDB (Redis Database) snapshots provide a simple, efficient mechanism to save an in-memory point-in-time copy to disk, letting you recover quickly after a restart or failure.

The problem this lesson solves

Redis is primarily an in-memory data store, which means by default it offers blazing speed but no durability guarantee. If you rely on Redis for any data that cannot be afford to lose (cached results, counters, temporary user state), a plain restart erases everything. The problem is obvious: how do you protect your data without sacrificing Redis's performance?

RDB persistence answers this by periodically snapshotting the entire dataset to a binary file on disk. The trade-off is simple: you accept potential loss of the most recent writes (since snapshots are not continuous) in exchange for low overhead and fast restart times. This lesson focuses on configuring RDB persistence so you understand when it fits — and when it doesn't.

Core concept / mental model

Think of RDB persistence like taking a photograph of your Redis database at scheduled moments. The photo is a compact, compressed file (usually dump.rdb) that captures the complete state of all keys, values, and expiration settings. After a crash, Redis loads the most recent photo from disk, restoring your data up to that snapshot time.

RDB snapshot trigger mechanisms

Redis triggers an RDB snapshot automatically based on three conditions you control:

  1. Time-based: The number of seconds that have passed since the last save.
  2. Change-based: The number of write operations (commands like SET, DEL, HSET) executed since the last save.
  3. Manual commands: You explicitly call SAVE or BGSAVE.

Once any configured condition is met, Redis starts a child process (via fork) that writes the full dataset to a temporary RDB file. When successful, the temp file is renamed atomically to the configured dbfilename (default dump.rdb).

Pro tip: Because RDB creates a point-in-time snapshot, changes made after a snapshot begins are not included. The next snapshot will capture those newer writes.

How it works step by step

  1. Redis receives write commands (e.g., SET, HSET, LPUSH) that increment an internal changes counter.
  2. Redis checks the save configuration: The save directive takes two arguments (seconds, changes). For example, save 60 1000 means: "If at least 1000 write commands have been issued in the last 60 seconds, trigger a snapshot."
  3. Fork a child process: When a condition is met, the main Redis process calls fork() to create a child. The child process inherits an exact copy of the parent's memory at that moment.
  4. Child writes to a temporary file: The child writes the dataset to a temp file (e.g., temp-<pid>.rdb) in the directory specified by dir. The parent process can continue serving requests during this time.
  5. Atomic rename: Once writing is complete, the child renames the temp file to the target dbfilename. The parent deletes the previous RDB file if it exists.
  6. On restart: Redis checks for the .rdb file in the configured dir directory. If it exists and is valid, Redis loads it entirely into memory before accepting connections.

Why fork? Fork lets the child write a consistent snapshot without pausing client requests. The child uses copy-on-write, so memory usage may temporarily spike during snapshots — important for sizing large datasets.

Hands-on walkthrough

Let's configure RDB persistence step by step on a local Redis instance. We'll use the official configuration file or change settings at runtime.

Step 1 — Check current persistence settings

Connect to your Redis instance and inspect the active configuration:

redis-cli

Then run:

CONFIG GET save

Expected output:

1) "save"
2) "3600 1 300 100 60 10000"

This output shows three enabled policies: save after 3600 seconds if at least 1 change, after 300 seconds if at least 100 changes, after 60 seconds if at least 10000 changes.

Step 2 — Set a simple custom snapshot rule

Let's configure a snapshot every 120 seconds if at least 50 writes happen:

CONFIG SET save "120 50"

Expected output:

OK

Now verify:

CONFIG GET save

Output:

1) "save"
2) "120 50"

Step 3 — Trigger a manual snapshot with BGSAVE

Write a few keys and then force a background save:

SET user:id:1 "alice"
SET page:views 1024
BGSAVE

Expected output for BGSAVE:

Background saving started

Check the log or database file size:

CONFIG GET dir
CONFIG GET dbfilename
1) "dir"
2) "/var/lib/redis"
1) "dbfilename"
2) "dump.rdb"

Now look at the file on the filesystem:

ls -lh /var/lib/redis/dump.rdb

Output (example):

-rw-rw-r-- 1 redis redis 45K Apr  5 10:32 dump.rdb

Step 4 — Simulate a restart and recovery

Stop Redis (using your OS service manager), then start it again:

redis-cli SHUTDOWN
# or
sudo systemctl restart redis

After restart, connect again and check your keys are still there:

GET user:id:1
GET page:views

Expected output:

"alice"
"1024"

Compare options / when to choose what

Redis offers two persistence mechanisms: RDB (snapshots) and AOF (Append-Only File). Choosing between them depends on your durability requirements and performance profile.

Feature RDB (Snapshot) AOF (Append-Only File)
Data loss window Up to the last snapshot interval Usually 1 second (fsync every sec) or none (fsync always)
File size Compact, compressed Typically much larger; can be compacted via BGREWRITEAOF
Restart speed Very fast (loads a single file) Slower — must replay each write operation
Overhead on writes None during normal ops; CPU/memory spike during snapshot Slight overhead to append to the AOF file
Recovery after crash Recover to last snapshot point Recover full dataset (except last second if fsync policy is "everysec")
Security of writes Not crash-safe between snapshots More durable with appendfsync always
Best use case Caching, session stores, analytics caches where losing a few minutes is acceptable Financial transactions, queues, any system requiring stricter durability

Pro tip: Many production setups enable both RDB and AOF simultaneously. RDB provides fast recovery for large datasets, while AOF protects against intermediate data loss. Disable RDB if you only rely on AOF and want to avoid fork overhead on large datasets.

Troubleshooting & edge cases

1. RDB file not being created

  • Symptoms: BGSAVE returns OK but dump.rdb doesn't appear.
  • Common cause: The dir directory is not writable by the Redis user.
  • Fix: Ensure the directory exists and has correct permissions. Use CONFIG GET dir to confirm the path.

2. Fork failure due to memory pressure

  • Symptoms: BGSAVE fails with "Cannot allocate memory" or similar.
  • Cause: Redis uses fork() so the child needs enough memory to snapshot the dataset (with copy-on-write, 30–50% extra memory).
  • Fix: Increase available memory or reduce dataset size. Consider setting save "" to disable RDB entirely if this is persistent.

3. Data loss after crash despite RDB configured

  • Symptoms: After a restart, some recent writes are missing.
  • Cause: RDB only captures snapshots at intervals. Writes after the last snapshot are lost.
  • Solution: Reduce the snapshot interval (save directive) or combine RDB with AOF persistence for better durability.

4. Corrupted RDB file on disk

  • Symptoms: Redis fails to start, logs show "Bad file format" or checksum mismatch.
  • Cause: Disk corruption, partial write, or misconfiguration.
  • Fix: Remove or rename the corrupted .rdb file and restart. Use the latest backup if available. Consider enabling AOF as a secondary persistence mechanism.

5. High latency during snapshot

  • Symptoms: Occasional spikes in response time, especially in write-heavy workloads.
  • Cause: fork() introduces CPU overhead; copy-on-write may increase memory usage and cause swapping.
  • Fix: Oversubscribe memory less, or use BGSAVE manually during low-traffic periods. Consider using AOF with appendfsync everysec instead.

What you learned & what's next

You now understand how RDB persistence works — its snapshot-based nature, configuration parameters, and when to use it vs. AOF. You learned to enable RDB via save directives, trigger manual snapshots with BGSAVE, verify file location and size, and recover data after a restart. The key takeaway: RDB offers simplicity and fast restart speed at the cost of a data loss window equal to your snapshot interval.

Next, you'll explore AOF persistence — a more durable alternative that logs every write operation. You'll compare the two approaches and learn how to combine them for strong consistency without sacrificing performance.

Practice recap

Practice by configuring a Redis instance with save 60 5 (snapshot every 60 seconds if at least 5 writes occur). Run redis-cli MONITOR to observe snapshot triggers while you write some keys, then shut down the server and restart it. Verify your keys survive. Next, disable RDB with save "", restart, write keys, crash — and compare data loss.

Common mistakes

  • Setting save "" without understanding it disables all RDB persistence — no snapshots will ever be created.
  • Assuming RDB is crash-proof: you can lose data equal to the snapshot interval, which is a fundamental trade-off, not a bug.
  • Forgetting to check write permissions on the dir directory — Redis silently fails to write the RDB file and logs the error in the server log.
  • Running SAVE (blocking) on a production large dataset because SAVE blocks all client requests until the snapshot finishes; always use BGSAVE in production.

Variations

  1. Use redis-cli CONFIG SET to change persistence settings dynamically without restarting the server.
  2. Combine RDB with AOF (both enabled in configuration) to get fast restarts and better durability.
  3. For large datasets (10+ GB), consider adjusting save intervals or using AOF exclusively to avoid excessive fork overhead.

Real-world use cases

  • A session store in a web application — losing the last few minutes of user sessions is acceptable, so RDB with a 5-minute snapshot interval fits perfectly.
  • A leaderboard for a live game — score updates are retrieved from Redis after restart; a few-second loss of new scores doesn't impact fairness.
  • A rate-limiting counter cache — RDB snapshots every 30 seconds sufficient to restore approximate request counts after a server restart.

Key takeaways

  • RDB persistence creates point-in-time snapshots via fork() and writes them atomically to disk.
  • Configure snapshots with the save directive: save <seconds> <changes> enables one rule; multiple rules can be chained.
  • Use BGSAVE for manual snapshots without blocking clients; avoid SAVE in production.
  • RDB trades durability for performance — you lose the last snapshot interval's worth of data on a crash.
  • The RDB file path is controlled by dir and dbfilename; ensure the directory is writable by the Redis user.
  • For stronger durability, combine RDB with AOF persistence or use AOF alone.

Sponsored

Sponsored

Discussion

Questions, corrections, and tips help everyone reading this page.

0 comments

Add a comment

Shown publicly with your comment.

Be constructive · max 4,000 characters

No comments yet — start the thread.

Related tutorials, quizzes, and articles for this topic.