- Check Redis Memory Usage: Determine how much memory Redis is currently using with the command:
redis-cli info memory
- Look at the
used_memory
and used_memory_rss
metrics to understand the current memory usage. - Identify Top Memory Consumers: Use the Redis
MEMORY USAGE
command for keys (if you have an idea of your key patterns) or a script to iterate through keys to report their sizes. This will help identify which keys are consuming the most memory: redis-cli --scan --pattern '*' | xargs -L 1 -I{} sh -c 'echo -n "{}: " ; redis-cli memory usage "{}"'
- Check Current Configuration: Review your Redis instance configuration to understand memory limits and eviction policies:
redis-cli config get maxmemory
redis-cli config get maxmemory-policy
- Analyze Slow Queries: Examine slow queries which might be causing bottlenecks and leading to increased memory usage:
redis-cli slowlog get 10
- Investigate the output to find any patterns or commands that are consistently slow.
- Monitor Swap Usage: Use system tools to monitor swap usage and identify if Redis or another process is causing excessive swap usage:
vmstat 1
- or
free -m
- to observe swap and memory usage over time.
- Reduce Memory Usage: If a specific key or set of keys are identified as consuming too much memory, consider deleting them if they are not needed, or reducing their size. For instance, to delete a key:
redis-cli del <key_name>
- Adjust Max Memory: If the memory usage is reaching the limit, and it's safe to allocate more, adjust Redis’s max memory setting (make sure you have enough system memory):
redis-cli config set maxmemory <new_limit>
- Change Eviction Policy: If necessary, change the eviction policy to better manage memory usage:
redis-cli config set maxmemory-policy <policy_name>
- Choose an appropriate eviction policy that matches your use case, like
volatile-lru
, allkeys-lru
, etc. - Restart Redis: If changes are made to the configuration that cannot be applied dynamically, or as a last resort to clear the current memory and swap usage (caution, as this will lead to data loss if data is not persisted properly):
redis-cli shutdown
- and then restart Redis.
- Monitor Metrics After Changes: After taking action, continue to monitor Redis memory and swap usage to ensure the problem is resolved:
redis-cli info memory
- and use system tools to monitor swap usage.
Take these actions step by step to identify and mitigate the root cause of excessive swap usage in Redis.