
How to Back Up and Restore Your Redis Data on Ubuntu 24
Redis is a powerful in-memory data structure store that serves as a database, cache, and message broker for countless applications worldwide. Whether you’re running a small web app or managing enterprise-level infrastructure, your Redis data is critical and needs proper backup and restore procedures. This guide walks you through the complete process of backing up and restoring Redis data on Ubuntu 24, covering both the default RDB snapshots and AOF (Append-Only File) methods, along with automation strategies and recovery scenarios you’ll likely encounter in production environments.
Understanding Redis Persistence Mechanisms
Redis offers two primary persistence methods that determine how your data gets saved to disk. The RDB (Redis Database) method creates point-in-time snapshots of your dataset at specified intervals, while AOF (Append-Only File) logs every write operation received by the server. Each approach has distinct advantages depending on your use case.
RDB snapshots are compact, fast to load, and perfect for backup purposes, but you might lose data between snapshots if Redis crashes. AOF provides better durability since it logs every write operation, but files tend to be larger and recovery can be slower. Many production setups use both methods simultaneously for maximum data protection.
Feature | RDB Snapshots | AOF Logging |
---|---|---|
File Size | Compact | Larger |
Recovery Speed | Fast | Slower |
Data Loss Risk | Up to snapshot interval | Minimal (1 second max) |
CPU Impact | Low (periodic) | Higher (continuous) |
Backup Suitability | Excellent | Good |
Setting Up Redis Persistence Configuration
Before diving into backup procedures, you need to configure Redis persistence properly. The default Redis configuration on Ubuntu 24 enables RDB snapshots, but you should customize these settings based on your requirements.
First, locate and edit your Redis configuration file:
sudo nano /etc/redis/redis.conf
For RDB configuration, adjust these parameters:
# Save snapshots based on time and number of changes
save 900 1 # Save if at least 1 key changed in 900 seconds
save 300 10 # Save if at least 10 keys changed in 300 seconds
save 60 10000 # Save if at least 10000 keys changed in 60 seconds
# Snapshot filename and directory
dbfilename dump.rdb
dir /var/lib/redis
# Compression and checksum
rdbcompression yes
rdbchecksum yes
For AOF configuration, enable and configure these options:
# Enable AOF persistence
appendonly yes
appendfilename "appendonly.aof"
# Sync policy (everysec recommended for balance)
appendfsync everysec
# AOF rewrite configuration
auto-aof-rewrite-percentage 100
auto-aof-rewrite-min-size 64mb
After making changes, restart Redis to apply the new configuration:
sudo systemctl restart redis-server
sudo systemctl status redis-server
Manual Backup Procedures
Manual backups are essential for maintenance windows, major deployments, or when you need guaranteed point-in-time recovery. Redis provides several approaches for creating manual backups without stopping the service.
The BGSAVE
command creates an RDB snapshot in the background without blocking client operations:
# Connect to Redis and trigger background save
redis-cli
127.0.0.1:6379> BGSAVE
Background saving started
# Check if background save completed
127.0.0.1:6379> LASTSAVE
(integer) 1703425234
For immediate snapshots that block operations (use carefully in production), use SAVE
:
127.0.0.1:6379> SAVE
OK
To copy backup files safely while Redis is running, use this approach:
# Create backup directory
sudo mkdir -p /backup/redis/$(date +%Y%m%d_%H%M%S)
BACKUP_DIR="/backup/redis/$(date +%Y%m%d_%H%M%S)"
# Copy RDB file
sudo cp /var/lib/redis/dump.rdb $BACKUP_DIR/
# Copy AOF file if enabled
sudo cp /var/lib/redis/appendonly.aof $BACKUP_DIR/
# Create compressed archive
sudo tar -czf $BACKUP_DIR.tar.gz -C $BACKUP_DIR .
sudo rm -rf $BACKUP_DIR
Automated Backup Scripts
Production environments require automated backup solutions that run consistently without manual intervention. Here’s a comprehensive backup script that handles both RDB and AOF files with rotation and error handling:
#!/bin/bash
# Redis Backup Script for Ubuntu 24
# Save as /usr/local/bin/redis-backup.sh
set -e
# Configuration
REDIS_DATA_DIR="/var/lib/redis"
BACKUP_BASE_DIR="/backup/redis"
RETENTION_DAYS=7
LOG_FILE="/var/log/redis-backup.log"
REDIS_CLI="/usr/bin/redis-cli"
# Create timestamp
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
BACKUP_DIR="$BACKUP_BASE_DIR/$TIMESTAMP"
# Logging function
log_message() {
echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" | tee -a $LOG_FILE
}
# Create backup directory
mkdir -p $BACKUP_DIR
log_message "Starting Redis backup to $BACKUP_DIR"
# Trigger background save
$REDIS_CLI BGSAVE >/dev/null
# Wait for background save to complete
log_message "Waiting for background save to complete..."
while [ $($REDIS_CLI LASTSAVE) -eq $($REDIS_CLI LASTSAVE) ]; do
sleep 1
done
# Copy files
if [ -f "$REDIS_DATA_DIR/dump.rdb" ]; then
cp "$REDIS_DATA_DIR/dump.rdb" "$BACKUP_DIR/"
log_message "RDB file backed up successfully"
fi
if [ -f "$REDIS_DATA_DIR/appendonly.aof" ]; then
cp "$REDIS_DATA_DIR/appendonly.aof" "$BACKUP_DIR/"
log_message "AOF file backed up successfully"
fi
# Create compressed archive
tar -czf "$BACKUP_DIR.tar.gz" -C "$BACKUP_DIR" .
rm -rf "$BACKUP_DIR"
# Cleanup old backups
find $BACKUP_BASE_DIR -name "*.tar.gz" -mtime +$RETENTION_DAYS -delete
log_message "Backup completed and old backups cleaned up"
# Verify backup integrity
if tar -tzf "$BACKUP_DIR.tar.gz" >/dev/null 2>&1; then
log_message "Backup archive integrity verified"
else
log_message "ERROR: Backup archive appears corrupted"
exit 1
fi
Make the script executable and set up proper permissions:
sudo chmod +x /usr/local/bin/redis-backup.sh
sudo chown root:root /usr/local/bin/redis-backup.sh
Schedule automated backups using cron. Edit the crontab:
sudo crontab -e
Add these entries for different backup frequencies:
# Daily backups at 2 AM
0 2 * * * /usr/local/bin/redis-backup.sh
# Hourly backups during business hours
0 9-17 * * 1-5 /usr/local/bin/redis-backup.sh
Data Restoration Procedures
Restoring Redis data depends on your persistence configuration and the type of backup files available. The process involves stopping Redis, replacing data files, and restarting the service with proper verification steps.
For RDB file restoration:
# Stop Redis service
sudo systemctl stop redis-server
# Backup current data (safety measure)
sudo cp /var/lib/redis/dump.rdb /var/lib/redis/dump.rdb.backup.$(date +%s)
# Extract and restore backup
cd /backup/redis
sudo tar -xzf 20231224_140000.tar.gz
sudo cp dump.rdb /var/lib/redis/
sudo chown redis:redis /var/lib/redis/dump.rdb
sudo chmod 660 /var/lib/redis/dump.rdb
# Start Redis and verify
sudo systemctl start redis-server
redis-cli ping
For AOF file restoration when AOF is enabled:
# Stop Redis service
sudo systemctl stop redis-server
# Restore AOF file
sudo cp appendonly.aof /var/lib/redis/
sudo chown redis:redis /var/lib/redis/appendonly.aof
sudo chmod 660 /var/lib/redis/appendonly.aof
# Start Redis service
sudo systemctl start redis-server
# Verify data integrity
redis-cli
127.0.0.1:6379> INFO persistence
127.0.0.1:6379> DBSIZE
If you encounter AOF corruption, Redis provides a repair tool:
# Check AOF file for corruption
redis-check-aof /var/lib/redis/appendonly.aof
# Repair corrupted AOF file
redis-check-aof --fix /var/lib/redis/appendonly.aof
Real-World Disaster Recovery Scenarios
Different failure scenarios require specific recovery approaches. Here are common situations you’ll encounter and their solutions:
Scenario 1: Complete server failure with recent backups
When migrating to a new server, such as upgrading to a more powerful VPS or dedicated server, follow this process:
# On new Ubuntu 24 server, install Redis
sudo apt update && sudo apt install redis-server
# Stop Redis service
sudo systemctl stop redis-server
# Transfer backup from old server
scp user@old-server:/backup/redis/latest.tar.gz /tmp/
cd /tmp && tar -xzf latest.tar.gz
# Restore data files
sudo cp dump.rdb /var/lib/redis/
sudo cp appendonly.aof /var/lib/redis/
sudo chown redis:redis /var/lib/redis/*
sudo chmod 660 /var/lib/redis/dump.rdb /var/lib/redis/appendonly.aof
# Configure Redis with previous settings
sudo cp redis.conf /etc/redis/redis.conf
# Start and verify
sudo systemctl start redis-server
redis-cli INFO keyspace
Scenario 2: Partial data corruption with mixed file states
Sometimes only one persistence file is corrupted while the other remains intact:
# Check file integrity
redis-check-rdb /var/lib/redis/dump.rdb
redis-check-aof /var/lib/redis/appendonly.aof
# If RDB is good but AOF is corrupted:
sudo systemctl stop redis-server
sudo mv /var/lib/redis/appendonly.aof /var/lib/redis/appendonly.aof.corrupt
sudo systemctl start redis-server
# Redis will start from RDB, then recreate AOF
redis-cli BGREWRITEAOF
Scenario 3: Point-in-time recovery to specific backup
When you need to restore to a specific point in time:
# List available backups
ls -la /backup/redis/
# Choose specific backup timestamp
RESTORE_DATE="20231220_153000"
cd /backup/redis
tar -xzf ${RESTORE_DATE}.tar.gz
# Create verification script
cat > verify_restore.sh << 'EOF'
#!/bin/bash
echo "Checking restored data..."
KEYS=$(redis-cli DBSIZE)
echo "Total keys: $KEYS"
redis-cli INFO memory | grep used_memory_human
redis-cli INFO persistence | grep rdb_last_save_time
EOF
chmod +x verify_restore.sh
Best Practices and Performance Optimization
Implementing robust Redis backup strategies requires attention to performance impact, storage efficiency, and operational procedures. Here are production-tested recommendations:
- Use BGSAVE instead of SAVE - Background saves don't block client operations, making them suitable for production environments
- Schedule backups during low-traffic periods - Even background operations consume I/O resources
- Monitor backup file sizes - Implement alerts when backup sizes change dramatically, indicating potential issues
- Test restore procedures regularly - Schedule monthly restore tests on non-production systems
- Store backups on separate storage - Use different physical devices or cloud storage for disaster recovery
- Implement backup verification - Always verify backup integrity after creation
Backup Frequency | Use Case | Storage Impact | Recovery Point |
---|---|---|---|
Every 15 minutes | Critical financial data | High | 15 minutes max loss |
Hourly | E-commerce sessions | Medium | 1 hour max loss |
Every 6 hours | Analytics cache | Low | 6 hours max loss |
Daily | Development environments | Very low | 24 hours max loss |
Common Issues and Troubleshooting
Redis backup and restore operations can encounter various issues. Here are the most common problems and their solutions:
Permission denied errors during restore:
# Fix ownership and permissions
sudo chown redis:redis /var/lib/redis/*
sudo chmod 660 /var/lib/redis/dump.rdb
sudo chmod 660 /var/lib/redis/appendonly.aof
# Check Redis user can access directory
sudo -u redis ls -la /var/lib/redis/
Out of memory errors during large restores:
# Check available memory
free -h
# Temporarily increase swap if needed
sudo fallocate -l 2G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
# Monitor memory usage during restore
watch -n 1 'free -h && redis-cli INFO memory | grep used_memory_human'
Redis fails to start after restore:
# Check Redis logs for specific errors
sudo journalctl -u redis-server -f
# Common fixes:
# 1. Verify file permissions
sudo ls -la /var/lib/redis/
# 2. Check disk space
df -h /var/lib/redis/
# 3. Validate configuration syntax
redis-server /etc/redis/redis.conf --test-memory 1024
AOF file corruption after system crash:
# Redis provides detailed repair information
redis-check-aof /var/lib/redis/appendonly.aof
# Repair with detailed output
redis-check-aof --fix /var/lib/redis/appendonly.aof
# If repair fails, fall back to RDB
sudo mv /var/lib/redis/appendonly.aof /var/lib/redis/appendonly.aof.corrupt
sudo systemctl restart redis-server
For complex deployment scenarios involving multiple Redis instances or cluster configurations, consider using specialized tools like Redis Sentinel for high availability or Redis Cluster for distributed setups. These tools provide additional backup and failover capabilities beyond single-instance configurations.
Remember that backup strategies should align with your application's RTO (Recovery Time Objective) and RPO (Recovery Point Objective) requirements. Critical applications may require more frequent backups and faster restore procedures, while development environments can tolerate longer recovery times with less frequent backups.

This article incorporates information and material from various online sources. We acknowledge and appreciate the work of all original authors, publishers, and websites. While every effort has been made to appropriately credit the source material, any unintentional oversight or omission does not constitute a copyright infringement. All trademarks, logos, and images mentioned are the property of their respective owners. If you believe that any content used in this article infringes upon your copyright, please contact us immediately for review and prompt action.
This article is intended for informational and educational purposes only and does not infringe on the rights of the copyright owners. If any copyrighted material has been used without proper credit or in violation of copyright laws, it is unintentional and we will rectify it promptly upon notification. Please note that the republishing, redistribution, or reproduction of part or all of the contents in any form is prohibited without express written permission from the author and website owner. For permissions or further inquiries, please contact us.