How Does Redis Implement Persistence with RDB and AOF?

Redis guarantees data durability through two complementary mechanisms: RDB (point-in-time binary snapshots) and AOF (append-only command logs), both implemented in Redis core and configurable via redis.conf.

Redis stores data in memory for high-performance access, but provides robust persistence options to survive process restarts or server crashes. According to the Snailclimb/JavaGuide repository documentation, Redis implements two distinct persistence strategies at the C code level—RDB snapshots and AOF logging—that can be used individually or combined for maximum data safety.

Redis RDB Persistence (Snapshotting)

RDB (Redis Database) persistence performs point-in-time snapshots of your dataset at specified intervals, creating a compact binary file (dump.rdb) that can be reloaded on startup.

How RDB Works

When a snapshot is triggered, Redis forks a child process to handle the bgsave operation. The child process writes the in-memory data structures to a temporary file using the RDB binary format, which includes fields like REDIS, RDB_VERSION, DB_NUM, KEY_VALUE_PAIRS, EOF, and CHECK_SUM. Once the child completes the write, the temporary file is atomically renamed to dump.rdb.

Because the child process runs independently, the main thread stays non-blocking during background saves. This architecture ensures that Redis can continue serving client requests while persisting data to disk.

Triggering RDB Snapshots

You can configure automatic snapshots or trigger them manually:

  • Automatic triggers: Use the save <seconds> <changes> directive in redis.conf (e.g., save 900 1 saves if at least 1 key changed in 15 minutes)
  • SAVE command: Synchronous operation that blocks the main thread until completion
  • BGSAVE command: Asynchronous operation that forks a child process (preferred for production)

As detailed in docs/database/redis/redis-persistence.md, the BGSAVE approach prevents latency spikes during persistence operations.

RDB Advantages and Trade-offs

Pros:

  • Compact binary files ideal for backups and disaster recovery
  • Fast restart times—Redis loads the entire dataset in one operation
  • Minimal runtime performance impact when using BGSAVE

Cons:

  • Potential data loss between the last snapshot and a crash (up to the configured interval)
  • CPU and memory overhead during child process forking and disk writes

Redis AOF Persistence (Append-Only File)

AOF (Append-Only File) persistence logs every write command (e.g., SET, INCR) to a file (appendonly.aof). On restart, Redis replays this log to reconstruct the dataset.

How AOF Works

The AOF implementation follows a five-step workflow as described in the JavaGuide documentation:

  1. Append: Commands are appended to an in-memory buffer (server.aof_buf)
  2. Write: The buffer is written to the OS page cache using the write syscall
  3. fsync: Data is flushed to disk according to the appendfsync policy—this is the actual durability point
  4. Rewrite: When the AOF grows too large, Redis forks a child that creates a new compact AOF containing minimal commands needed to reconstruct the current dataset
  5. Load: During startup, Redis reads the AOF line by line and re-executes each command

AOF fsync Policies

The appendfsync configuration determines the balance between durability and performance:

  • always: fsync after every write—safest but blocks the main thread, impacting latency
  • everysec: fsync once per second—default trade-off allowing at most 1 second of data loss
  • no: Let the OS handle flushing—fastest but riskiest (approximately 30 seconds of data loss possible)

AOF Rewrite Process

AOF files can grow large over time. Redis handles this through AOF rewrite, where a child process creates a new minimal AOF file containing only the commands necessary to recreate the current state. This process temporarily doubles write I/O but prevents unbounded file growth.

AOF Advantages and Trade-offs

Pros:

  • Near-real-time durability, especially with appendfsync everysec
  • Human-readable command log for easy inspection and manual recovery
  • More granular data recovery compared to RDB snapshots

Cons:

  • Larger file sizes compared to RDB (every write is stored)
  • Slower restart times due to command replay overhead
  • AOF rewrite can temporarily increase disk I/O load

Hybrid Persistence Mode (RDB + AOF)

Since Redis 4.0, you can enable mixed persistence using the aof-use-rdb-preamble yes configuration. In this mode, the AOF file begins with an RDB preamble (binary snapshot) followed by incremental AOF commands.

This hybrid approach combines the fast restart benefits of RDB with the granular durability of AOF, providing both quick recovery and minimal data loss. The JavaGuide documentation in docs/database/redis/redis-persistence.md recommends this configuration for production systems requiring high availability.

Configuring Redis Persistence

RDB Configuration Examples

Configure automatic snapshots via redis.conf or runtime commands:


# Disable default save schedules

CONFIG SET save ""

# Save every 5 minutes if at least 5 keys changed

CONFIG SET save "300 5"

# Trigger manual snapshots

SAVE          # Synchronous - blocks server

BGSAVE        # Asynchronous - preferred

AOF Configuration Examples

Enable and tune AOF persistence:


# Enable AOF

CONFIG SET appendonly yes

# Choose durability level

CONFIG SET appendfsync everysec   # Default - 1 second safety window

CONFIG SET appendfsync always     # Maximum durability, higher latency

CONFIG SET appendfsync no         # Maximum performance, OS handles flush

Hybrid Persistence Configuration

Enable RDB+AOF hybrid mode (Redis 4.0+):

CONFIG SET aof-use-rdb-preamble yes

Java Client Implementation (Jedis)

Programmatically manage persistence settings using the Jedis client:

import redis.clients.jedis.Jedis;

public class RedisPersistenceDemo {
    public static void main(String[] args) {
        try (Jedis jedis = new Jedis("localhost", 6379)) {
            // Enable AOF programmatically
            jedis.configSet("appendonly", "yes");
            jedis.configSet("appendfsync", "everysec");
            
            // Trigger asynchronous snapshot
            jedis.bgsave();
            
            // Verify persistence configuration
            System.out.println("appendonly: " + jedis.configGet("appendonly"));
            System.out.println("appendfsync: " + jedis.configGet("appendfsync"));
        }
    }
}

Monitoring Persistence Status

Check persistence metrics using the INFO command:

redis-cli INFO persistence

Key metrics to watch:

  • rdb_last_save_time: Timestamp of last successful RDB save
  • aof_enabled: Whether AOF is active (1=yes, 0=no)
  • aof_current_size: Current AOF file size in bytes

Summary

  • RDB persistence creates binary point-in-time snapshots using a forked child process (bgsave), providing compact files and fast restarts but risking data loss between snapshots.
  • AOF persistence logs every write command to appendonly.aof with configurable fsync policies (always, everysec, no), offering better durability at the cost of file size and restart speed.
  • Hybrid mode (Redis 4.0+) combines RDB and AOF by prepending an RDB snapshot to the AOF file, balancing fast recovery with minimal data loss.
  • Configuration is managed through redis.conf directives or runtime CONFIG SET commands, with the implementation details documented in docs/database/redis/redis-persistence.md.

Frequently Asked Questions

What is the difference between RDB and AOF in Redis?

RDB creates binary snapshots of the entire dataset at intervals, producing compact files ideal for backups but potentially losing data since the last snapshot. AOF logs every write command as text, allowing for finer-grained recovery (typically 1 second of loss with everysec) but resulting in larger files and slower restarts due to command replay.

Does RDB block the Redis main thread?

The SAVE command blocks the main thread until the snapshot completes, while BGSAVE forks a child process to perform the write asynchronously. As implemented in the Redis source and documented in docs/database/redis/redis-common-blocking-problems-summary.md, BGSAVE is the preferred production approach to avoid latency spikes.

How often does Redis sync AOF to disk?

The sync frequency depends on the appendfsync setting: always syncs on every write, everysec syncs once per second (default), and no leaves the timing to the operating system (typically ~30 seconds). The everysec policy offers the best balance, risking at most 1 second of data loss while maintaining good performance.

Can I use both RDB and AOF together?

Yes, Redis supports running both mechanisms simultaneously, and since version 4.0 offers a hybrid mode (aof-use-rdb-preamble yes) that embeds an RDB snapshot at the beginning of the AOF file. This configuration—recommended in the JavaGuide documentation—provides the fast restart benefits of RDB with the durability guarantees of AOF.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →