0
0
RedisHow-ToBeginner · 3 min read

How to Use BGSAVE in Redis for Background Saving

Use the BGSAVE command in Redis to create a snapshot of the database asynchronously in the background. This command saves the current state to disk without blocking Redis from serving requests.
📐

Syntax

The BGSAVE command has a simple syntax with no arguments. It triggers Redis to save the dataset to disk in the background.

  • BGSAVE: Starts an asynchronous save operation.
redis
BGSAVE
💻

Example

This example shows how to run BGSAVE in the Redis CLI and the expected output. It demonstrates saving the database snapshot without blocking other commands.

redis
127.0.0.1:6379> BGSAVE
OK
Output
OK
⚠️

Common Pitfalls

Common mistakes when using BGSAVE include:

  • Running BGSAVE when a background save is already in progress, which will cause Redis to return an error.
  • Expecting immediate completion; BGSAVE runs asynchronously, so the save happens in the background.
  • Not monitoring the Redis logs or LASTSAVE command to confirm the save completed successfully.

To check if a save is in progress, use INFO Persistence and look for rdb_bgsave_in_progress.

redis
127.0.0.1:6379> BGSAVE
(error) Background save already in progress

# Correct approach: wait for the current save to finish before running BGSAVE again
Output
(error) Background save already in progress
📊

Quick Reference

CommandDescription
BGSAVEStarts an asynchronous save of the dataset to disk.
SAVEBlocks Redis and saves the dataset synchronously.
LASTSAVEReturns the Unix timestamp of the last successful save.
INFO PersistenceShows persistence-related information including save status.

Key Takeaways

Use BGSAVE to save Redis data asynchronously without blocking clients.
Avoid running BGSAVE if a background save is already in progress to prevent errors.
Check LASTSAVE or Redis logs to confirm the snapshot was saved successfully.
Use INFO Persistence to monitor the status of background saves.
BGSAVE is preferred over SAVE for non-blocking persistence.