Domain 8Data InfrastructureINTERMEDIATE

The Production SRE Handbook for Redis: Architecture, Operations, Security, and Incident Response

A comprehensive guide to Redis in production. Covers architecture, RESP protocol, memory tuning, eviction policies, replication, Sentinel/Cluster, persistence (RDB/AOF), CLI management, diagnostic workflows, and real-world failure troubleshooting.

Domain: Domain 8: Data Infrastructure•Updated: 2026-11-03
#linux#sysadmin#redis#sre#database#caching

1. Overview

Redis (Remote Dictionary Server) is an open-source, in-memory data structure store used primarily as a database, cache, message broker, and streaming engine. Unlike traditional relational database management systems (RDBMS) that query disk-backed tabular data structures via SQL, Redis holds its entire dataset in physical memory (RAM) to deliver sub-millisecond reads and writes.

The Core Problem Solved

Traditional disk-backed databases (such as PostgreSQL or MySQL) are bounded by disk I/O, complex indexing, and query execution planning. When web applications scale to thousands of concurrent requests per second, database read locks, page cache misses, and CPU-intensive joins introduce severe latency bottlenecks. Redis resolves this issue by keeping hot datasets directly in RAM and executing operations using highly optimized, single-threaded in-memory algorithms.

+-------------------+      Read Hot Data (<1ms)      +-------------------+
|  Client / Web App | -----------------------------> |   Redis Cache     |
|   Microservices   | <----------------------------- |    (in RAM)       |
+-------------------+      Cache Miss / Write        +-------------------+
          |                                                    |
          | Fallback Query                                     | Periodic Snapshot / AOF
          v                                                    v
+-----------------------------------+                +-------------------+
| Disk-Backed DB (Postgres / MySQL) |                |  Disk Storage     |
+-----------------------------------+                +-------------------+

Common Production Use Cases

  • Database Caching: Offloading frequent read queries from disk-backed RDBMS by caching object states and setting dynamic Time-To-Live (TTL) values.
  • Session State Storage: Maintaining centralized user authentication sessions with strict TTL expiration, enabling stateless application scale-out.
  • Rate Limiting & Throttling: Employing lightweight integer operations (INCR, DECR) paired with key expiration to construct leaky/token bucket rate limiters.
  • Asynchronous Queues & Streams: Utilizing ordered Lists and Streams to buffer background jobs for consumer worker processes.
  • Real-Time Leaderboards & Metrics: Leveraging Sorted Sets (ZSET) to maintain dynamic, pre-sorted metrics (such as gaming scoreboards or active user rankings).
  • Pub/Sub Messaging: Facilitating low-latency, fire-and-forget message fan-out between decoupled microservices.

Redis vs. Alternatives

  • Redis vs. Memcached: Memcached is a multithreaded, pure in-memory key-value store suitable for simple string caching. Redis supports rich data structures (Hashes, Sets, Sorted Sets, Streams), persistence options, replication, Lua scripting, pub/sub, and transaction execution.
  • Redis vs. KeyDB / Dragonfly: Modern multithreaded forks/alternatives aim to scale across CPU cores without multiple process instances. However, vanilla Redis remains the industry standard due to its maturity, predictable performance, robust ecosystem, and wide managed service support.

2. Architecture and Mental Model

To operate Redis effectively as a System Administrator or Site Reliability Engineer (SRE), you must understand its execution loop, client communication mechanism, and memory usage characteristics.

Single-Threaded Execution Model

Redis processes client commands sequentially using an event loop built on I/O multiplexing (epoll on Linux).

                                    +----------------------------------+
                                    |        Redis Main Thread         |
+------------------+                |                                  |
|  Client Conn 1   | ---\           |  +----------------------------+  |
+------------------+     \          |  |       epoll Event Loop     |  |
+------------------+      \         |  +----------------------------+  |
|  Client Conn 2   | -----> [Multiplexer] -----------> |               |
+------------------+      /         |                  v               |
+------------------+     /          |         Execute Command          |
|  Client Conn 3   | ---/           |       (Sequential / Atomic)      |
+------------------+                |                                  |
                                    +----------------------------------+
                                                       |
                                      +----------------+----------------+
                                      |                                 |
                                      v                                 v
                            +-------------------+             +-------------------+
                            | Background Threads|             | Background Threads|
                            | (Bio / Asynchronous|            | (BGSAVE / AOF     |
                            |  FLUSH / Unlink)  |             |  BGREWRITEAOF)    |
                            +-------------------+             +-------------------+

Because command execution occurs on a single thread per instance:

  1. Atomicity: Key operations execute without locking overhead or race conditions.
  2. Head-of-Line Blocking Risk: Any long-running command (e.g., KEYS *, large SMEMBERS, complex SORT) stalls all subsequent commands for all clients connected to that Redis node.

Note on Modern Redis Architecture: Redis 6.0 introduced threaded I/O for network socket parsing and serialization, but actual execution of commands on the internal key-value data structures remains strictly single-threaded.

Redis Serialization Protocol (RESP)

Clients communicate with Redis over TCP (default port 6379) or Unix sockets using the RESP protocol. RESP is a simple, human-readable framing protocol:

  • Simple Strings: Starts with + (e.g., +OK\r\n)
  • Errors: Starts with - (e.g., -ERR unknown command\r\n)
  • Integers: Starts with : (e.g., :1000\r\n)
  • Bulk Strings: Starts with $ followed by byte count (e.g., $5\r\nhello\r\n)
  • Arrays: Starts with * followed by element count.

High Availability and Scaling Architecture

  1. Standalone Architecture: Single process handling all reads/writes. Vulnerable to single point of failure (SPOF) and bounded by a single machine’s RAM capacity.
  2. Replication Architecture (Primary / Replica): A primary server receives writes and streams operational commands asynchronously to one or more replicas to supply read offloading.
  3. Sentinel Architecture (High Availability): A set of independent Sentinel processes monitors primary and replica nodes, automatically promoting a replica to primary if the primary fails.
  4. Cluster Architecture (Horizontal Scaling): Data is automatically split across multiple primary shards using 16,384 fixed hash slots (slot = CRC16(key) mod 16384).

3. Core Concepts and Terminology

Understanding Redis’s primitive data structures and management primitives is essential for proper application design and performance tuning.

+-----------------------------------------------------------------------------------------+
|                                    REDIS DATA STRUCTURES                                |
+------------------+-------------------+--------------------+-----------------------------+
|   Data Type      |  Common Use Cases | Key CLI Commands   | Operational Considerations  |
+------------------+-------------------+--------------------+-----------------------------+
| Strings          | Cache, counters,  | SET, GET, INCR,    | Max 512MB per value. Core   |
|                  | locks             | DECR, MGET         | structure for key-value.    |
+------------------+-------------------+--------------------+-----------------------------+
| Hashes           | User profiles,    | HSET, HGET,        | Efficient memory encoding   |
|                  | object fields     | HGETALL, HDEL      | (ziplist/listpack).         |
+------------------+-------------------+--------------------+-----------------------------+
| Lists            | Queues, activity  | LPUSH, RPOP,       | O(1) push/pop at ends.      |
|                  | feeds             | LINDEX, LRANGE     | Heavy O(N) risks on LRANGE. |
+------------------+-------------------+--------------------+-----------------------------+
| Sets             | Unique tags, IP   | SADD, SMEMBERS,    | Unordered unique elements.  |
|                  | blacklists        | SISMEMBER, SINTER  | Set intersections can be CPU|
|                  |                   |                    | intensive.                  |
+------------------+-------------------+--------------------+-----------------------------+
| Sorted Sets      | Leaderboards,     | ZADD, ZRANGE,      | Members ranked by floating- |
| (ZSets)          | priority queues   | ZREVRANGEBYSCORE   | point score. Uses skip lists|
+------------------+-------------------+--------------------+-----------------------------+
| Streams          | Event logs, job   | XADD, XREAD,       | Append-only stream log with |
|                  | queues w/ groups  | XREADGROUP         | built-in consumer groups.   |
+------------------+-------------------+--------------------+-----------------------------+

Key Technical Terms

  • TTL (Time To Live): The lifetime assigned to a key before Redis automatically deletes or evicts it.
  • Key Eviction: The process of freeing memory by removing existing keys when maxmemory limit is reached, driven by an eviction policy.
  • Fragmentation Ratio: The ratio of memory requested from the OS (used_memory_rss) to memory allocated by Redis internals (used_memory). High ratios indicate wasted OS memory due to fragmentation.
  • Save Point (RDB): A snapshot rule in redis.conf that triggers a background point-in-time state save to disk if a specified number of write operations occur within a given time frame.
  • Copy-on-Write (CoW): A Linux kernel memory optimization utilized during BGSAVE and BGREWRITEAOF where child processes read memory pages shared with the parent until the parent writes to them.

4. Installation and Version Management

Installing on Debian / Ubuntu

Official repositories often lag behind upstream releases. It is recommended to use the official Redis APT repository:

# Install dependencies
sudo apt-get update
sudo apt-get install -y lsb-release curl gpg

# Add official Redis GPG key and repository
curl -fsSL https://packages.redis.io/gpg | sudo gpg --dearmor -o /usr/share/keyrings/redis-archive-keyring.gpg
echo "deb [signed-by=/usr/share/keyrings/redis-archive-keyring.gpg] https://packages.redis.io/deb $(lsb_release -cs) main" | sudo tee /etc/apt/sources.list.d/redis.list

# Update package index and install server
sudo apt-get update
sudo apt-get install -y redis

Installing on RHEL / Rocky Linux / AlmaLinux

On Enterprise Linux systems, Redis is available via EPEL or AppStream modules:

# Enable EPEL and install Redis
sudo dnf install -y epel-release
sudo dnf install -y redis

# Alternatively, enable a specific Redis AppStream stream
sudo dnf module reset redis
sudo dnf module enable redis:7 -y
sudo dnf install -y redis

Verifying Installation and Version

# Inspect CLI and server version information
redis-server --version
redis-cli --version

# Perform health probe on local instance
redis-cli PING

Expected Output: PONG


5. Configuration Files and Directory Structure

Redis configuration paths and service environments differ slightly across distributions:

File/Directory Purpose Distribution / Details
/etc/redis/redis.conf Main Configuration File Debian/Ubuntu default location.
/etc/redis.conf Main Configuration File RHEL/CentOS/Rocky default location.
/var/lib/redis/ Data Directory Default storage path for dump.rdb and appendonly.aof.
/var/log/redis/redis-server.log Log File Location Default log destination when logfile directive is set.
/run/redis/redis-server.sock Unix Domain Socket Unix socket for fast local connections (if enabled).
/etc/systemd/system/redis.service Systemd Unit File Service configuration file governing process runtime.

Critical Directives in redis.conf

################################# NETWORKING #################################
# Interfaces to listen on. Default 127.0.0.1 limits to loopback interface.
bind 127.0.0.1 ::1

# TCP Port (default 6379)
port 6379

# Protected mode rejects external queries if bind is open and no auth is set.
protected-mode yes

################################# GENERAL #################################
# Daemonize (set to 'no' when running under systemd with Type=notify)
daemonize no

# Log file destination. Empty string forces logging to standard output / journald.
logfile /var/log/redis/redis-server.log

# Working directory for RDB and AOF files
dir /var/lib/redis

################################# SECURITY #################################
# Legacy single password authentication
# requirepass SuperSecretPassword123

# Preferred: ACL rules (Redis 6+) configured directly or in external aclfile
# aclfile /etc/redis/users.acl

################################# MEMORY MANAGEMENT #######################
# Maximum memory ceiling (e.g., 4GB). Mandatory for production servers!
maxmemory 4gb

# Eviction strategy when maxmemory is hit
maxmemory-policy allkeys-lru

################################# PERSISTENCE ##############################
# RDB Snapshots: save <seconds> <changes>
save 900 1
save 300 10
save 60 10000

# Stop writes if RDB background save fails
stop-writes-on-bgsave-error yes

# Enable Append Only File (AOF)
appendonly yes
appendfsync everysec

Validating Configuration Changes

Before restarting production services, validate syntax to prevent runtime start failures:

# Test configuration syntax and print loaded options
redis-server /etc/redis/redis.conf --test-memory 1024

6. Service Management and Common Operations

Managing the Redis daemon using systemd requires recognizing distribution naming differences: Debian/Ubuntu uses redis-server, whereas Enterprise Linux uses redis.

Service Management Commands

# Debian / Ubuntu Service Control
sudo systemctl start redis-server
sudo systemctl stop redis-server
sudo systemctl restart redis-server
sudo systemctl reload redis-server   # Note: Not all parameters accept runtime reload
sudo systemctl status redis-server
sudo systemctl enable redis-server

# RHEL / Rocky Linux Service Control
sudo systemctl start redis
sudo systemctl stop redis
sudo systemctl status redis
sudo systemctl enable redis

Verifying Service Listeners and Processes

# Verify process status and execution flags
ps aux | grep redis-server

# Confirm listening port binding
ss -tlnp | grep 6379

Expected Output: LISTEN 0 511 127.0.0.1:6379 0.0.0.0:* users:(("redis-server",pid=1234,fd=6))


7. Common Administrative Tasks and Workflows

Task 1: Setting up ACLs (Access Control Lists)

Redis 6 introduced ACLs to replace the monolithic requirepass password model.

# Connect to Redis with administrative privileges
redis-cli -a "AdminMasterPassword"

# Create a restricted user for an application service
> ACL SETUSER app-user on >AppStrongPassword ~cache:* +@read +@write -@dangerous

Explanation: This creates user app-user, enables it (on), sets a password (>AppStrongPassword), restricts key access to patterns starting with cache:* (~cache:*), allows read and write commands (+@read +@write), and revokes access to dangerous administration commands (-@dangerous).

Task 2: Modifying Parameters at Runtime Without Restarting

Certain parameters can be adjusted dynamically without incurring service downtime:

# Check current maxmemory allocation
redis-cli CONFIG GET maxmemory

# Dynamically increase maxmemory to 8 Gigabytes
redis-cli CONFIG SET maxmemory 8589934592

# Persist active runtime changes back to disk configuration file (/etc/redis/redis.conf)
redis-cli CONFIG REWRITE

Task 3: Safely Iterating Keys in Production

Running KEYS * on large datasets stalls the event loop, causing application timeouts. Use SCAN instead for non-blocking iteration.

# Safely iterate keys matching a prefix using dynamic cursors
redis-cli SCAN 0 MATCH "session:*" COUNT 100

Output Format: Returns a new cursor ID along with an array of matched keys. Repeat using the new cursor until the returned cursor is 0.


8. CLI Command Reference and Cheatsheet

The redis-cli utility is the primary management interface.

Connection & Global Inspection

Command Purpose Flags / Options Practical Example
redis-cli Primary CLI connection -h (host), -p (port), -a (password), -n (DB num) redis-cli -h 10.0.0.5 -p 6379 -a Secret123
redis-cli -u URI Connection Accepts redis:// or rediss:// (TLS) redis-cli -u redis://user:pass@127.0.0.1:6379/0
PING Check service health Optional custom string redis-cli PING (Returns PONG)
INFO Global operational statistics Section filter: server, memory, stats, replication redis-cli INFO memory
MONITOR Real-time command stream CAUTION: Disables performance; debug only redis-cli MONITOR

Key Operations & Data Manipulation

Command Purpose Arguments Example
SET Store string value Key, value, EX (TTL sec), NX (if not exists) SET token:123 "abc" EX 3600
GET Fetch string value Key GET token:123
TTL Query remaining lifetime Key TTL token:123 (Returns seconds, -1 no TTL, -2 missing)
EXPIRE Set key timeout Key, seconds EXPIRE session:99 1800
DEL Synchronous deletion Key [key …] DEL cache:temp1 cache:temp2
UNLINK Asynchronous deletion Key [key …] (Frees memory in background thread) UNLINK high_volume_huge_set
SCAN Non-blocking key search cursor MATCH pattern COUNT count SCAN 0 MATCH "user:*" COUNT 50
TYPE Inspect data structure Key TYPE session:123

Diagnostic & Administration Tools

Command Purpose Flags / Details Example
SLOWLOG GET Retrieve slow execution logs Count SLOWLOG GET 10
CLIENT LIST Inspect connected clients Shows IP, file descriptor, idle time, current command redis-cli CLIENT LIST
CLIENT KILL Terminate specific connection ID, ADDR, TYPE CLIENT KILL TYPE normal SKIPME yes
MEMORY USAGE Measure exact key RAM footprint Key MEMORY USAGE session:large
FLUSHALL ASYNC Wipe all keys across all DBs DESTRUCTIVE! ASYNC avoids blocking event loop FLUSHALL ASYNC

⚠️ WARNING: FLUSHALL and FLUSHDB clear database instances instantly. Never run these in production without explicit authorization and confirmed backup snapshots.


9. Logs, Monitoring and Diagnostics

Log File Analysis

Locate errors via journalctl or logfiles:

# Follow logs live via journalctl
sudo journalctl -u redis-server -f -n 100

# Search for critical errors in physical log files
grep -E "WARNING|ERROR|MISCONF|OOM" /var/log/redis/redis-server.log

Key Metrics to Monitor via redis-cli INFO

  1. Memory Health (INFO memory):
  • used_memory_human: RAM allocated by Redis memory allocator.
  • used_memory_rss_human: Total RAM consumed by the process as reported by the OS.
  • mem_fragmentation_ratio: used_memory_rss / used_memory. Ratios > 1.5 indicate excessive OS fragmentation; ratios < 1.0 mean Redis is swapping.
  1. Performance Metrics (INFO stats):
  • instantaneous_ops_per_sec: Current query throughput.
  • evicted_keys: Counter of keys removed due to maxmemory enforcement. Rising numbers indicate cache capacity exhaustion.
  • rejected_connections: Connections dropped due to reaching maxclients.
  1. Client Connections (INFO clients):
  • connected_clients: Active TCP connections.
  • blocked_clients: Connections waiting on blocking calls (e.g., BLPOP).

10. Troubleshooting Guide and Common Failure Scenarios

Problem 1: MISCONF Redis is configured to save RDB snapshots, but is currently not able to persist to disk

Symptoms

Applications fail with error: -MISCONF Redis is configured to save RDB snapshots, but is currently not able to persist to disk. Commands that may modify the data set are disabled...

Possible Causes

  1. Disk space exhausted on the target partition housing dir (e.g., /var/lib/redis).
  2. Permission errors: The redis user lacks write permissions to the data directory.
  3. Memory overcommit restrictions: Linux kernel rejects fork() execution during BGSAVE because available RAM is insufficient for Copy-on-Write allocation.

Investigation and Diagnosis

  1. Inspect disk storage capacity:
df -h /var/lib/redis
  1. Verify directory permissions and ownership:
ls -ld /var/lib/redis
  1. Check memory overcommit system tuning settings:
sysctl vm.overcommit_memory
  1. Read system logs for kernel OOM-killer interventions during snapshots:
sudo journalctl -u redis-server -e --grep="BGSAVE"

Root Cause Identification

  • If df -h returns 100% usage, disk exhaustion is the root cause.
  • If sysctl vm.overcommit_memory returns 0, the Linux kernel may reject child process allocation under high write load.

Resolution

  • Disk Full: Clean old files, expand partition size, or relocate dir to a larger volume.
  • Kernel Memory Overcommit: Set vm.overcommit_memory = 1 in /etc/sysctl.conf and apply:
sudo sysctl vm.overcommit_memory=1
  • Temporary Emergency Mitigation (Use with caution):
redis-cli CONFIG SET stop-writes-on-bgsave-error no

Verification

Trigger a background snapshot manually and verify successful completion:

redis-cli BGSAVE
redis-cli INFO persistence | grep rdb_last_bgsave_status

Expected Output: rdb_last_bgsave_status:ok

Prevention

Set up Prometheus/Grafana alerts for disk space usage on /var/lib/redis exceeding 80%, and ensure vm.overcommit_memory = 1 is persisted across host reboots.


Problem 2: Sudden Latency Spikes / Client Timeouts

Symptoms

Application logs show connection timeouts (e.g., Redis::TimeoutError), and command latency increases from <1ms to hundreds of milliseconds.

Possible Causes

  1. Execution of $O(N)$ blocking commands (such as KEYS * or large SMEMBERS).
  2. Transparent Huge Pages (THP) enabled in the Linux kernel causing memory allocation stalls during Copy-on-Write.
  3. Excessive swapping due to RAM exhaustion on the host node.

Investigation and Diagnosis

  1. Check slow execution log:
redis-cli SLOWLOG GET 20
  1. Verify if Transparent Huge Pages (THP) are enabled in Linux:
cat /sys/kernel/mm/transparent_hugepage/enabled

If [always] is bracketed, THP is active and causing latency stalls. 3. Inspect system memory and swap usage:

free -m
vmstat 1 5

Resolution

  1. Stop running blocking commands. Replace KEYS with SCAN in application code.
  2. Disable Transparent Huge Pages immediately:
echo never | sudo tee /sys/kernel/mm/transparent_hugepage/enabled

Persist this setting by adding transparent_hugepage=never to GRUB boot arguments or /etc/rc.local.

Verification

Run latency sampling via CLI:

redis-cli --latency

Ensure continuous average latency remains well below 1.0 ms.


Problem 3: OOM command not allowed when used memory > 'maxmemory'

Symptoms

Write commands (e.g., SET, HSET) return (error) OOM command not allowed when used memory > 'maxmemory'.

Possible Causes

  1. Total memory has reached the maxmemory threshold.
  2. maxmemory-policy is set to noeviction (default setting), causing Redis to reject writes when full rather than purging stale data.

Investigation and Diagnosis

Check current memory footprint and active eviction strategy:

redis-cli INFO memory | grep -E "used_memory_human|maxmemory_human"
redis-cli CONFIG GET maxmemory-policy

Resolution

  1. For Caching Use Cases: Change policy to evict least recently used keys automatically:
redis-cli CONFIG SET maxmemory-policy allkeys-lru
redis-cli CONFIG REWRITE
  1. For Persistent Datasets: Scale up instance memory or expand to a Redis Cluster architecture to shard data across nodes.

Verification

Issue a write command to confirm normal operational status:

redis-cli SET healthcheck:test "1" EX 10

11. Security and Best Practices

  1. Network Isolation: Never bind Redis directly to public IP addresses (0.0.0.0). Ensure bind 127.0.0.1 or private VPC subnet interfaces are explicitly configured.
  2. Disable Dangerous Commands: Rename or disable commands capable of causing catastrophic failure within /etc/redis/redis.conf:
rename-command FLUSHALL ""
rename-command FLUSHDB  ""
rename-command KEYS     ""
rename-command CONFIG   "ADMIN_CONFIG_SECRET_KEY"
  1. Enforce Role-Based Access Control (ACLs): Avoid master passwords (requirepass). Define user-specific privileges using ACL SETUSER to adhere to the principle of least privilege.
  2. TLS Encryption: Enable TLS natively for all cross-node and client communications over untrusted networks.

12. Performance and Resource Optimisation

  • Set Memory Allocator Limits: Always set maxmemory to approximately 75-80% of total host RAM. This leaves headroom for OS operations, client connection buffers, and Copy-on-Write memory page multiplication during BGSAVE snapshots.

  • Configure Eviction Policies Appropriately:

  • allkeys-lru: Ideal for standard caching workloads.

  • volatile-lru: Purges only keys configured with an explicit TTL expiration.

  • noeviction: Best for queues or databases where missing data causes operational failure.

  • Tune TCP Backlog: Increase system network backlog limits in /etc/sysctl.conf to handle bursty connection spikes:

net.core.somaxconn = 65535

13. Backup, Recovery and Maintenance

Replication is a real-time command stream, not a backup system. A FLUSHALL executed on a primary instantly replicates to all slaves.

Production Backup Procedure (RDB Snapshotting)

  1. Trigger a background snapshot:
redis-cli BGSAVE
  1. Monitor completion status until rdb_bgsave_in_progress becomes 0:
redis-cli INFO persistence
  1. Copy the snapshot file safely to remote long-term storage:
cp /var/lib/redis/dump.rdb /backups/redis-dump-$(date +%Y%m%d%H%M).rdb

Restoration Procedure

  1. Stop the active Redis daemon:
sudo systemctl stop redis-server
  1. Copy the backup RDB file into place:
cp /backups/redis-dump-target.rdb /var/lib/redis/dump.rdb
sudo chown redis:redis /var/lib/redis/dump.rdb
  1. Start the service:
sudo systemctl start redis-server

14. Automation and Integration

Systemd Timer for Automatic Nightly Backups

Create script /usr/local/bin/redis-backup.sh:

#!/usr/bin/env bash
set -euo pipefail

BACKUP_DIR="/var/backups/redis"
DATE=$(date +%Y%m%d_%H%M%S)

mkdir -p "$BACKUP_DIR"
redis-cli BGSAVE

# Wait for background save to finish
until [ "$(redis-cli INFO persistence | grep rdb_bgsave_in_progress | tr -d '\r' | cut -d: -f2)" "==" "0" ]; do
    sleep 1
done

cp /var/lib/redis/dump.rdb "$BACKUP_DIR/dump_$DATE.rdb"
find "$BACKUP_DIR" -type f -name "*.rdb" -mtime +7 -delete

Make executable: chmod +x /usr/local/bin/redis-backup.sh.


15. Practical Labs and Exercises

Exercise 1: Non-Blocking Cache Key Expiry and Eviction Testing

  • Goal: Understand key eviction under memory pressure.
  • Steps:
  1. Configure maxmemory 10mb and maxmemory-policy allkeys-lru dynamically.
  2. Populate test keys using a shell loop:
for i in {1..50000}; do redis-cli SET "test:key:$i" "value_$i" > /dev/null; done
  1. Inspect INFO stats to confirm evicted_keys increases beyond 0.

Exercise 2: Simulated Diagnostic Incident Response

  • Goal: Identify and terminate a blocking process.
  • Steps:
  1. Open Terminal A and run redis-cli MONITOR or simulate a heavy lock.
  2. In Terminal B, run redis-cli CLIENT LIST to locate the client file descriptor and IP address.
  3. Terminate the connection using redis-cli CLIENT KILL ADDR <IP:PORT>.

16. Quick Reference and Cheat Sheet

Important Configuration Directives

Parameter Default Recommended Setting Purpose
bind 127.0.0.1 Private IP / Loopback Restricts network exposure interface.
maxmemory 0 (unlimited) 75% Host RAM Mandates upper threshold limit.
maxmemory-policy noeviction allkeys-lru Dictates purging strategy on full RAM.
appendonly no yes Enables append-only persistence logging.

Important Log & Storage Locations

Asset Path
Config File /etc/redis/redis.conf (Debian) / /etc/redis.conf (RHEL)
Data Directory /var/lib/redis/
Service Log /var/log/redis/redis-server.log or journalctl -u redis-server

Common Operational Commands

Action CLI Command
Ping Server redis-cli PING
Check Memory Stats redis-cli INFO memory
View Slow Queries redis-cli SLOWLOG GET 10
Safe Key Scan redis-cli SCAN 0 MATCH "pattern*" COUNT 100
Manual Snapshot redis-cli BGSAVE

17. Further Reading and References

  1. Official Redis Documentation
  2. Redis Configuration Guide
  3. Redis Persistence Reference
  4. Redis High Availability with Sentinel
  5. Redis Security and Access Control Lists (ACL)