The ProblemIf your Redis logs are screaming Can't save in background: fork: Cannot allocate memory, you are likely facing a common Linux memory management hurdle. This error usually triggers during a BGSAVE or BGREWRITEAOF command. When it occurs, Redis stops creating data snapshots. This is a major risk. If your server crashes now, you could lose every write operation performed since the last successful save.
Root CauseRedis handles data persistence by calling fork() to create a child process. This child process uses Copy-on-Write (COW) to share memory with the parent. While this is efficient, the Linux kernel is often over-protective. By default, the kernel estimates whether it has enough RAM to handle a worst-case scenario where the child process eventually needs as much memory as the parent.
Imagine you have a 16GB RAM server. If Redis is using 9GB, the kernel might reject the fork() because it fears the total usage could hit 18GB, exceeding your physical RAM. It blocks the request to prevent a system-wide crash, even if the child process would only actually need a few hundred megabytes of incremental memory.
Step-by-Step Fix### Step 1: Inspect Current Overcommit SettingsStart by checking how your Linux host currently handles memory overcommitting. Run this command:
cat /proc/sys/vm/overcommit_memory
A value of 0 means the kernel uses a heuristic approach. This is almost always the culprit for Redis instances using more than 50% of available system memory.
Step 2: Enable Memory Overcommit ImmediatelyYou can fix this instantly without a reboot or service restart. Set the overcommit mode to 1. This tells the kernel to trust the application and always allow memory allocations.
sudo sysctl vm.overcommit_memory=1
Once applied, try forcing a save to verify the fix:
redis-cli BGSAVE
Step 3: Persist the ConfigurationThe sysctl command is temporary and resets after a reboot. To make this change permanent, you must update the system configuration file.
- Open the config file:
sudo nano /etc/sysctl.conf- Add this line to the end of the file:vm.overcommit_memory = 1- Save and exit (Ctrl+O, Enter, Ctrl+X).- Reload the settings to ensure they are active:sudo sysctl -p### Step 4: Evaluate Swap SpaceIf the error persists even with overcommit set to 1, your system is genuinely out of resources. Check your current usage withfree -m. If your 16GB server shows only 100MB free and 0B swap, you need more breathing room. Adding a 4GB swap file can act as a safety net for these brief spikes during forks.
sudo fallocate -l 4G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
VerificationConfirm the fix by watching the Redis logs in real-time while you trigger a save. Open two terminal windows.
# Terminal 1: Watch the logs
tail -f /var/log/redis/redis-server.log
# Terminal 2: Trigger the save
redis-cli BGSAVE
A successful fix will produce log lines indicating the background saving started and terminated successfully with a specific PID.

