Database Advanced

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.

👨‍💻
Senior Systems Architect • Verified in Staging Labs

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:

  1. Redis maxmemory Limit Reached: This is the most direct cause. Redis is configured with a maxmemory directive in its redis.conf file, or it's implicitly limited by system memory. When the amount of data stored (used_memory) exceeds this limit, and the maxmemory-policy is set to noeviction (the default), Redis will prevent any further write operations to protect data integrity.

  2. Ineffective maxmemory-policy: The maxmemory-policy dictates how Redis behaves when maxmemory is reached. If set to noeviction, 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.

  3. 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.

  4. Memory Fragmentation in Redis: Redis might report used_memory (data size) below maxmemory, but used_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.

  5. 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.

  6. 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.

  1. Connect to Redis CLI:

    redis-cli
    
  2. Get Memory Information:

    info memory
    

    Look 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 of used_memory_rss to used_memory. A value > 1.5 might indicate significant fragmentation.
  3. Check maxmemory and maxmemory-policy in configuration: Exit redis-cli (Ctrl+C) and check the redis.conf file. The default location on Ubuntu is /etc/redis/redis.conf.

    sudo grep -E "maxmemory|maxmemory-policy|activedefrag" /etc/redis/redis.conf
    

    This will show you the active maxmemory and maxmemory-policy settings. If maxmemory is commented out or set to 0, 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.

  1. Edit Redis Configuration: Open the Redis configuration file:

    sudo nano /etc/redis/redis.conf
    

    Locate the maxmemory directive. 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 maxmemory to 3gb.

    # Set the maxmemory limit (e.g., 3 gigabytes)
    maxmemory 3gb
    
  2. Restart Redis:

    sudo systemctl restart redis-server
    

Increasing maxmemory without 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.

  1. Understand Eviction Policies:

    • noeviction: (Default) Returns OOM error on writes when maxmemory is 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.
  2. Edit Redis Configuration: Open /etc/redis/redis.conf again:

    sudo nano /etc/redis/redis.conf
    

    Locate or add the maxmemory-policy directive. For most caching scenarios, allkeys-lru or allkeys-lfu are excellent choices.

    # Set the maxmemory eviction policy
    maxmemory-policy allkeys-lfu
    
  3. Restart Redis:

    sudo systemctl restart redis-server
    

Choosing the correct maxmemory-policy is critical for your application's behavior. noeviction will 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.

  1. Enable Active Defragmentation: Open /etc/redis/redis.conf:

    sudo nano /etc/redis/redis.conf
    

    Add 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 75
    
  2. Restart 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-min and active-defrag-cycle-max settings 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.

  1. Shutdown WSL2: First, ensure all WSL2 instances are shut down from Windows PowerShell or Command Prompt:

    wsl --shutdown
    
  2. Create/Edit .wslconfig File: 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)
    
  3. Configure .wslconfig: Add or modify the following lines in .wslconfig. Adjust memory and processors based 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.
    
  4. Restart WSL2: Open a new WSL2 terminal (e.g., launch Ubuntu). This will automatically start the WSL2 VM with the new settings.

  5. Verify WSL2 Memory: Inside your Ubuntu WSL2 terminal, run:

    free -h
    

    Confirm that total memory reflects your .wslconfig changes.

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.

  1. 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 100 to quickly inspect key prefixes and identify potential problem areas.
  2. Analyze Key Sizes: For specific keys, you can check their memory usage:

    redis-cli debug object <key_name>
    

    Look at serializedlength to understand the key's size. If you have many large keys, this could be the culprit.

  3. 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.

  1. Redis Monitoring:

    • Use redis-cli info memory regularly 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 monitor command provides a real-time stream of commands processed by Redis, which can help pinpoint application actions leading to memory spikes.
  2. WSL2 System Monitoring:

    • Inside WSL2, use htop or top to monitor CPU, memory, and process usage.
    • Consider tools like dstat or netdata for more comprehensive resource utilization monitoring within WSL2.

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.

👨‍💻

Johnathon Wheeler

Senior Systems Architect & DevOps Engineer • Austin, TX

Connect on LinkedIn

Johnathon has over 16 years of hands-on experience designing, debugging, and scaling Linux web hosting stacks, container clusters, and high-availability database architectures. Every guide on ButItWorkedLocal is independently tested against Debian 12, Ubuntu 24.04/22.04 LTS, Rocky Linux, and Docker environments to guarantee reproducibility in production.

🛡️

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.