This is the 25th day of my participation in Gwen Challenge

Redis persists in another way: RDB snapshots

RDB

RDB snapshot: a snapshot (in binary form) of memory data generated at a certain point in time is written to disk.

AOF is a recording operation and RDB is a snapshot of the data at a point in time. Therefore, during data recovery, you only need to read the RDB file directly into the memory to complete fast recovery

triggering

Manual trigger

save

  • Sending the save command to request persistence blocks Redis Server from processing other requests until data synchronization is complete

bgsave

  • When the BGSave command is sent to persist, the main Redis process forks a child process, asynchronously saves data to an RDB file, replaces the original file, and notifies the main process that synchronization is complete

Automatic trigger

Save m n in the configuration indicates that bgSave is automatically triggered when the data set is modified for n times within m seconds

RDB pros and cons

Advantages:

  • RDB files are small and suitable for periodic backup for disaster recovery
  • RDB files directly store in-memory data, while AOF files store a command, so Redis loads RDB files faster than AOF files

Disadvantages:

  • RDB persistence is not capable of real-time/second persistence. Real-time persistence requires full memory flushing to disk, which is costly
  • RDB files are binary files. Cross-version compatibility is not supported if Redis upgrades have multiple versions of RDB files

thinking

1. Does RDB flash block the thread?

First, Redis is single-threaded for processing data. You can learn the trigger mechanism of RDB in manual and automatic ways. In manual start, run the save and BGsave commands.

  • The save command blocks the main thread until synchronization is complete, which blocks the main thread
  • Bgsave allows the main thread to be forked by a child thread without blocking the main thread (default)

2. Can the RDB data be modified when creating a snapshot?

Imagine a scenario in which data is modified or cannot be modified during snapshot execution

  • If a write can be performed, meaning that Redis can still handle writes, it is possible that the data in the snapshot being performed has been modified
  • If you can’t write, it means that all Redis writes will have to wait until the snapshot is complete, blocking the main thread

How to solve it?

This can be resolved using BGSave

  • The main thread performs reads, and the main thread and bgSave child processes are not affected
  • When the main thread performs a write operation, a copy of the modified data is made, and the bgSave child writes the copy to the RDB file, while the main thread can still modify the original data