Troubleshooting Redis OOM: ‘OOM command not allowed when used memory limit reached’ on WSL2 Ubuntu
Fix Redis OOM errors on WSL2 Ubuntu when memory limits are hit. A deep dive into configuration, WSL2 settings, and application optimization for Redis performance.
Fix Redis OOM errors on WSL2 Ubuntu when memory limits are hit. A deep dive into configuration, WSL2 settings, and application optimization for Redis performance.
Introduction
As an experienced Systems Administrator and DevOps engineer, encountering OOM command not allowed errors in Redis is a clear indicator that your Redis instance has hit its configured memory ceiling. When this occurs within a Windows Subsystem for Linux 2 (WSL2) Ubuntu environment, it adds an additional layer of complexity, as you're dealing with a virtualized Linux kernel managed by Windows.
This guide will walk you through diagnosing and resolving the "OOM command not allowed when used memory limit reached" error, specifically tailored for Redis running on Ubuntu within WSL2. You'll learn how to inspect Redis configuration, understand WSL2's resource allocation, and optimize both to ensure your Redis server operates stably and efficiently. When this error manifests, applications relying on Redis for caching, session storage, or data persistence will typically experience failures, often presenting as "connection refused," "read timeout," or generic server errors in your application logs.
Symptom & Error Signature
When Redis reaches its maxmemory limit and is configured with the default noeviction policy, it will reject all write commands, returning the OOM command not allowed error. Your application will typically report this error, and Redis logs will explicitly show the condition.
Typical Redis Log Output:
9876:M 24 Aug 2026 10:30:00.123 # WARNING: OOM command not allowed when used memory > 'maxmemory'
9876:M 24 Aug 2026 10:30:00.124 # Redis is running in a memory-limited environment. To avoid OOM errors, increase maxmemory, change your maxmemory-policy, or remove some keys.
Application Error Examples (depending on language/client):
PHP (Predis):
Fatal error: Uncaught PredisConnectionConnectionException: OOM command not allowed when used memory > 'maxmemory' [tcp://127.0.0.1:6379] in /path/to/vendor/predis/predis/src/Connection/AbstractConnection.php:155
Stack trace:
#0 /path/to/vendor/predis/predis/src/Client.php(336): PredisConnectionAbstractConnection->executeCommand(Object(PredisCommandServerFlushall))
#1 /path/to/app/index.php(10): PredisClient->__call('flushall', Array)
#2 {main}
thrown in /path/to/vendor/predis/predis/src/Connection/AbstractConnection.php on line 155
Python (redis-py):
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
redis.exceptions.OutOfMemoryError: OOM command not allowed when used memory > 'maxmemory'
Root Cause Analysis
The "Redis OOM command not allowed" error on WSL2 Ubuntu typically stems from one or a combination of the following factors:
Redis
maxmemoryLimit Reached: This is the most direct cause. Redis is configured with amaxmemorydirective in itsredis.conffile, or it's implicitly limited by system memory. When the amount of data stored (used_memory) exceeds this limit, and themaxmemory-policyis set tonoeviction(the default), Redis will prevent any further write operations to protect data integrity.Ineffective
maxmemory-policy: Themaxmemory-policydictates how Redis behaves whenmaxmemoryis reached. If set tonoeviction, Redis will simply block writes. Other policies (e.g.,allkeys-lru,volatile-lfu) instruct Redis to evict keys based on specific algorithms, allowing new data to be written.WSL2 Memory Allocation Constraints: WSL2 instances run as lightweight virtual machines with their own allocated memory pool. By default, WSL2 might allocate only a percentage of your total host RAM (e.g., 50-80% or a fixed amount like 4GB for systems with 8GB+ RAM), which can be further restricted if other Windows applications consume significant memory. Your Redis instance is confined to this WSL2 pool, not the total system RAM.
Memory Fragmentation in Redis: Redis might report
used_memory(data size) belowmaxmemory, butused_memory_rss(resident set size, actual physical memory consumed) could be much higher due to fragmentation. This happens when Redis frees memory, but the underlying allocator (jemalloc by default) doesn't release it back to the OS immediately, or the freed chunks are too small and scattered to be reused efficiently.Application-Level Memory Spikes: The application interacting with Redis might be storing excessively large keys, complex data structures, or an unexpectedly high volume of data without proper eviction or TTL (Time To Live) mechanisms. This can lead to rapid memory consumption.
Other Processes within WSL2: Other services or applications running inside your WSL2 Ubuntu instance (e.g., databases, web servers, build tools) could be consuming significant memory, reducing the available pool for Redis and indirectly causing it to hit its limits faster.
Step-by-Step Resolution
Follow these steps to diagnose and resolve the Redis OOM error on your WSL2 Ubuntu environment.
1. Check Current Redis Memory Usage and Configuration
First, connect to your Redis instance and gather vital statistics.
Connect to Redis CLI:
redis-cliGet Memory Information:
info memoryLook for these key metrics:
used_memory_human: The amount of memory consumed by Redis data, human-readable.used_memory_rss_human: The actual physical memory consumed by Redis, including fragmentation overhead.maxmemory_human: The configured maximum memory limit.mem_fragmentation_ratio: Ratio ofused_memory_rsstoused_memory. A value > 1.5 might indicate significant fragmentation.
Check
maxmemoryandmaxmemory-policyin configuration: Exitredis-cli(Ctrl+C) and check theredis.conffile. The default location on Ubuntu is/etc/redis/redis.conf.sudo grep -E "maxmemory|maxmemory-policy|activedefrag" /etc/redis/redis.confThis will show you the active
maxmemoryandmaxmemory-policysettings. Ifmaxmemoryis commented out or set to0, Redis will attempt to use all available system memory.
2. Adjust Redis maxmemory Limit
If info memory shows used_memory_human is close to or equal to maxmemory_human, you need to either increase the maxmemory limit or enable an eviction policy.
Edit Redis Configuration: Open the Redis configuration file:
sudo nano /etc/redis/redis.confLocate the
maxmemorydirective. If it's commented out or set too low, adjust it. A good starting point is to allocate 70-80% of your WSL2 instance's available RAM to Redis.Example: If your WSL2 instance has 4GB of RAM, set
maxmemoryto3gb.# Set the maxmemory limit (e.g., 3 gigabytes) maxmemory 3gbRestart Redis:
sudo systemctl restart redis-server
Increasing
maxmemorywithout considering the total available RAM for your WSL2 instance or your host system can lead to severe performance degradation and instability for both your WSL2 environment and Windows host. Always monitor overall system resources.
3. Configure Redis maxmemory-policy
If you're using Redis primarily as a cache, simply increasing maxmemory might only postpone the problem. Implementing an effective eviction policy is crucial.
Understand Eviction Policies:
noeviction: (Default) Returns OOM error on writes whenmaxmemoryis reached.allkeys-lru: Evicts least recently used (LRU) keys among all keys. Best for generic caching.volatile-lru: Evicts LRU keys only among keys with an expire set. Useful if some keys must persist.allkeys-lfu: Evicts least frequently used (LFU) keys among all keys. Generally more effective than LRU for caching.volatile-lfu: Evicts LFU keys only among keys with an expire set.allkeys-random: Evicts random keys among all keys.volatile-random: Evicts random keys only among keys with an expire set.volatile-ttl: Evicts keys with the shortest remaining TTL.
Edit Redis Configuration: Open
/etc/redis/redis.confagain:sudo nano /etc/redis/redis.confLocate or add the
maxmemory-policydirective. For most caching scenarios,allkeys-lruorallkeys-lfuare excellent choices.# Set the maxmemory eviction policy maxmemory-policy allkeys-lfuRestart Redis:
sudo systemctl restart redis-server
Choosing the correct
maxmemory-policyis critical for your application's behavior.noevictionwill halt all writes, which might be desired for persistent data stores, but not for volatile caches. For caching, an eviction policy is almost always necessary to prevent OOM errors.
4. Optimize Redis Memory Fragmentation
If mem_fragmentation_ratio from info memory is consistently high (e.g., > 1.5), Redis is using more physical memory than necessary due to fragmentation. Redis 4.0+ introduced active defragmentation.
Enable Active Defragmentation: Open
/etc/redis/redis.conf:sudo nano /etc/redis/redis.confAdd or uncomment the following directives:
# Enable active defragmentation activedefrag yes # Minimum amount of fragmented memory to start defrag (bytes) active-defrag-ignore-bytes 100mb # Minimum percentage of fragmentation to start defrag active-defrag-threshold-lower 10 # Maximum percentage of fragmentation to continue defrag active-defrag-threshold-upper 100 # Minimum time for defrag to run (ms/sec) - default 1ms active-defrag-cycle-min 5 # Maximum time for defrag to run (ms/sec) - default 25ms active-defrag-cycle-max 75Restart Redis:
sudo systemctl restart redis-server
Active defragmentation runs in the background and can introduce minor latency spikes during compaction. Monitor your Redis latency metrics after enabling it. The
active-defrag-cycle-minandactive-defrag-cycle-maxsettings control how aggressive Redis is with defragmentation.
5. Increase WSL2 Memory Allocation
If your WSL2 instance itself is running out of memory (check with free -h inside WSL2), you need to allocate more resources to it from Windows.
Shutdown WSL2: First, ensure all WSL2 instances are shut down from Windows PowerShell or Command Prompt:
wsl --shutdownCreate/Edit
.wslconfigFile: Navigate to your Windows user profile directory (C:Users<YourUser>) and create (or edit if it exists) a file named.wslconfig.# Open File Explorer, go to C:Users<YourUser> # Create or edit .wslconfig (ensure it's not .wslconfig.txt)Configure
.wslconfig: Add or modify the following lines in.wslconfig. Adjustmemoryandprocessorsbased on your host machine's resources and your needs.[wsl2] # Limits the VM memory to 4GB. Omit to use 50% of your total RAM. memory=4GB # Sets the number of virtual processors to 2. processors=2 # Do not create a swap file. (Set to 0 if you have ample RAM) swap=0 # Sets the swap file size to 8GB. (Only relevant if swap is not 0) # swapfile=C:tempwsl-swap.vhdx # Forces all installed distributions to use the WSL 2 architecture. # If not specified, distributions will use the default architecture. # Forcing all to WSL2 is often desired for performance. # kernelCommandLine = "mem=4G" # Alternative for memory, but 'memory=' is preferred.Restart WSL2: Open a new WSL2 terminal (e.g., launch Ubuntu). This will automatically start the WSL2 VM with the new settings.
Verify WSL2 Memory: Inside your Ubuntu WSL2 terminal, run:
free -hConfirm that
totalmemory reflects your.wslconfigchanges.
Over-allocating memory to WSL2 can starve your Windows host system, leading to overall slowdowns or unresponsiveness on your primary desktop. Aim for a balance, typically leaving at least 4-8GB for Windows itself, depending on your total RAM.
6. Identify and Optimize Application Memory Usage
Sometimes the issue isn't Redis or WSL2, but how your application interacts with Redis.
Monitor Application Data:
- Are you storing large objects in Redis? Consider serializing only necessary data or breaking down large objects.
- Are you inadvertently creating a huge number of keys?
- Are keys being set with appropriate TTLs (Time To Live) to expire gracefully?
- Use
redis-cli --scan | head -n 100to quickly inspect key prefixes and identify potential problem areas.
Analyze Key Sizes: For specific keys, you can check their memory usage:
redis-cli debug object <key_name>Look at
serializedlengthto understand the key's size. If you have many large keys, this could be the culprit.Implement Efficient Data Structures: Redis offers various data structures (Strings, Hashes, Lists, Sets, Sorted Sets). Using the most appropriate and memory-efficient structure for your data can significantly reduce memory footprint. For instance, using Redis Hashes for related fields of an object is often more memory-efficient than individual String keys for each field.
7. Monitor Redis and System Resources Continuously
Proactive monitoring can help you detect memory pressure before it leads to OOM errors.
Redis Monitoring:
- Use
redis-cli info memoryregularly or script it. - Set up monitoring tools like Prometheus and Grafana to track Redis metrics (used memory, fragmentation ratio, keyspace, hit rate, etc.).
- The
redis-cli monitorcommand provides a real-time stream of commands processed by Redis, which can help pinpoint application actions leading to memory spikes.
- Use
WSL2 System Monitoring:
- Inside WSL2, use
htoportopto monitor CPU, memory, and process usage. - Consider tools like
dstatornetdatafor more comprehensive resource utilization monitoring within WSL2.
- Inside WSL2, use
By systematically applying these steps, you can effectively resolve the "Redis OOM command not allowed" error on your WSL2 Ubuntu environment and establish a more robust and performant Redis setup.
Our Production Verification Guarantee
Encountering a bug not covered here or running a non-standard kernel configuration? Our solutions are continually refined against real production incidents. Submit an environment trace for our editorial team to replicate.