<< All versions
Skill v1.0.0
currentAutomated scan100/100bagelhole/devops-security-agent-skills/redis
──Details
PublishedSeptember 29, 2026 at 12:14 PM
Content Hashsha256:eca508ac6a39cc60...
Git SHA0365f57a079b
──Files
Files (1 file, 9.5 KB)
SKILL.md9.5 KBactive
SKILL.md · 407 lines · 9.5 KB
version: "1.0.0" name: redis description: Configure Redis for caching and data storage. Set up clustering, persistence, and Sentinel. Use when implementing Redis caching or queues. license: MIT metadata: author: devops-skills version: "1.0"
Redis
Configure, operate, and optimize Redis for caching, queues, rate limiting, and real-time data storage.
When to Use
- You need a low-latency in-memory cache to reduce database load.
- Your application requires rate limiting, session storage, or leaderboards.
- You need pub/sub messaging between services.
- You want a distributed lock or job queue backed by an in-memory store.
Prerequisites
- Linux server or Docker.
- Root or sudo access for package installation.
- Redis 7.x recommended for production.
Installation and Setup
bash
# Debian / Ubuntusudo apt updatesudo apt install -y redis-server# RHEL / Amazon Linuxsudo dnf install -y redis# Start and enablesudo systemctl enable --now redis-server# Verifyredis-cli ping# Expected output: PONG
Core Configuration
Edit /etc/redis/redis.conf:
ini
# Networkbind 0.0.0.0port 6379protected-mode yesrequirepass strong_redis_password# Memorymaxmemory 2gbmaxmemory-policy allkeys-lru# Connectionsmaxclients 10000timeout 300tcp-keepalive 60# Loggingloglevel noticelogfile /var/log/redis/redis-server.log# Security — disable dangerous commands in productionrename-command FLUSHALL ""rename-command FLUSHDB ""rename-command CONFIG ""rename-command DEBUG ""
bash
sudo systemctl restart redis-server
redis-cli Commands Reference
bash
# Connect with authenticationredis-cli -a strong_redis_password# Connect to a remote hostredis-cli -h 10.0.0.5 -p 6379 -a strong_redis_password
String Operations
SET user:1:name "Alice"GET user:1:name# Set with TTL (seconds)SETEX session:abc123 3600 '{"userId":1}'# Set only if key does not exist (distributed lock pattern)SET lock:order:42 "worker-1" NX EX 30# Increment countersINCR page:views:/homeINCRBY api:quota:user:1 -1
Hash Operations
HSET user:1 name "Alice" email "alice@example.com" plan "pro"HGET user:1 emailHGETALL user:1HINCRBY user:1 login_count 1
List Operations (Queues)
LPUSH queue:emails '{"to":"alice@example.com","subject":"Welcome"}'RPOP queue:emailsLLEN queue:emails# Blocking pop (worker pattern)BRPOP queue:emails 30
Set and Sorted Set Operations
# Sets — unique tagsSADD article:1:tags "redis" "database" "caching"SMEMBERS article:1:tagsSISMEMBER article:1:tags "redis"# Sorted sets — leaderboardsZADD leaderboard 1500 "player:1" 2300 "player:2" 1800 "player:3"ZREVRANGE leaderboard 0 9 WITHSCORESZINCRBY leaderboard 100 "player:1"ZRANK leaderboard "player:2"
Key Management
KEYS user:* # avoid in production — use SCAN insteadSCAN 0 MATCH user:* COUNT 100TTL session:abc123PERSIST session:abc123DEL user:oldEXPIRE user:1 86400TYPE user:1
Persistence
RDB Snapshots
ini
# redis.conf — save snapshots at intervalssave 900 1 # snapshot if >= 1 key changed in 900 secondssave 300 10 # snapshot if >= 10 keys changed in 300 secondssave 60 10000 # snapshot if >= 10000 keys changed in 60 secondsdbfilename dump.rdbdir /var/lib/redisrdbcompression yes
AOF (Append-Only File)
ini
appendonly yesappendfilename "appendonly.aof"appendfsync everysec # good balance of safety and performance# Options: always (safest, slowest), everysec (recommended), no (OS decides)# AOF rewrite thresholdsauto-aof-rewrite-percentage 100auto-aof-rewrite-min-size 64mb
Recommended Production Strategy
Use both RDB and AOF together. RDB provides fast restarts and compact backups. AOF provides durability down to 1-second granularity.
ini
save 900 1save 300 10appendonly yesappendfsync everysec
Redis Sentinel (High Availability)
Sentinel monitors Redis instances and performs automatic failover.
Sentinel Configuration
ini
# /etc/redis/sentinel.confport 26379sentinel monitor mymaster 10.0.0.1 6379 2sentinel auth-pass mymaster strong_redis_passwordsentinel down-after-milliseconds mymaster 5000sentinel failover-timeout mymaster 60000sentinel parallel-syncs mymaster 1
Run at least three Sentinel instances for quorum.
bash
# Start Sentinelredis-sentinel /etc/redis/sentinel.conf# Query Sentinelredis-cli -p 26379 SENTINEL mastersredis-cli -p 26379 SENTINEL get-master-addr-by-name mymasterredis-cli -p 26379 SENTINEL replicas mymaster
Redis Cluster Mode
Cluster mode distributes data across multiple shards automatically.
bash
# Create a 6-node cluster (3 masters + 3 replicas)redis-cli --cluster create \10.0.0.1:6379 10.0.0.2:6379 10.0.0.3:6379 \10.0.0.4:6379 10.0.0.5:6379 10.0.0.6:6379 \--cluster-replicas 1 -a strong_redis_password# Check cluster statusredis-cli -c -a strong_redis_password CLUSTER INFOredis-cli -c -a strong_redis_password CLUSTER NODES# Add a new noderedis-cli --cluster add-node 10.0.0.7:6379 10.0.0.1:6379# Rebalance slotsredis-cli --cluster rebalance 10.0.0.1:6379
ini
# redis.conf for cluster nodescluster-enabled yescluster-config-file nodes.confcluster-node-timeout 5000
Common Patterns
Caching with TTL
bash
# Cache a database query result for 5 minutesSET cache:user:42:profile '{"name":"Alice","plan":"pro"}' EX 300# Cache-aside pattern (pseudocode):# 1. GET cache:key -> if hit, return# 2. Query database# 3. SET cache:key result EX 300# 4. Return result
Rate Limiting (Sliding Window)
bash
# Allow 100 requests per minute per user# Using a sorted set with timestamps as scoresZADD ratelimit:user:42 1700000000.123 "req-uuid-1"ZREMRANGEBYSCORE ratelimit:user:42 0 1699999940.000ZCARD ratelimit:user:42EXPIRE ratelimit:user:42 60# If ZCARD >= 100, reject the request
Pub/Sub Messaging
bash
# Terminal 1 — subscriberredis-cli -a strong_redis_passwordSUBSCRIBE notifications:order-updates# Terminal 2 — publisherredis-cli -a strong_redis_passwordPUBLISH notifications:order-updates '{"orderId":42,"status":"shipped"}'# Pattern subscriptionPSUBSCRIBE notifications:*
Distributed Locking (Redlock Pattern)
bash
# Acquire lockSET lock:resource:42 "worker-abc" NX EX 30# Returns OK if acquired, nil if already held# Release lock (use Lua script to ensure atomicity)redis-cli -a strong_redis_password EVAL "if redis.call('get', KEYS[1]) == ARGV[1] thenreturn redis.call('del', KEYS[1])elsereturn 0end" 1 lock:resource:42 "worker-abc"
Docker Compose Setup
yaml
# docker-compose.ymlversion: "3.9"services:redis:image: redis:7-alpinerestart: unless-stoppedports:- "6379:6379"volumes:- redis_data:/data- ./redis.conf:/usr/local/etc/redis/redis.conf:rocommand: redis-server /usr/local/etc/redis/redis.confhealthcheck:test: ["CMD", "redis-cli", "-a", "strong_redis_password", "ping"]interval: 10stimeout: 5sretries: 5redis-sentinel:image: redis:7-alpinerestart: unless-stoppedports:- "26379:26379"volumes:- ./sentinel.conf:/usr/local/etc/redis/sentinel.confcommand: redis-sentinel /usr/local/etc/redis/sentinel.confdepends_on:redis:condition: service_healthyredis-commander:image: rediscommander/redis-commander:latestrestart: unless-stoppedports:- "8081:8081"environment:REDIS_HOSTS: "local:redis:6379:0:strong_redis_password"depends_on:redis:condition: service_healthyvolumes:redis_data:
bash
docker compose up -dredis-cli -h 127.0.0.1 -a strong_redis_password ping
Monitoring
bash
# Real-time statsredis-cli -a strong_redis_password INFO statsredis-cli -a strong_redis_password INFO memoryredis-cli -a strong_redis_password INFO replication# Key metrics to watchredis-cli -a strong_redis_password INFO stats | grep -E "keyspace_hits|keyspace_misses"# Hit ratio = hits / (hits + misses) — aim for > 95%# Memory usage breakdownredis-cli -a strong_redis_password MEMORY STATS# Slow log (queries > 10ms by default)redis-cli -a strong_redis_password SLOWLOG GET 10redis-cli -a strong_redis_password SLOWLOG LEN# Monitor all commands in real time (debugging only — impacts performance)redis-cli -a strong_redis_password MONITOR# Connected clientsredis-cli -a strong_redis_password CLIENT LIST
Troubleshooting
| Symptom | Likely Cause | Fix | |
|---|---|---|---|
OOM command not allowed | maxmemory limit reached | Increase maxmemory or set a stricter eviction policy | |
| High latency spikes | RDB save or AOF rewrite forking | Use save "" to disable RDB if AOF is enabled; tune auto-aof-rewrite-min-size | |
LOADING Redis is loading the dataset in memory | Large dataset being restored on startup | Wait for load to complete; consider smaller dataset or faster disk | |
| Cache hit ratio < 90% | TTLs too short or working set exceeds memory | Increase maxmemory; review TTL strategy | |
| Sentinel not failing over | Fewer than quorum Sentinels reachable | Ensure >= 3 Sentinels are running and network-connected | |
CROSSSLOT error in cluster | Multi-key command spans slots | Use hash tags {user:42}:profile to colocate related keys |
Related Skills
- postgresql - Primary database that Redis caches
- mysql - Primary database that Redis caches
- mongodb - Document database that Redis can front
- database-backups - Include RDB files in backup strategy