# Redis Out of Memory

Introduction

This article covers troubleshooting steps and solutions for Redis Out of Memory. The error typically occurs in production environments and can cause service disruptions if not addressed promptly.

Symptoms

Common error messages include:

bash
OOM command not allowed when used memory > 'maxmemory'
bash
(error) OOM command not allowed when used memory > 'maxmemory'.
bash
(error) MISCONF Redis is configured to save RDB snapshots, but it's currently not able to persist on disk.

Error Message

bash
OOM command not allowed when used memory > 'maxmemory'

Or:

bash
(error) OOM command not allowed when used memory > 'maxmemory'.

Or:

bash
(error) MISCONF Redis is configured to save RDB snapshots, but it's currently not able to persist on disk.

Common Causes

  1. 1.No maxmemory limit set - Redis using all available RAM
  2. 2.Ineffective eviction policy - Keys not being evicted properly
  3. 3.Large objects - Individual keys with large values
  4. 4.Memory fragmentation - Inefficient memory allocation
  5. 5.Data bloat - Unnecessary or stale data accumulating
  6. 6.Memory leaks - Application not cleaning up keys

Step-by-Step Fix

Step 1: Check Memory Usage

```bash # Connect to Redis redis-cli

# Check memory info 127.0.0.1:6379> INFO memory

# Key metrics: # used_memory: bytes used by Redis # used_memory_human: human-readable format # used_memory_peak: peak memory usage # maxmemory: configured memory limit (0 = unlimited) ```

Step 2: Check Current Configuration

```bash # Check maxmemory setting redis-cli CONFIG GET maxmemory

# Check eviction policy redis-cli CONFIG GET maxmemory-policy

# Check memory stats redis-cli MEMORY STATS ```

Step 3: Analyze Memory Usage by Key

```bash # Sample memory usage of keys redis-cli --bigkeys

# Or sample memory usage redis-cli MEMORY USAGE keyname

# Get all keys and their memory usage (use carefully on large datasets) redis-cli --eval memory_analysis.lua ```

Step 4: Check for Memory Fragmentation

bash
redis-cli INFO memory | grep mem_fragmentation_ratio
# mem_fragmentation_ratio > 1.5 indicates high fragmentation

Step-by-Step Fix

Solution 1: Set Memory Limit

```bash # Set memory limit (e.g., 4GB) redis-cli CONFIG SET maxmemory 4gb

# Or in redis.conf # /etc/redis/redis.conf maxmemory 4gb ```

Solution 2: Configure Eviction Policy

```bash # View current policy redis-cli CONFIG GET maxmemory-policy

# Set eviction policy redis-cli CONFIG SET maxmemory-policy allkeys-lru ```

Available policies:

PolicyDescriptionUse Case
noevictionReturn error when memory limit reachedNever (causes OOM)
allkeys-lruEvict least recently used keysGeneral caching
volatile-lruEvict LRU keys with expire setCache with persistent data
allkeys-lfuEvict least frequently used keysTrending data
volatile-lfuEvict LFU keys with expire setMixed cache/persistent
allkeys-randomEvict random keysUniform access patterns
volatile-randomEvict random keys with expire setMixed usage
volatile-ttlEvict keys with shortest TTLTime-sensitive cache

Solution 3: Analyze and Optimize Data

```bash # Find large keys redis-cli --bigkeys

# Sample specific key sizes redis-cli MEMORY USAGE "user:session:123" redis-cli MEMORY USAGE "cache:homepage" redis-cli STRLEN "large:string:key" redis-cli HLEN "large:hash:key" redis-cli LLEN "large:list:key" redis-cli SCARD "large:set:key" redis-cli ZCARD "large:zset:key" ```

Solution 4: Reduce Memory Usage

Use appropriate data structures:

```bash # Instead of multiple string keys SET user:1:name "John" SET user:1:email "john@example.com" SET user:1:age "30"

# Use a hash (more memory efficient for small objects) HMSET user:1 name "John" email "john@example.com" age "30" ```

Enable memory optimization:

```bash # Use ziplist for small hashes (default in recent Redis) redis-cli CONFIG SET hash-max-ziplist-entries 512 redis-cli CONFIG SET hash-max-ziplist-value 64

# Optimize lists redis-cli CONFIG SET list-max-ziplist-size -2

# Optimize sets redis-cli CONFIG SET set-max-intset-entries 512

# Optimize sorted sets redis-cli CONFIG SET zset-max-ziplist-entries 128 redis-cli CONFIG SET zset-max-ziplist-value 64 ```

Solution 5: Set Expiration on Keys

```bash # Set expiration when creating keys SET cache:user:123 "data" EX 3600 # Expire in 1 hour

# Or use EXPIRE command EXPIRE cache:user:123 3600

# Check TTL TTL cache:user:123

# Set expiration on existing keys in batch (Lua script) EVAL " local keys = redis.call('KEYS', ARGV[1]) for i=1, #keys do redis.call('EXPIRE', keys[i], ARGV[2]) end return #keys " 0 "cache:*" 3600 ```

Solution 6: Clean Up Old Data

```bash # Find keys without expiration redis-cli --scan --pattern "cache:*" | while read key; do ttl=$(redis-cli TTL "$key") if [ "$ttl" -eq -1 ]; then echo "$key has no expiration" fi done

# Delete keys matching pattern (use with caution) redis-cli --scan --pattern "temp:*" | xargs redis-cli DEL

# Or use SCAN for safer deletion redis-cli --eval delete_keys.lua , "temp:*" ```

Lua script for safe deletion:

```lua -- delete_keys.lua local pattern = ARGV[1] local cursor = '0' local count = 0

repeat local reply = redis.call('SCAN', cursor, 'MATCH', pattern, 'COUNT', 1000) cursor = reply[1] local keys = reply[2] if #keys > 0 then redis.call('DEL', unpack(keys)) count = count + #keys end until cursor == '0'

return count ```

Solution 7: Fix Memory Fragmentation

```bash # Check fragmentation ratio redis-cli INFO memory | grep mem_fragmentation_ratio

# If > 1.5, use jemalloc allocator # Check allocator redis-cli MEMORY STATS | grep allocator

# Restart Redis to defragment (causes brief downtime) sudo systemctl restart redis-server

# In Redis 4+, use active defragmentation redis-cli CONFIG SET activedefrag yes

# Or in redis.conf activedefrag yes active-defrag-ignore-bytes 100mb active-defrag-threshold-lower 10 active-defrag-threshold-upper 100 ```

Solution 8: Scale Horizontally

When memory is maxed out, consider Redis Cluster:

bash
# Create Redis cluster
redis-cli --cluster create \
    node1:6379 node2:6379 node3:6379 \
    node4:6379 node5:6379 node6:6379 \
    --cluster-replicas 1

Configuration for Production

```ini # /etc/redis/redis.conf

# Memory Management maxmemory 4gb maxmemory-policy allkeys-lru

# Memory Optimization hash-max-ziplist-entries 512 hash-max-ziplist-value 64 list-max-ziplist-size -2 set-max-intset-entries 512 zset-max-ziplist-entries 128 zset-max-ziplist-value 64

# Active Defragmentation activedefrag yes active-defrag-ignore-bytes 100mb active-defrag-threshold-lower 10 active-defrag-threshold-upper 100

# Save configuration save 900 1 save 300 10 save 60 10000 ```

Monitoring Script

```bash #!/bin/bash # redis_memory_monitor.sh

THRESHOLD=80

# Get memory usage MEMORY_INFO=$(redis-cli INFO memory) USED_MEMORY=$(echo "$MEMORY_INFO" | grep used_memory: | cut -d: -f2 | tr -d '\r') MAX_MEMORY=$(redis-cli CONFIG GET maxmemory | tail -1)

if [ "$MAX_MEMORY" -eq 0 ]; then echo "Warning: maxmemory not set" exit 1 fi

USAGE=$((USED_MEMORY * 100 / MAX_MEMORY))

if [ $USAGE -gt $THRESHOLD ]; then echo "CRITICAL: Redis memory usage at ${USAGE}%" echo "Used: $((USED_MEMORY / 1024 / 1024)) MB / Max: $((MAX_MEMORY / 1024 / 1024)) MB" # Send alert exit 2 fi

echo "OK: Redis memory usage at ${USAGE}%" ```

Prevention

1. Set Appropriate Memory Limit

  • Set maxmemory to 75-80% of available RAM
  • Leave room for OS and other processes

2. Use Consistent Key Expiration

javascript
// Always set TTL for cache keys
await redis.set('cache:user:123', data, 'EX', 3600);

3. Monitor Memory Usage

bash
# Set up monitoring with Redis INFO
redis-cli INFO memory | grep used_memory_human

4. Use Memory-Efficient Structures

  • Use hashes for small objects
  • Use appropriate data types
  • Compress large values before storing
  • [Redis Persistence Failed](./fix-redis-persistence-failed)
  • [Redis Key Eviction Issues](./fix-redis-key-eviction)

Additional Troubleshooting Steps

Step 5: Advanced Diagnostics ```bash # Deep diagnostic analysis redis diagnostic analyze --full

# Check system logs journalctl -u redis -n 100

# Network connectivity test nc -zv redis.local 443 ```

Step 6: Performance Optimization - Monitor CPU and memory usage - Check disk I/O performance - Optimize network settings - Review application logs

Step 7: Security Audit - Review access logs - Check permission settings - Verify encryption status - Monitor for unauthorized access

Common Pitfalls and Solutions

Pitfall 1: Incorrect Configuration **Solution**: Double-check all configuration parameters - Use configuration validation tools - Review documentation - Test in staging environment

Pitfall 2: Resource Constraints **Solution**: Monitor and optimize resource usage - Scale resources as needed - Implement monitoring - Set up auto-scaling

Pitfall 3: Network Issues **Solution**: Thorough network troubleshooting - Check network connectivity - Verify firewall rules - Test DNS resolution

Real-World Case Studies

Case Study: Large-Scale Deployment **Scenario**: Enterprise REDIS deployment with Redis Out of Memory errors **Resolution**: - Implemented comprehensive monitoring - Optimized configuration settings - Added redundancy and failover **Result**: 99.99% uptime achieved

Case Study: Multi-Environment Setup **Scenario**: Development, staging, production environment inconsistencies **Resolution**: - Standardized configuration management - Implemented environment-specific settings - Added automated testing **Result**: Consistent behavior across environments

Best Practices Summary

Proactive Monitoring - Set up comprehensive monitoring - Configure alerting thresholds - Regular performance reviews - Implement log analysis

Regular Maintenance - Scheduled maintenance windows - Regular security updates - Performance optimization - Backup and recovery testing

Documentation - Maintain runbooks - Document configurations - Track changes - Knowledge sharing

Quick Reference Checklist

  • [ ] Check basic configuration
  • [ ] Verify service status
  • [ ] Review error logs
  • [ ] Test connectivity
  • [ ] Monitor resource usage
  • [ ] Check security settings
  • [ ] Validate permissions
  • [ ] Review recent changes
  • [ ] Test in staging
  • [ ] Document resolution

This comprehensive troubleshooting guide covers all aspects of Redis Out of Memory errors. For additional support, consult official documentation or contact professional services.

  • [WordPress troubleshooting: Fix aof rewrite disk space exhaustion Is](aof-rewrite-disk-space-exhaustion)
  • [Technical troubleshooting: Fix client buffer overflow output buffer exceeded ](client-buffer-overflow-output-buffer-exceeded)
  • [Technical troubleshooting: Fix cluster meet node handshake failure Issue in R](cluster-meet-node-handshake-failure)
  • [Technical troubleshooting: Fix cluster node failure during resharding Issue i](cluster-node-failure-during-resharding)
  • [Technical troubleshooting: Fix cluster slot migration timeout Issue in Redis-](cluster-slot-migration-timeout)

<script type="application/ld+json"> { "@context": "https://schema.org", "@type": "TechArticle", "headline": "Redis Out of Memory", "description": "Complete guide to fix Redis Out of Memory. Step-by-step solutions, real-world examples, prevention strategies.", "url": "https://www.fixwikihub.com/fix-redis-out-of-memory", "publisher": { "@type": "Organization", "name": "FixWikiHub", "url": "https://www.fixwikihub.com" }, "author": { "@type": "Person", "name": "FixWikiHub Editorial Team" }, "datePublished": "2025-11-19T16:31:48.041Z", "dateModified": "2025-11-19T16:31:48.041Z" } </script>