📦 deps(thirdparty): update snapshots

This commit is contained in:
ci[bot]
2026-07-01 16:02:41 +00:00
parent 8301f01888
commit c824ba9d7b
2449 changed files with 555104 additions and 9259 deletions
@@ -0,0 +1,392 @@
---
name: redis-cli
description: Redis command-line interface (redis-cli) reference and usage guide. Use this skill whenever the user mentions redis-cli, Redis CLI, or any task involving querying, inspecting, debugging, or managing Redis from the command line. Triggers on key/value reads and writes, SCAN or keyspace...
risk: unknown
source: https://github.com/chaunsin/agent-skills/tree/master/skills/redis-cli
source_repo: chaunsin/agent-skills
source_type: community
date_added: 2026-07-01
license: Apache-2.0
license_source: https://github.com/chaunsin/agent-skills/blob/master/LICENSE
---
# redis-cli — Redis Command Line Interface
## When to Use
Use this skill when you need redis command-line interface (redis-cli) reference and usage guide. Use this skill whenever the user mentions redis-cli, Redis CLI, or any task involving querying, inspecting, debugging, or managing Redis from the command line. Triggers on key/value reads and writes, SCAN or keyspace...
redis-cli is the primary command-line tool for interacting with Redis. It supports two modes: **command-line execution** (run a command and exit) and **interactive mode** (a REPL with tab completion, history, and hints). It also provides special modes for monitoring, latency analysis, key space scanning, and data import/export.
**Official resources:** [Redis CLI Docs](https://redis.io/docs/latest/develop/tools/cli/) | [Commands](https://redis.io/commands/) | [Download](https://redis.io/downloads/)
## Prerequisites
```bash
# Check if redis-cli is installed
redis-cli --version
# Install options:
# macOS (Homebrew)
brew install redis
# Ubuntu / Debian
sudo apt install redis-tools
# CentOS / RHEL
sudo yum install redis
# Alpine
apk add redis
# Build from source (binary only)
make redis-cli
# Binary at: src/redis-cli
# Docker (no installation needed)
docker run -it --rm redis redis-cli -h <host> -p <port> PING
```
## Security Considerations
> **IMPORTANT**: Redis provides powerful operations that can irreversibly modify or delete data.
> Pay close attention to the following safety guidelines:
- **Never pass passwords via `-a` in production** — visible in shell history and process listings. Use `REDISCLI_AUTH` environment variable instead.
- **`KEYS *` blocks the server** on large databases — always use `SCAN` in production code.
- **`MONITOR` logs all commands** including sensitive data — use cautiously, and never for extended periods on production servers.
- **`FLUSHALL` / `FLUSHDB` are irreversible** — verify target database with `CLIENT LIST` or `INFO keyspace` first.
- **`--rdb` transfer during write operations** may produce inconsistent snapshots on busy servers.
## Quick Reference
### Connection
```bash
# Basic connection (default: 127.0.0.1:6379)
redis-cli
redis-cli -h redis15.localnet.org -p 6390 PING
# With password (prefer REDISCLI_AUTH env var for security)
redis-cli -a myUnguessablePazzzzzword123 PING
# URI connection
redis-cli -u redis://user:password@host:port/dbnum PING
# TLS
redis-cli --tls --cacert /path/to/ca.crt -h redis.example.com PING
# Specific database
redis-cli -n 2 DBSIZE
# IPv4/IPv6 preference
redis-cli -4 PING # prefer IPv4
redis-cli -6 PING # prefer IPv6
```
### Command-Line vs Interactive Mode
```bash
# Command-line mode: execute one command and exit
redis-cli INCR mycounter
redis-cli GET mykey
# Interactive mode: type commands at the prompt
redis-cli
127.0.0.1:6379> PING
PONG
127.0.0.1:6379> SELECT 2
OK
127.0.0.1:6379[2]> DBSIZE
(integer) 1
```
The prompt shows `host:port[db]`. Use `CONNECT <host> <port>` to switch instances interactively.
### Data Query Cheat Sheet
**String operations** (O(1)):
```
GET key # Get value
SET key value [NX|XX] [EX sec|PX ms|KEEPTTL] # Set with conditions/TTL
SET key value GET # Set new, return old value
GETSET key newvalue # [Use SET key value GET instead]
MGET key1 key2 ... # Get multiple values
INCR key # Increment integer (+1)
INCRBY key 10 # Increment by amount
STRLEN key # String length
GETRANGE key 0 50 # Substring
```
**Hash operations**:
```
HGET key field # Get field value O(1)
HMGET key f1 f2 # Get multiple fields O(N)
HGETALL key # Get all fields/values O(N)
HKEYS key # Get all field names O(N)
HLEN key # Number of fields O(1)
HEXISTS key field # Check field exists O(1)
HSCAN key 0 [MATCH pat] # Iterate hash fields O(1) per call
```
**List operations**:
```
LRANGE key 0 -1 # Get all elements O(N)
LLEN key # List length O(1)
LINDEX key 0 # Get by index O(N)
LPOS key value # Find element position O(N)
```
**Set operations**:
```
SMEMBERS key # Get all members O(N)
SCARD key # Set cardinality O(1)
SISMEMBER key member # Check membership O(1)
SMISMEMBER key m1 m2 # Multi-membership check O(N)
SSCAN key 0 [MATCH pat] # Iterate set members O(1) per call
```
**Sorted Set operations**:
```
ZRANGE key 0 -1 [WITHSCORES] # By index O(log(N)+M)
ZRANGE key -inf +inf BYSCORE # By score range O(log(N)+M)
ZRANGE key [a [z BYLEX # By lexicographic O(log(N)+M)
ZCARD key # Member count O(1)
ZSCORE key member # Get score O(1)
ZRANK key member # Get rank O(log(N))
ZSCAN key 0 [MATCH pat] # Iterate members O(1) per call
```
**Key inspection**:
```
EXISTS key [key ...] # Check existence (O(N) for multi) — returns count
TYPE key # Data type: string|list|set|zset|hash|stream O(1)
TTL key # Seconds until expiry (-1=none, -2=not exists) O(1)
PTTL key # Milliseconds until expiry O(1)
MEMORY USAGE key [SAMPLES n] # Memory consumption in bytes O(N)
OBJECT ENCODING key # Internal encoding (ziplist, hashtable, etc.) O(1)
OBJECT IDLETIME key # Seconds since last access O(1)
DBSIZE # Total keys in current database O(1)
RANDOMKEY # Return a random key O(1)
```
### Key Scanning (Production-Safe)
SCAN-based iteration never blocks the server, unlike `KEYS *` which should be avoided in production.
```bash
# redis-cli built-in scan mode
redis-cli --scan # List all keys
redis-cli --scan --pattern 'user:*' # Filter by pattern
redis-cli --scan --pattern '*:12345*' # Glob patterns
redis-cli --scan --count 100 # Batch size hint
# Programmatic SCAN in interactive mode
SCAN 0 MATCH user:* COUNT 100
# Returns: 1) next_cursor 2) [keys...]
# Continue with: SCAN <next_cursor> MATCH user:* COUNT 100
# Iteration complete when cursor returns 0
# Count keys matching a pattern
redis-cli --scan --pattern 'session:*' | wc -l
```
SCAN guarantees: a full iteration (cursor 0 → cursor 0) always returns all elements that existed for the entire duration. Elements may appear multiple times — handle duplicates in your application.
### Server Inspection
```bash
# Real-time stats (updates every second, use -i to change interval)
redis-cli --stat
# Server information
redis-cli INFO server # Server details
redis-cli INFO memory # Memory usage
redis-cli INFO keyspace # Database key counts
redis-cli INFO replication # Replication status
redis-cli INFO all # Everything
# Key space analysis
redis-cli --bigkeys # Find largest keys by element count
redis-cli --memkeys # Find largest keys by memory usage
redis-cli --keystats # Combined bigkeys + memkeys with distribution
# Latency analysis
redis-cli --latency # Continuous latency sampling
redis-cli --latency-history # Latency over time (15s windows)
redis-cli --latency-dist # Latency spectrum visualization
redis-cli --intrinsic-latency 5 # System baseline latency (run on Redis host)
```
### Output Control
```bash
# Raw output (no type prefixes) — default when piping
redis-cli --raw GET mykey
redis-cli GET mykey > /tmp/output.txt # auto raw mode
# Human-readable (force) when piping
redis-cli --no-raw GET mykey | cat
# CSV output
redis-cli --csv LRANGE mylist 0 -1
# JSON output (RESP3, use -2 for RESP2)
redis-cli --json HGETALL user:1
# Read last argument from stdin
cat /etc/services | redis-cli -x SET net_services
# Pipe commands from file
cat /tmp/commands.txt | redis-cli
```
### Repeat Commands
```bash
# Run command N times
redis-cli -r 5 INCR counter
# Run with delay (seconds, supports decimals)
redis-cli -r -1 -i 1 INFO | grep rss_human # infinite, every 1s
# Interactive: prefix with count
5 INCR mycounter # runs 5 times
```
### Server Administration
```bash
# ACL management
redis-cli ACL LIST # List all users
redis-cli ACL SETUSER admin on >pwd ~* +@all # Create admin user
redis-cli ACL SETUSER readonly on >pwd ~* +@read # Create read-only user
redis-cli ACL DELUSER username # Delete user
redis-cli ACL DRYRUN username GET key # Test user permission
redis-cli ACL GENPASS # Generate random password
# Client management
redis-cli CLIENT LIST # List all connections
redis-cli CLIENT KILL ADDR ip:port # Disconnect client
redis-cli CLIENT PAUSE 5000 WRITE # Pause writes for 5s
redis-cli CLIENT SETNAME my-app # Name current connection
# Configuration
redis-cli CONFIG GET maxmemory # Read config
redis-cli CONFIG SET maxmemory 100mb # Set config at runtime
redis-cli CONFIG REWRITE # Persist to redis.conf
redis-cli CONFIG RESETSTAT # Reset INFO counters
# Replication acknowledgment
redis-cli WAIT 2 5000 # Wait for 2 replicas (5s timeout)
redis-cli WAITAOF 1 1 5000 # Wait for AOF fsync (Redis 7.2+)
# Persistence
redis-cli BGSAVE # Background RDB save
redis-cli BGREWRITEAOF # Background AOF rewrite
redis-cli LASTSAVE # Last save timestamp
# Replication
redis-cli REPLICAOF host port # Become replica
redis-cli REPLICAOF NO ONE # Promote to master
# Server lifecycle
redis-cli SHUTDOWN SAVE # Save and stop
redis-cli SHUTDOWN NOSAVE # Stop without saving
# Slow log
redis-cli SLOWLOG GET 10 # Recent slow commands
redis-cli SLOWLOG LEN # Entry count
redis-cli SLOWLOG RESET # Clear entries
# Cluster management
redis-cli --cluster check host:port # Check cluster health
redis-cli --cluster reshard host:port # Move slots between nodes
redis-cli -c -h cluster-node PING # Cluster-aware connection
```
## Detailed Reference Files
| File | Content | When to read |
|------|---------|-------------|
| `references/connection-and-options.md` | Full connection options, CLI flags, SSL/TLS, environment variables, interactive mode features (completion, history, preferences), RESP protocol versions | Configuring connections, setting up TLS, customizing CLI behavior |
| `references/data-query-commands.md` | Core data type commands: Strings, Hashes, Lists, Sets, Sorted Sets, Streams, Bitmaps, HyperLogLog, Geospatial, plus Key Operations, Database Operations, and Transactions | Looking up core command syntax, understanding command options and return values |
| `references/module-data-types.md` | Module data types: JSON (RedisJSON), Vector Sets (Redis 8.0+), Bloom Filter, Cuckoo Filter, Top-K, Count-Min Sketch, T-Digest, TimeSeries (TS.*), Full-Text Search / RediSearch (FT.*) — with full command syntax and behavioral notes | Working with Redis module data types, similarity search, probabilistic data structures, time series data, full-text search |
| `references/key-management.md` | SCAN family details (SCAN/SSCAN/HSCAN/ZSCAN), big keys analysis (--bigkeys, --memkeys, --keystats), key expiration (EXPIRE, TTL, PERSIST), key space patterns, mass insertion | Scanning databases, analyzing key distribution, managing key lifecycles |
| `references/inspection-and-monitoring.md` | INFO sections, MONITOR, --stat mode, latency tools (--latency, --latency-history, --latency-dist, --intrinsic-latency), RDB backup, replica mode, LRU simulation | Monitoring Redis instances, debugging performance, creating backups |
| `references/advanced-features.md` | Lua scripting (--eval, --ldb), Pub/Sub mode, pipe mode, CSV/JSON output, string quoting and escaping, get input from stdin, remote RDB transfer, Cluster management (--cluster subcommands, cluster commands) | Running scripts, subscribing to channels, bulk data operations, managing Redis Cluster |
| `references/server-administration.md` | ACL management (ACL SETUSER/DELUSER/LIST/CAT/GENPASS), client management (CLIENT LIST/KILL/PAUSE/TRACKING), configuration (CONFIG GET/SET/REWRITE), replication acknowledgment (WAIT/WAITAOF), persistence (SAVE/BGSAVE/BGREWRITEAOF), replication setup (REPLICAOF), server lifecycle (SHUTDOWN/FAILOVER) | Managing users and permissions, controlling client connections, runtime configuration, ensuring write durability, persistence management, replication setup |
## Common Workflows
### Explore an Unknown Database
```bash
# Step 1: Basic stats
redis-cli INFO keyspace
redis-cli DBSIZE
# Step 2: Find big keys and memory usage
redis-cli --bigkeys
redis-cli --memkeys
# Step 3: Sample keys and inspect types
redis-cli --scan | head -20
redis-cli TYPE <key>
redis-cli TTL <key>
# Step 4: Read data based on type
redis-cli HGETALL <hash_key>
redis-cli LRANGE <list_key> 0 -1
redis-cli ZRANGE <zset_key> 0 -1 WITHSCORES
```
### Monitor in Real Time
```bash
# Live server stats
redis-cli --stat -i 2
# Watch memory specifically
redis-cli -r -1 -i 5 INFO memory | grep used_memory_human
# Monitor all commands (caution: high overhead)
redis-cli MONITOR
# Continuous latency
redis-cli --latency-history -i 5
```
### Query Specific Key Patterns
```bash
# Count keys by pattern
redis-cli --scan --pattern 'session:*' | wc -l
# Find and inspect hash keys
redis-cli --scan --pattern 'user:*' | while read key; do
echo "=== $key ==="
redis-cli HGETALL "$key"
done
# Check TTL of matching keys
redis-cli --scan --pattern 'cache:*' | while read key; do
redis-cli TTL "$key"
done
```
## External References
- [Redis CLI Documentation](https://redis.io/docs/latest/develop/tools/cli/)
- [Redis Commands](https://redis.io/commands/)
- [Redis Data Types](https://redis.io/docs/latest/develop/data-types/)
- [Redis Protocol Specification](https://redis.io/docs/latest/develop/reference/protocol-spec/)
- [Redis Mass Insertion](https://redis.io/docs/latest/develop/clients/patterns/bulk-loading/)
- [Redis Lua Debugger](https://redis.io/docs/latest/develop/programmability/lua-debugging/)
## Limitations
- Use this skill only when the task clearly matches its upstream source and local project context.
- Verify commands, generated code, dependencies, credentials, and external service behavior before applying changes.
- Do not treat examples as a substitute for environment-specific tests, security review, or user approval for destructive or costly actions.
@@ -0,0 +1,338 @@
# Advanced Features
## Table of Contents
- [Lua Scripting](#lua-scripting)
- [Pub/Sub Mode](#pubsub-mode)
- [Pipe Mode](#pipe-mode)
- [CSV and JSON Output](#csv-and-json-output)
- [Getting Input from Other Programs](#getting-input-from-other-programs)
- [Cluster Management](#cluster-management)
## Lua Scripting
Redis supports server-side Lua scripting for atomic multi-command operations.
### Running Scripts
```bash
# Run script from file with --eval
redis-cli --eval /tmp/script.lua key1 key2 , arg1 arg2 arg3
# The comma separates KEYS[] from ARGV[]:
# key1, key2 → KEYS[1], KEYS[2]
# arg1, arg2, arg3 → ARGV[1], ARGV[2], ARGV[3]
# Inline EVAL
redis-cli EVAL "return redis.call('SET', KEYS[1], ARGV[1])" 1 mykey myvalue
# EVALSHA (use SHA1 hash of cached script)
redis-cli EVALSHA <sha1> numkeys key [key ...] arg [arg ...]
```
### Lua Script Examples
```lua
-- Conditional SET (only if value matches)
local current = redis.call('GET', KEYS[1])
if current == ARGV[1] then
return redis.call('SET', KEYS[1], ARGV[2])
end
return nil
-- Atomic counter reset
local old = redis.call('GET', KEYS[1])
redis.call('SET', KEYS[1], ARGV[1])
return old
-- Multi-key operation
local results = {}
for i = 1, #KEYS do
results[i] = redis.call('GET', KEYS[i])
end
return results
```
### Lua Debugger
```bash
# Enable debugger (--ldb)
redis-cli --ldb --eval /tmp/script.lua key1 , arg1
# Synchronous mode (blocks server — for debugging only)
redis-cli --ldb-sync-mode --eval /tmp/script.lua key1 , arg1
```
**Async mode** (default): server continues serving other clients during debugging. Script changes are rolled back from server memory after debugging.
**Sync mode**: server is blocked. Script changes persist in server memory. Use only in development.
### Script Management
```bash
redis-cli SCRIPT EXISTS sha1 [sha1 ...] # Check if scripts are cached
redis-cli SCRIPT FLUSH [ASYNC|SYNC] # Clear script cache
redis-cli SCRIPT LOAD script # Cache script, return SHA1
redis-cli SCRIPT KILL # Kill running script (only if no write)
```
### Function API (Redis 7.0+)
Functions are a persistent alternative to scripts:
```bash
redis-cli FUNCTION LOAD "redis.register_function('myfunc', function(keys, args) ... end)"
redis-cli FCALL myfunc 0 arg1 arg2
redis-cli FUNCTION LIST
redis-cli FUNCTION DELETE myfunc
redis-cli FUNCTION FLUSH [ASYNC|SYNC]
redis-cli FUNCTION DUMP # Serialize all functions
redis-cli FUNCTION RESTORE serialized-data # Restore functions
```
## Pub/Sub Mode
redis-cli can publish and subscribe to Redis Pub/Sub channels.
### Subscribing
```bash
# Subscribe to specific channels
redis-cli SUBSCRIBE channel1 channel2
# Pattern subscription
redis-cli PSUBSCRIBE '*'
# Read published messages (blocks until Ctrl-C)
# Output format:
# 1) "pmessage" — message type
# 2) "*" — pattern matched
# 3) "mychannel" — channel name
# 4) "mymessage" — message content
```
### Publishing
```bash
redis-cli PUBLISH mychannel "Hello World"
```
### Inspecting Pub/Sub
```bash
redis-cli PUBSUB CHANNELS [pattern] # List active channels
redis-cli PUBSUB NUMSUB [channel ...] # Subscriber count per channel
redis-cli PUBSUB NUMPAT # Pattern subscription count
redis-cli PUBSUB SHARDCHANNELS [pattern] # List shard channels
redis-cli PUBSUB SHARDNUMSUB [channel ...] # Shard channel subscriber count
```
### Shard Pub/Sub (Redis 7.0+)
Shard Pub/Sub routes messages to the cluster node that owns the channel's slot, providing better scalability:
```bash
redis-cli SSUBSCRIBE shardchannel
redis-cli SUNSUBSCRIBE shardchannel
redis-cli SPUBLISH shardchannel "message"
```
## Pipe Mode
Transfer raw Redis protocol from stdin to the server. This is the fastest way to bulk-insert data.
```bash
# Basic pipe mode
cat data.protocol | redis-cli --pipe
# Custom timeout (seconds)
cat data.protocol | redis-cli --pipe --pipe-timeout 60
# Zero timeout (wait forever)
cat data.protocol | redis-cli --pipe --pipe-timeout 0
```
### Protocol Format
Each command in the pipe file must use Redis protocol:
```
*<number-of-arguments>\r\n
$<length-of-argument>\r\n
<argument-data>\r\n
```
Example — `SET mykey myvalue`:
```
*3\r\n$3\r\nSET\r\n$5\r\nmykey\r\n$7\r\nmyvalue\r\n
```
Pipe mode is dramatically faster than individual commands because it batches network round trips. See the [mass insertion guide](https://redis.io/docs/latest/develop/clients/patterns/bulk-loading/) for generating protocol files.
## CSV and JSON Output
### CSV Output
Single-command CSV output for data export:
```bash
redis-cli --csv LRANGE mylist 0 -1
# "d","c","b","a"
redis-cli --csv HGETALL user:1
# "name","Alice","age","30"
```
**Note:** `--csv` works per command, not for exporting entire databases.
### JSON Output
JSON output using RESP3 protocol:
```bash
# JSON output (uses RESP3 by default)
redis-cli --json HGETALL user:1
# {"name": "Alice", "age": "30"}
# Use with RESP2 if needed
redis-cli --json -2 HGETALL user:1
# ASCII-safe quoted strings (no Unicode)
redis-cli --quoted-json GET mykey
```
### Pipe Commands to Other Tools
```bash
# Format and filter output
redis-cli --raw GET mykey | jq .
# Export to file
redis-cli --csv LRANGE mylist 0 -1 > output.csv
# Use with grep
redis-cli MONITOR | grep "SET"
```
## Getting Input from Other Programs
### Read Last Argument from stdin (-x)
```bash
# Set key to contents of a file
cat /etc/services | redis-cli -x SET net_services
# Check the stored value
redis-cli GETRANGE net_services 0 50
```
### Read Tagged Argument from stdin (-X)
```bash
# Dump and restore a key atomically
redis-cli -D "" --raw dump mykey > /tmp/mykey.dump
redis-cli -X dump_tag restore mykey2 0 dump_tag replace < /tmp/mykey.dump
```
### Pipe Multiple Commands
```bash
# Execute commands from a text file
cat /tmp/commands.txt | redis-cli
# commands.txt format (one command per line):
# SET item:3374 100
# INCR item:3374
# APPEND item:3374 xxx
# GET item:3374
```
### Feed Continuous Data
```bash
# Generate keys continuously
while true; do
echo "SET timestamp:$(date +%s) $(date -Iseconds)"
done | redis-cli --pipe
```
## Cluster Management
redis-cli provides built-in cluster management via `--cluster` subcommands, plus direct cluster commands for lower-level control.
### redis-cli Cluster Operations
```bash
# Create a new cluster (interactive prompts for replication)
redis-cli --cluster create host1:port1 host2:port2 host3:port3 --cluster-replicas 1
# Check cluster state
redis-cli --cluster check host1:port1
# Show cluster info
redis-cli --cluster info host1:port1
# Reshard (move slots between nodes)
redis-cli --cluster reshard host1:port1 --cluster-from <node-id> --cluster-to <node-id> --cluster-slots <n>
# Rebalance slots across all nodes
redis-cli --cluster rebalance host1:port1
# Add a node to the cluster
redis-cli --cluster add-node new-host:new-port existing-host:existing-port
# As replica:
redis-cli --cluster add-node new-host:new-port existing-host:existing-port --cluster-slave --cluster-master-id <id>
# Remove a node
redis-cli --cluster del-node host:port <node-id>
# Fix cluster issues (missing slots, etc.)
redis-cli --cluster fix host:port
# Execute command on all cluster nodes
redis-cli --cluster call host:port <command>
# List all --cluster subcommands
redis-cli --cluster help
```
Use `-c` flag to enable cluster mode in redis-cli (automatically follows `-ASK` and `-MOVED` redirections):
```bash
redis-cli -c -h cluster-node -p 6379
```
### Cluster Commands (Direct)
```bash
# Cluster state and topology
redis-cli CLUSTER INFO # Cluster state overview (O(1))
redis-cli CLUSTER NODES # Full node topology (O(N))
redis-cli CLUSTER SHARDS # Shard/node mapping (O(N), Redis 7.0+)
# Slot management
redis-cli CLUSTER KEYSLOT key # Hash slot for a key (O(1))
redis-cli CLUSTER ADDSLOTS slot [slot ...] # Assign slots to node (O(N))
redis-cli CLUSTER DELSLOTS slot [slot ...] # Unbind slots (O(N))
redis-cli CLUSTER SETSLOT slot IMPORTING|node-id|MIGRATING|STABLE # Slot migration (O(1))
# Node management
redis-cli CLUSTER MEET ip port [bus-port] # Join cluster (O(1))
redis-cli CLUSTER FORGET node-id # Remove node (O(1))
redis-cli CLUSTER REPLICATE node-id # Become replica of node (O(1))
redis-cli CLUSTER RESET [HARD|SOFT] # Reset cluster state (O(N))
# Failover
redis-cli CLUSTER FAILOVER [FORCE|TAKEOVER] # Manual failover (O(1))
redis-cli CLUSTER SAVECONFIG # Save config to disk (O(1))
# Node identification
redis-cli CLUSTER MYID # Current node ID (O(1))
redis-cli CLUSTER MYSHARDID # Current shard ID (O(1))
```
**Behavioral notes:**
- Redis Cluster has 16384 hash slots distributed across master nodes
- `CLUSTER SLOTS` is deprecated since Redis 7.0 — use `CLUSTER SHARDS` instead
- Use `redis-cli -c` for transparent cluster redirections in interactive mode
- `CLUSTER FORGET` auto-propagates via gossip in Redis 7.2+
@@ -0,0 +1,258 @@
# Connection and CLI Options
## Table of Contents
- [Connection Methods](#connection-methods)
- [CLI Flags Reference](#cli-flags-reference)
- [Environment Variables](#environment-variables)
- [SSL/TLS Configuration](#ssltls-configuration)
- [Interactive Mode](#interactive-mode)
- [String Quoting and Escaping](#string-quoting-and-escaping)
## Connection Methods
### Basic Connection
By default, redis-cli connects to `127.0.0.1:6379` with no password.
```bash
# Default connection
redis-cli
# Custom host and port
redis-cli -h redis15.localnet.org -p 6390 PING
# Password authentication
redis-cli -a myUnguessablePazzzzzword123 PING
# ACL-style authentication (Redis 6+)
redis-cli --user admin --pass myPassword PING
# Specific database number
redis-cli -n 2 DBSIZE
```
### URI Connection
```bash
# Full URI format
redis-cli -u redis://user:password@host:port/dbnum PING
# Without username (use "default")
redis-cli -u redis://default:password@localhost:6379/0 PING
# TLS scheme
redis-cli -u rediss://default:password@redis.example.com:6380/0 PING
# Minimal URI
redis-cli -u redis://localhost:6379 PING
```
User, password, and dbnum are optional in the URI. For TLS, use the `rediss://` scheme.
### IPv4/IPv6 Preference
```bash
redis-cli -4 PING # Prefer IPv4
redis-cli -6 PING # Prefer IPv6
```
## CLI Flags Reference
```
Usage: redis-cli [OPTIONS] [cmd [arg [arg ...]]]
Connection:
-h <hostname> Server hostname (default: 127.0.0.1)
-p <port> Server port (default: 6379)
-t <timeout> Connection timeout in seconds (decimals allowed, default: 0 = no limit)
-s <socket> Unix socket (overrides hostname and port)
-a <password> Password (also via REDISCLI_AUTH env var)
--user <username> ACL username (requires -a)
--pass <password> Alias of -a
--askpass Prompt for password from STDIN (ignores -a and REDISCLI_AUTH)
-u <uri> Connection URI: redis://user:password@host:port/dbnum
-n <db> Database number
Protocol:
-2 Start in RESP2 protocol mode
-3 Start in RESP3 protocol mode
Execution:
-r <repeat> Execute command N times (-1 for infinite)
-i <interval> Seconds between repeated commands (supports decimals like 0.1)
Also used in --scan, --stat, --bigkeys, --memkeys, --keystats
-x Read last argument from STDIN
-X <tag> Read tagged argument from STDIN
Output:
--raw Raw output (no type prefixes, default when not TTY)
--no-raw Force human-readable output even when piping
--csv CSV output format
--json JSON output (default RESP3, use -2 for RESP2)
--quoted-json JSON with ASCII-safe quoted strings
-d <delimiter> Delimiter between response bulks in raw mode (default: \n)
-D <delimiter> Delimiter between responses in raw mode (default: \n)
Cluster:
-c Enable cluster mode (follow -ASK and -MOVED redirections)
Behavior:
-e Return non-zero exit code on command failure
--verbose Verbose output
--no-auth-warning Suppress password-on-CLI warning
--quoted-input Force input handling as quoted strings
--show-pushes <yn> Print RESP3 PUSH messages (default: yes in TTY)
Special Modes:
--stat Continuous server stats
--latency Continuous latency sampling
--latency-history Latency tracking over time (15s windows, change with -i)
--latency-dist Latency spectrum visualization (requires xterm 256 colors)
--lru-test <keys> Simulate LRU cache workload
--replica Simulate replica, show commands from master
--rdb <filename> Transfer RDB dump from remote server
--functions-rdb <filename> RDB dump with functions only
--pipe Transfer raw Redis protocol from stdin
--pipe-timeout <n> Pipe mode timeout in seconds (default: 30, 0 = forever)
--bigkeys Scan for keys with many elements
--memkeys Scan for keys consuming memory
--memkeys-samples <n> Memory sampling count
--keystats Combined bigkeys + memkeys with distribution
--keystats-samples <n> Key stats sampling count
--hotkeys Find hot keys (requires *lfu maxmemory-policy)
--scan List keys using SCAN
--pattern <pat> Pattern for --scan, --bigkeys, --memkeys, --keystats, --hotkeys
--quoted-pattern <pat> Same as --pattern, but accepts quoted binary-safe strings
--count <count> COUNT hint for scan operations
--cursor <n> Start scan at cursor (after Ctrl-C)
--top <n> Display top N key sizes (default: 10, with --keystats)
--intrinsic-latency <sec> Measure system baseline latency
--eval <file> Execute Lua script
--ldb Enable Lua debugger with --eval
--ldb-sync-mode Synchronous Lua debugger (blocks server)
--cluster <cmd> Cluster management command
Examples:
redis-cli -u redis://default:PASSWORD@localhost:6379/0
cat /etc/passwd | redis-cli -x set mypasswd
redis-cli -D "" --raw dump key > key.dump && redis-cli -X dump_tag restore key2 0 dump_tag replace < key.dump
redis-cli -r 100 lpush mylist x
redis-cli -r 100 -i 1 info | grep used_memory_human:
redis-cli --eval myscript.lua key1 key2 , arg1 arg2 arg3
```
## Environment Variables
| Variable | Purpose |
|----------|---------|
| `REDISCLI_AUTH` | Password for authentication (preferred over `-a` flag) |
| `REDISCLI_HISTFILE` | Custom history file path (default: `~/.rediscli_history`, set to `/dev/null` to disable) |
| `REDISCLI_RCFILE` | Custom preferences file path (default: `~/.redisclirc`) |
| `HOME` | Base directory for `.rediscli_history` and `.redisclirc` |
**Security tip**: Always prefer `REDISCLI_AUTH` over `-a <password>`. The `-a` flag exposes the password in shell history and process listings (`ps aux`).
## SSL/TLS Configuration
```bash
# Enable TLS with trusted CA
redis-cli --tls --cacert /path/to/ca.crt -h redis.example.com PING
# CA certificate directory
redis-cli --tls --cacertdir /etc/ssl/certs -h redis.example.com PING
# Client certificate authentication (mutual TLS)
redis-cli --tls --cacert /path/to/ca.crt \
--cert /path/to/client.crt \
--key /path/to/client.key \
-h redis.example.com PING
```
## Interactive Mode
### Startup
Run `redis-cli` without arguments to enter interactive mode:
```
$ redis-cli
127.0.0.1:6379> PING
PONG
```
The prompt shows `host:port[db_number]` and updates when you switch databases or connect to a different server.
### Connection Management
```
CONNECT <host> <port> # Connect to different instance
SELECT <db> # Switch database (prompt updates to show db number)
QUIT # Exit redis-cli
```
On disconnection, redis-cli automatically attempts to reconnect. It re-selects the last database but loses other state (e.g., MULTI/EXEC transactions).
### Editing and History
- **Line editing**: Built-in linenoise library — no external dependencies
- **History**: Arrow keys (up/down) access previous commands. Stored in `~/.rediscli_history`
- **Tab completion**: Press TAB to complete command names
- **Syntax hints**: Shown after entering a command name (toggle with `:set hints` / `:set nohints`)
- **Reverse search**: `Ctrl+R` for history search
### Preferences
Set via `:set` command in interactive mode or in `~/.redisclirc`:
```
:set hints # Enable syntax hints
:set nohints # Disable syntax hints
```
### Help System
```
HELP @<category> # Show all commands in a category
HELP <command> # Show help for a specific command
# Available categories:
# @generic, @string, @list, @set, @sorted_set, @hash,
# @pubsub, @transactions, @connection, @server, @scripting,
# @hyperloglog, @cluster, @geo, @stream
```
### Screen Control
```
CLEAR # Clear terminal screen
```
### Repeating Commands
Prefix any command with a number to repeat it:
```
5 INCR mycounter # Execute INCR mycounter 5 times
```
## String Quoting and Escaping
When a string value contains whitespace or non-printable characters, use quoting:
**Double-quoted strings** support escape sequences:
- `\"` `\\` `\n` `\r` `\t` `\b` `\a` `\xhh` (hex)
**Single-quoted strings** are literal, only escaping:
- `\'` `\\`
```
SET mykey "Hello\nWorld" # Two lines: Hello / World
GET mykey
# Hello
# World
AUTH user ">^8T>6Na{u|jp>+v\"55\@_" # Escaped quotes in password
```
When the output target is not a terminal, redis-cli automatically uses raw output mode (no type prefixes like `(integer)`). Force with `--raw` or `--no-raw`.
@@ -0,0 +1,417 @@
# Data Query Commands
Complete command reference for querying and manipulating data in Redis, organized by data type. Each entry includes syntax, complexity, and key behavioral notes.
## Table of Contents
- [Strings](#strings)
- [Hashes](#hashes)
- [Lists](#lists)
- [Sets](#sets)
- [Sorted Sets](#sorted-sets)
- [Streams](#streams)
- [Bitmaps and Bitfields](#bitmaps-and-bitfields)
- [HyperLogLog](#hyperloglog)
- [Geospatial](#geospatial)
- [Key Operations](#key-operations)
- [Database Operations](#database-operations)
- [Transactions](#transactions)
## Strings
Strings are the most basic Redis type, holding up to 512MB. They can store text, numbers (for INCR/DECR), or binary data.
```
# Read / Write
GET key # Get value O(1)
SET key value [EX sec|PX ms|EXAT ts|PXAT ms|KEEPTTL] # Set with optional expiry O(1)
SET key value [NX|XX] # NX=only if not exists, XX=exists O(1)
SET key value GET # Set and return old value O(1)
GETSET key newvalue # [Deprecated 6.2] Use SET key value GET
GETDEL key # Get then delete O(1)
GETEX key [EX sec|PX ms|PERSIST] # Get and set/remove expiry O(1)
# Multi-key
MGET key [key ...] # Get multiple values O(N)
MSET key value [key value ...] # Set multiple values O(N)
MSETNX key value [key value ...] # Set if NONE exist O(N)
# Numeric operations (value must be integer or float)
INCR key # +1 O(1)
INCRBY key increment # +N O(1)
INCRBYFLOAT key increment # +float O(1)
DECR key # -1 O(1)
DECRBY key decrement # -N O(1)
# String manipulation
STRLEN key # Length in bytes O(1)
GETRANGE key start end # Substring O(N)
SETRANGE key offset value # Overwrite at position O(N)
APPEND key value # Append to string O(1)
SUBSTR key start end # Alias for GETRANGE O(N)
# Conditional set (Redis 8.4+)
SET key value IFEQ expected-value # Set only if current value matches
SET key value IFNE expected-value # Set only if current value differs
SET key value IFDEQ expected-digest # Set only if digest matches (hash comparison)
SET key value IFDNE expected-digest # Set only if digest differs
```
**Behavioral notes:**
- `SET` overwrites any existing value regardless of type and clears any existing TTL
- `SET NX` is commonly used for distributed locks
- `INCR`/`DECR` fail if the value is not a valid integer; use `INCRBYFLOAT` for decimals
- `GETRANGE` is 0-indexed; negative indices count from end (-1 = last character)
- Empty string uses ~56 bytes of overhead (`MEMORY USAGE`)
## Hashes
Hashes map string fields to string values — ideal for representing objects. Small hashes are stored in a memory-efficient ziplist encoding.
```
# Read
HGET key field # Get field value O(1)
HMGET key field [field ...] # Get multiple fields O(N)
HGETALL key # Get all fields and values O(N)
HKEYS key # Get all field names O(N)
HVALS key # Get all values O(N)
HLEN key # Number of fields O(1)
HEXISTS key field # Check field exists O(1)
HRANDFIELD key [count [WITHVALUES]] # Random field(s) O(N)
# Write
HSET key field value [field value ...] # Set one or more fields O(N)
HSETNX key field value # Set field only if not exists O(1)
HDEL key field [field ...] # Delete fields O(N)
# Numeric
HINCRBY key field increment # Increment integer field O(1)
HINCRBYFLOAT key field increment # Increment float field O(1)
# Iterate
HSCAN key cursor [MATCH pat] [COUNT n] [NOVALUES] # Incremental iterate O(1)/call
# Field-level expiry (Redis 7.4+)
HEXPIRE key seconds [NX|XX|GT|LT] FIELDS numfields field [field ...] # Set field TTL
HPEXPIRE key milliseconds [NX|XX|GT|LT] FIELDS numfields field [field ...] # Set field TTL (ms)
HTTL key numfields field [field ...] # Get field TTL
HPERSIST key [NX|XX|GT|LT] FIELDS numfields field [field ...] # Remove field TTL
```
**Behavioral notes:**
- `HGETALL` returns alternating field-value pairs: `[field1, value1, field2, value2, ...]`
- `HGETALL` on a non-existent key returns an empty list
- Field order in `HGETALL` and `HKEYS` is non-deterministic
- `HSCAN` with `NOVALUES` returns field names only (saves bandwidth)
- For small hashes, `HGETALL` is efficient; for large ones, prefer `HSCAN`
- Minimum hash length is 0 (empty hash after HDEL of last field)
## Lists
Lists are ordered sequences of strings, implemented as linked lists for fast head/tail operations. Good for queues, stacks, and timelines.
```
# Read
LRANGE key start stop # Get range (0 -1 = all) O(N)
LLEN key # List length O(1)
LINDEX key index # Get by index (0-based) O(N)
LPOS key value [RANK rank] [COUNT n] [MAXLEN len] # Find position O(N)
LMPOP numkeys key [key ...] LEFT|RIGHT [COUNT count] # Pop from multiple lists O(N+M)
# Write (push)
LPUSH key element [element ...] # Push to head O(N) for N elements
RPUSH key element [element ...] # Push to tail O(N) for N elements
LPUSHX key element # Push to head if exists O(1)
RPUSHX key element # Push to tail if exists O(1)
LINSERT key BEFORE|AFTER pivot element # Insert relative to pivot O(N)
# Write (pop)
LPOP key [count] # Pop from head O(N) for count
RPOP key [count] # Pop from tail O(N) for count
BLPOP key [key ...] timeout # Blocking pop from head O(N)
BRPOP key [key ...] timeout # Blocking pop from tail O(N)
# Move
LMOVE source destination LEFT|RIGHT LEFT|RIGHT # Atomic move O(1)
BLMOVE src dest L|R L|R timeout # Blocking move O(1)
RPOPLPUSH source destination # [Deprecated 6.2] Use LMOVE O(1)
# Modify
LSET key index element # Set at index O(N)
LREM key count element # Remove occurrences O(N+M)
LTRIM key start stop # Keep only range O(N)
```
**Behavioral notes:**
- `LRANGE key 0 -1` returns all elements; `LRANGE key 0 9` returns first 10
- Negative indexes count from end: `-1` is last element
- `LPUSH` with multiple elements pushes them left-to-right, so final order is reversed
- `LPOP`/`RPOP` with count (Redis 6.2+) returns an array; without count returns a single element or nil
- `LTRIM` is often combined with `LPUSH` to maintain a capped list
- `BLPOP`/`BRPOP` block the client until data is available or timeout expires (0 = wait forever)
## Sets
Sets are unordered collections of unique strings. Good for membership checking, deduplication, and set operations.
```
# Read
SMEMBERS key # Get all members O(N)
SCARD key # Member count O(1)
SISMEMBER key member # Check membership O(1)
SMISMEMBER key member [member ...] # Multi-membership check O(N)
SRANDMEMBER key [count] # Random member(s) O(N)
SSCAN key cursor [MATCH pat] [COUNT n] # Incremental iterate O(1)/call
# Write
SADD key member [member ...] # Add members O(N)
SREM key member [member ...] # Remove members O(N)
SPOP key [count] # Remove and return random O(N)
SMOVE source dest member # Move member between sets O(1)
# Set operations
SINTER key [key ...] # Intersection O(N*M)
SINTERCARD numkeys key [key ...] [LIMIT limit] # Intersection cardinality O(N*M)
SINTERSTORE dest key [key ...] # Intersection → new set O(N*M)
SUNION key [key ...] # Union O(N)
SUNIONSTORE dest key [key ...] # Union → new set O(N)
SDIFF key [key ...] # Difference (first - rest) O(N)
SDIFFSTORE dest key [key ...] # Difference → new set O(N)
```
**Behavioral notes:**
- `SMEMBERS` returns all members; for large sets, use `SSCAN`
- `SRANDMEMBER` with positive count returns distinct elements (may be fewer than count if count > set size)
- `SRANDMEMBER` with negative count may return duplicates (always returns exactly count elements)
- `SPOP` removes the element(s) from the set; `SRANDMEMBER` does not
- `SDIFF` computes difference starting from the first key — order matters
## Sorted Sets
Sorted sets (zsets) map members to scores. Members are unique and ordered by score, then lexicographically. Good for leaderboards, rankings, and priority queues.
```
# Read by index
ZRANGE key start stop [WITHSCORES] # By rank O(log(N)+M)
ZRANGESTORE dest src start stop # Store range O(log(N)+M)
# Read by score
ZRANGE key min max BYSCORE [WITHSCORES] [LIMIT offset count] # By score O(log(N)+M)
ZCOUNT key min max # Count in score range O(log(N))
ZLEXCOUNT key min max # Count in lex range O(log(N))
# Read by lexicographic order (all members must have same score)
ZRANGE key min max BYLEX [LIMIT offset count] # By lex O(log(N)+M)
# Member lookup
ZSCORE key member # Get score O(1)
ZRANK key member # Get rank (ascending) O(log(N))
ZREVRANK key member # Get rank (descending)O(log(N))
ZMSCORE key member [member ...] # Multi-score get O(N)
# Aggregate info
ZCARD key # Member count O(1)
ZRANDMEMBER key [count [WITHSCORES]] # Random member(s) O(N)
# Iterate
ZSCAN key cursor [MATCH pat] [COUNT n] # Incremental iterate O(1)/call
# Pop extremes
ZPOPMIN key [count] # Remove lowest scored O(log(N)*count)
ZPOPMAX key [count] # Remove highest scoredO(log(N)*count)
BZPOPMIN key [key ...] timeout # Blocking pop min O(log(N))
BZPOPMAX key [key ...] timeout # Blocking pop max O(log(N))
ZMPOP numkeys key [key ...] MIN|MAX [COUNT count] # Pop from multiple O(K)+O(M*log(N))
# Write
ZADD key [NX|XX] [GT|LT] [CH] score member [score member ...] # Add/update O(log(N))
ZREM key member [member ...] # Remove members O(M*log(N))
ZINCRBY key increment member # Increment score O(log(N))
# Remove by range
ZREMRANGEBYRANK key start stop # Remove by rank O(log(N)+M)
ZREMRANGEBYSCORE key min max # Remove by score O(log(N)+M)
ZREMRANGEBYLEX key min max # Remove by lex O(log(N)+M)
# Set operations
ZUNIONSTORE dest numkeys key [key ...] [WEIGHTS w...] [AGGREGATE SUM|MIN|MAX]
ZINTERSTORE dest numkeys key [key ...] [WEIGHTS w...] [AGGREGATE SUM|MIN|MAX]
ZUNION numkeys key [key ...] [WITHSCORES] # Union result
ZINTER numkeys key [key ...] [WITHSCORES] # Intersection result
ZINTERCARD numkeys key [key ...] [LIMIT limit] # Intersection count
ZDIFF numkeys key [key ...] [WITHSCORES] # Difference result
ZDIFFSTORE dest numkeys key [key ...] # Difference → new set
```
**Behavioral notes:**
- `ZRANGE` replaces `ZRANGEBYSCORE`, `ZRANGEBYLEX`, `ZREVRANGE`, `ZREVRANGEBYSCORE`, `ZREVRANGEBYLEX` (all deprecated since Redis 6.2)
- Index-based: `0` is lowest score, `-1` is highest; `REV` flag reverses order
- Score-based: use `-inf` and `+inf` for unbounded ranges; `(` prefix means exclusive: `(1 10` = scores >1 and <=10
- Lex-based: use `[` for inclusive, `(` for exclusive: `[a (z` = members >= "a" and < "z"
- `ZADD` options: `NX` (only add new), `XX` (only update existing), `GT` (only if new score > current), `LT` (only if new score < current), `CH` (return number of changed elements)
- `WITHSCORES` returns alternating member,score pairs
## Streams
Streams are append-only log data structures with consumer groups for message processing.
```
# Write
XADD key [NOMKSTREAM] [MAXLEN|MINID [=|~] threshold [LIMIT count]] *|ID field value [field value ...]
# Add entry O(1)
XADD key [KEEPREF|DELREF|ACKED] ... # Reference control (Redis 8.2+)
XADD key [IDMPAUTO pid | IDMP pid iid] ... # Idempotent add (Redis 8.6+)
# Read
XRANGE key start end [COUNT count] # Read by ID range O(N)
XREVRANGE key end start [COUNT count] # Reverse read O(N)
XREAD [COUNT count] [BLOCK ms] STREAMS key [key ...] ID [ID ...] # Read new entries
XLEN key # Entry count O(1)
# Consumer groups
XGROUP CREATE key groupname ID|$ [MKSTREAM] # Create group
XREADGROUP GROUP group consumer [COUNT n] [BLOCK ms] [NOACK] STREAMS key [key ...] ID [ID ...]
XPENDING key group # Pending messages info
XACK key group ID [ID ...] # Acknowledge message
XCLAIM key group consumer min-idle-time ID [ID ...] [IDLE ms] [TIME ms] [RETRYCOUNT n] [FORCE] [JUSTID]
XAUTOCLAIM key group consumer min-idle-time start [COUNT count] [JUSTID]
# Info
XINFO STREAM key # Stream info
XINFO GROUPS key # Consumer group info
XINFO CONSUMERS key group # Consumer info
# Management
XTRIM key MAXLEN|MINID [=|~] threshold [LIMIT count] # Trim stream
XDEL key ID [ID ...] # Delete entries
XSETID key last-idle # Set last ID
```
**Behavioral notes:**
- `XADD` with `*` auto-generates an ID in format `TIMESTAMP-SEQUENCE`
- `XRANGE key - +` returns all entries; use `COUNT` to limit
- `XREAD BLOCK 0 STREAMS mystream $` blocks until new entries arrive (`$` = latest ID)
- Consumer groups enable multiple consumers to process a stream collaboratively
- Use `XREADGROUP ... STREAMS key >` to read new unassigned messages
## Bitmaps and Bitfields
Bitmaps are strings treated as arrays of bits. Bitfields provide atomic operations on arbitrary-width integers at bit offsets.
```
# Bitmap operations
SETBIT key offset value # Set bit at offset O(1)
GETBIT key offset # Get bit at offset O(1)
BITCOUNT key [start end [BYTE|BIT]] # Count set bits O(N)
BITPOS key bit [start [end [BYTE|BIT]]] # Find first set/unset bit O(N)
BITOP AND|OR|XOR|NOT dest key [key ...] # Bitwise operations O(N)
# Bitfield operations
BITFIELD key [GET type offset] [SET type offset value] [INCRBY type offset increment] [OVERFLOW WRAP|SAT|FAIL]
```
## HyperLogLog
HyperLogLog provides approximate cardinality counting with ~0.81% standard error using constant memory (~12KB).
```
PFADD key element [element ...] # Add elements O(1)
PFCOUNT key [key ...] # Estimate unique count O(1) per key
PFMERGE destkey sourcekey [sourcekey ...] # Merge HyperLogLogs O(N)
```
## Geospatial
Geospatial commands operate on sorted sets with GEO-specific wrappers.
```
GEOADD key [NX|XX] longitude latitude member [longitude latitude member ...] # Add geo entry
GEOPOS key member [member ...] # Get coordinates O(N)
GEODIST key member1 member2 [m|km|ft|mi] # Distance between two members O(log(N))
GEOHASH key member [member ...] # Get geohash strings O(N)
GEORADIUS key longitude latitude radius m|km|ft|mi [WITHCOORD] [WITHDIST] [WITHHASH] [COUNT count] [ASC|DESC] # [Deprecated 6.2]
GEORADIUSBYMEMBER key member radius m|km|ft|mi [...] # [Deprecated 6.2]
GEOSEARCH key [FROMMEMBER member|FROMLONLAT lon lat] [BYRADIUS radius m|km|ft|mi|BYBOX width height m|km|ft|mi] [ASC|DESC] [COUNT count [ANY]] [WITHCOORD] [WITHDIST] [WITHHASH]
GEOSEARCHSTORE dest key [...] # Store search results O(N)
```
**Note:** `GEORADIUS` and `GEORADIUSBYMEMBER` are deprecated. Use `GEOSEARCH` instead.
## Key Operations
### Debugging
```
DEBUG OBJECT key # Internal debug info (rl:refcount, lru, lru_seconds_idle, etc.) O(1)
DEBUG SEGFAULT # Crash server (debugging only, never in production)
```
`DEBUG OBJECT` returns internal metadata such as reference count, LRU idle time, encoding, and serialized length. Useful for diagnosing memory and eviction issues.
```
EXISTS key [key ...] # Check existence (returns count) O(N) for multi
TYPE key # Data type (string|list|set|zset|hash|stream|none) O(1)
RENAME key newkey # Rename key O(1)
RENAMENX key newkey # Rename if target not exists O(1)
COPY key newkey [DB db] [REPLACE] # Copy key O(N)
DEL key [key ...] # Delete keys O(N)
UNLINK key [key ...] # Async delete (non-blocking) O(1)
TOUCH key [key ...] # Update last access time O(N)
MOVE key db # Move key to another database O(1)
RANDOMKEY # Return a random key O(1)
# Expiry
EXPIRE key seconds [NX|XX|GT|LT] # Set TTL in seconds O(1)
PEXPIRE key milliseconds [NX|XX|GT|LT]# Set TTL in ms O(1)
EXPIREAT key timestamp [NX|XX|GT|LT] # Set expiry at Unix timestamp O(1)
PEXPIREAT key ms-timestamp [NX|XX|GT|LT] # Set expiry at ms-timestamp O(1)
TTL key # Get TTL in seconds (-1=none, -2=not exists) O(1)
PTTL key # Get TTL in ms O(1)
EXPIRETIME key # Expiry as Unix timestamp O(1)
PERSIST key # Remove expiry O(1)
# Object introspection
DUMP key # Serialize value O(N)
RESTORE key ttl serialized-value [REPLACE] [ABSTTL] [IDLETIME sec] [FREQ freq] # Deserialize
OBJECT REFCOUNT key # Reference count O(1)
OBJECT ENCODING key # Internal encoding O(1)
OBJECT IDLETIME key # Seconds since last access O(1)
OBJECT FREQ key # Access frequency (LFU) O(1)
MEMORY USAGE key [SAMPLES count] # Memory in bytes O(N)
SORT key [BY pattern] [LIMIT offset count] [GET pattern [GET pattern ...]] [ASC|DESC] [ALPHA] [STORE dest]
SORT_RO key [BY pattern] [LIMIT offset count] [GET pattern [GET pattern ...]] [ASC|DESC] [ALPHA] # Read-only sort (Redis 7.0+)
```
**Expiry options explained:**
- `NX` — set expiry only if key has no expiry
- `XX` — set expiry only if key already has an expiry
- `GT` — set expiry only if new TTL is greater than current
- `LT` — set expiry only if new TTL is less than current
## Database Operations
```
DBSIZE # Total keys in database O(1)
FLUSHDB [ASYNC|SYNC] # Delete all keys in current DB O(N)
FLUSHALL [ASYNC|SYNC] # Delete all keys in all DBs O(N)
SWAPDB index1 index2 # Swap two databases O(N)
SELECT index # Switch database O(1)
SCAN cursor [MATCH pattern] [COUNT count] [TYPE type] # Incremental key iteration O(1)/call
```
## Transactions
```
MULTI # Start transaction
... commands ...
EXEC # Execute all queued commands
DISCARD # Discard queued commands
WATCH key [key ...] # Watch keys for conditional exec
UNWATCH # Unwatch all keys
```
**Behavioral notes:**
- Commands between `MULTI` and `EXEC` are queued and executed atomically
- If `WATCH` detects changes to watched keys, `EXEC` returns nil (transaction aborted)
- Redis transactions are not rollback-capable — if one command fails, the rest still execute
@@ -0,0 +1,309 @@
# Inspection and Monitoring
## Table of Contents
- [INFO Command](#info-command)
- [Continuous Stats Mode](#continuous-stats-mode)
- [MONITOR Command](#monitor-command)
- [Latency Analysis](#latency-analysis)
- [RDB Backup](#rdb-backup)
- [Replica Mode](#replica-mode)
- [LRU Simulation](#lru-simulation)
- [Slow Log](#slow-log)
## INFO Command
Returns server information and statistics as key-value pairs organized in sections.
```bash
# All default sections
redis-cli INFO
# Specific sections
redis-cli INFO server
redis-cli INFO memory
redis-cli INFO keyspace
redis-cli INFO replication
redis-cli INFO clients
redis-cli INFO stats
redis-cli INFO persistence
redis-cli INFO cpu
redis-cli INFO commandstats
redis-cli INFO latencystats
redis-cli INFO cluster
redis-cli INFO modules
# Multiple sections (Redis 7.0+)
redis-cli INFO memory keyspace
# All sections including hidden ones
redis-cli INFO all
# Everything including debug sections
redis-cli INFO everything
```
### Key INFO Sections
**server** — Redis version, process ID, uptime, architecture, TCP port, config file
**memory** — Used memory, peak memory, fragmentation ratio, total system memory
**keyspace** — Key counts per database (e.g., `db0:keys=1000,expires=50,avg_ttl=3600`)
**clients** — Connected clients, blocked clients, max clients
**replication** — Role (master/replica), connected replicas, replication offset
**stats** — Total connections, commands processed, keyspace hits/misses
**persistence** — RDB/AOF status, last save time, current save progress
**cpu** — User/system CPU time consumed by Redis
### Useful INFO Queries
```bash
# Check memory usage and fragmentation
redis-cli INFO memory | grep -E "used_memory_human|fragmentation_ratio"
# Monitor keyspace changes
redis-cli INFO keyspace
# Check replication health
redis-cli INFO replication | grep -E "role|connected_slaves|master_repl_offset"
# Track hit rate
redis-cli INFO stats | grep -E "keyspace_hits|keyspace_misses"
# Watch specific metric over time
redis-cli -r -1 -i 5 INFO memory | grep used_memory_human
```
## Continuous Stats Mode
Rolling display of server statistics updated every second (configurable with `-i`).
```bash
redis-cli --stat
# Change update interval
redis-cli --stat -i 5 # every 5 seconds
```
Output columns:
```
------- data ------ --------------------- load -------------------- - child -
keys mem clients blocked requests connections
506 1015.00K 1 0 24 (+0) 7
506 1015.00K 1 0 25 (+1) 7
```
- **keys**: Total key count
- **mem**: Memory usage
- **clients**: Connected clients
- **blocked**: Blocked clients
- **requests**: Total processed requests (+delta since last line)
- **connections**: Total connections since startup
The delta in parentheses makes it easy to spot sudden traffic spikes.
## MONITOR Command
Streams all commands processed by the Redis server in real time.
```bash
redis-cli MONITOR
```
Output format:
```
1460100081.165665 [0 127.0.0.1:51706] "set" "shipment:8000736522714:status" "sorting"
1460100083.053365 [0 127.0.0.1:51707] "get" "shipment:8000736522714:status"
```
Fields: `timestamp [db client_addr] "command" "arg1" "arg2" ...`
**Warning:** MONITOR adds significant overhead (each command is also sent to MONITOR clients). Avoid running it for extended periods on busy production servers.
Useful for debugging — pipe through grep to filter:
```bash
redis-cli MONITOR | grep "SET"
redis-cli MONITOR | grep "user:"
```
## Latency Analysis
Redis provides multiple latency tools for different diagnostic scenarios.
### Basic Latency (--latency)
Continuously sends PING and measures round-trip time (100 samples/sec):
```bash
redis-cli --latency
# min: 0, max: 1, avg: 0.19 (427 samples)
```
Stats are in milliseconds. When not in a TTY (or with `--raw`), samples for 1 second then exits with a single output line.
### Latency History (--latency-history)
Same as `--latency` but resets statistics every 15 seconds (configurable):
```bash
redis-cli --latency-history
redis-cli --latency-history -i 30 # 30-second windows
```
### Latency Distribution (--latency-dist)
Color-coded spectrum visualization of latency distribution:
```bash
redis-cli --latency-dist
```
Requires xterm 256-color terminal. Default 1-second interval, change with `-i`.
### Intrinsic Latency (--intrinsic-latency)
Measures the baseline latency of the system (kernel scheduler, hypervisor), not Redis itself.
```bash
# Run ON THE SAME MACHINE as Redis, not remotely
redis-cli --intrinsic-latency 5
```
The argument is the test duration in seconds. Output:
```
Max latency so far: 739 microseconds.
65433042 total runs (avg latency: 0.0764 microseconds).
Worst run took 9671x longer than the average latency.
```
This tells you the minimum achievable latency on this system. Redis cannot outperform this baseline.
### LATENCY Command (Redis Internal)
Redis also tracks slow events internally:
```bash
redis-cli LATENCY LATEST # Latest latency spikes per event
redis-cli LATENCY HISTORY event-name # Time-series data for an event
redis-cli LATENCY GRAPH event-name # ASCII graph of latency over time
redis-cli LATENCY RESET [event ...] # Reset latency data
redis-cli LATENCY DOCTOR # Diagnose latency issues
```
Common event names: `command`, `fork`, `rdb-unlink`, `aof-write`, `aof-fsync-always`.
## RDB Backup
Transfer an RDB dump file from a remote Redis instance to the local machine.
```bash
redis-cli --rdb /tmp/dump.rdb
# SYNC sent to master, writing 13256 bytes to '/tmp/dump.rdb'
# Transfer finished with success.
```
Check exit code for errors:
```bash
redis-cli --rdb /tmp/dump.rdb
echo $? # 0 = success, non-zero = error
```
**Functions-only RDB** (skip key data):
```bash
redis-cli --functions-rdb /tmp/functions.rdb
```
Useful for automated backup scripts and cron jobs. The RDB file can be loaded by any Redis instance.
## Replica Mode
Simulates a replica to inspect the replication stream from a master:
```bash
redis-cli --replica
```
Output shows commands as they are replicated in CSV format:
```
SYNC with master, discarding 13256 bytes of bulk transfer...
SYNC done. Logging commands from master.
"PING"
"SELECT","0"
"SET","last_name","Enigk"
"INCR","mycounter"
```
Useful for debugging replication issues and understanding what data is being sent to replicas.
## LRU Simulation
Simulates cache behavior to help determine the optimal `maxmemory` setting.
```bash
# Simulate 10 million keys with LRU eviction
redis-cli --lru-test 10000000
```
Prerequisites:
- Configure `maxmemory` (e.g., `100mb`) in redis.conf
- Set `maxmemory-policy` to `allkeys-lru`
- **WARNING**: This test uses pipelining and stresses the server — never use on production instances
Output shows hit/miss rates:
```
156000 Gets/sec | Hits: 4552 (2.92%) | Misses: 151448 (97.08%)
153750 Gets/sec | Hits: 12906 (8.39%) | Misses: 140844 (91.61%)
```
Use this to find the right `maxmemory` value for your key count and access pattern (80-20 power law distribution). A miss rate >10% usually means more memory is needed.
## Slow Log
The slow log records commands that exceed a configured execution time threshold. This is the first tool to reach for when debugging unexplained latency.
### Configuration
```bash
# Check current slowlog settings
redis-cli CONFIG GET slowlog*
# slowlog-log-slower-than: threshold in microseconds (negative = disabled)
# slowlog-max-len: maximum number of entries to keep (ring buffer)
redis-cli CONFIG SET slowlog-log-slower-than 10000 # 10ms
redis-cli CONFIG SET slowlog-max-len 128
```
### Querying
```bash
# Get recent slow log entries (default: 10)
redis-cli SLOWLOG GET
redis-cli SLOWLOG GET 20 # Last 20 entries
# Each entry format:
# 1) id — unique entry ID
# 2) timestamp — Unix timestamp
# 3) duration — execution time in microseconds
# 4) command — array: [cmd, arg1, arg2, ...]
# 5) client — client address:port
# 6) client_name — client name (via CLIENT SETNAME)
# Get entry count
redis-cli SLOWLOG LEN
# Reset (clear all entries)
redis-cli SLOWLOG RESET
```
### Useful SLOWLOG Queries
```bash
# Find slowest commands
redis-cli SLOWLOG GET 50 | grep -E "^\d+\)|^\d+\) \(integer\)"
# Monitor slow log continuously
redis-cli -r -1 -i 10 SLOWLOG GET 5
# Combine with LATENCY for deeper analysis
redis-cli LATENCY LATEST
redis-cli SLOWLOG GET 10
```
@@ -0,0 +1,252 @@
# Key Management
## Table of Contents
- [SCAN Family](#scan-family)
- [Built-in Scan Modes](#built-in-scan-modes)
- [Big Keys Analysis](#big-keys-analysis)
- [Memory Usage Analysis](#memory-usage-analysis)
- [Combined Analysis](#combined-analysis-keystats)
- [Hot Keys Detection](#hot-keys-detection)
- [Key Expiration Management](#key-expiration-management)
- [Mass Insertion](#mass-insertion)
## SCAN Family
The SCAN family provides production-safe iteration over collections. Unlike `KEYS *` or `SMEMBERS` which block the server on large datasets, SCAN returns small batches incrementally.
### SCAN Command Reference
| Command | Iterates Over | Syntax |
|---------|--------------|--------|
| `SCAN` | Keys in database | `SCAN cursor [MATCH pattern] [COUNT count] [TYPE type]` |
| `SSCAN` | Members of a Set | `SSCAN key cursor [MATCH pattern] [COUNT count]` |
| `HSCAN` | Fields of a Hash | `HSCAN key cursor [MATCH pattern] [COUNT count] [NOVALUES]` |
| `ZSCAN` | Members of a Sorted Set | `ZSCAN key cursor [MATCH pattern] [COUNT count]` |
### How SCAN Works
1. Start iteration with cursor `0`
2. Each call returns `[new_cursor, [elements...]]`
3. Use `new_cursor` in the next call
4. Iteration is complete when cursor returns `0`
```
# Full iteration example
SCAN 0 MATCH user:* COUNT 100
# Returns: 1) "42" 2) ["user:1", "user:5", "user:23"]
SCAN 42 MATCH user:* COUNT 100
# Returns: 1) "0" 2) ["user:88", "user:91"] ← iteration complete (cursor=0)
```
### SCAN Options
**MATCH pattern** — Glob-style filtering applied *after* retrieval (not server-side filtering):
- `*` matches any sequence
- `?` matches single character
- `[ae]` matches one of the characters
- Important: because MATCH is applied post-retrieval, some iterations may return empty results. Increase `COUNT` to compensate.
**COUNT n** — Hint for number of elements per call (default: 10):
- This is a *hint*, not a guarantee
- For small collections encoded as ziplists/intsets, all elements may be returned in one call regardless of COUNT
- The key space (SCAN) always uses hash tables and respects COUNT more predictably
- You can change COUNT between calls without affecting iteration correctness
**TYPE type** — Filter by data type (SCAN only, Redis 6.0+):
- `SCAN 0 TYPE hash` returns only hash keys
- Type is the same string that `TYPE` command returns: `string`, `list`, `set`, `zset`, `hash`, `stream`
- Like MATCH, this is applied post-retrieval
**NOVALUES** — Return field names only, without values (HSCAN only):
- `HSCAN myhash 0 NOVALUES` returns just field names, saving bandwidth for large hashes
### SCAN Guarantees
A full iteration (cursor 0 → 0) provides:
1. **Completeness**: All elements that existed for the entire duration of the iteration will be returned at least once
2. **No false positives**: Elements that never existed during the iteration are never returned
### SCAN Limitations
- Elements may be returned **multiple times** — handle deduplication in your application
- Elements added or removed during iteration may or may not appear — undefined behavior
- Only valid cursors are `0` (start) or values returned by previous SCAN calls
- An iteration over a collection that grows faster than SCAN progresses may never terminate
### SCAN in Redis Cluster
In cluster mode, SCAN only iterates keys in the current node's slot range. The `--scan` option in redis-cli handles cluster iteration automatically across all nodes.
Pattern matching is optimized for patterns implying a single slot. For example, `{a}h*llo` only scans keys in slot 15495 (hash tag `{a}`).
## Built-in Scan Modes
redis-cli provides built-in scan modes that wrap the SCAN command:
```bash
# List all keys
redis-cli --scan
# Filter by glob pattern
redis-cli --scan --pattern 'user:*'
redis-cli --scan --pattern '*-11*'
# Control batch size
redis-cli --scan --count 100
# Add delay between SCAN calls (reduce server load)
redis-cli --scan --pattern 'user:*' -i 0.01
# Count keys matching a pattern
redis-cli --scan --pattern 'session:*' | wc -l
# Chain with other tools
redis-cli --scan --pattern 'cache:*' | head -20
redis-cli --scan --pattern 'temp:*' | while read key; do redis-cli DEL "$key"; done
```
## Big Keys Analysis
Scans the entire keyspace to find keys with the most elements (complexity-based).
```bash
# Find biggest keys by element count
redis-cli --bigkeys
# Throttle scanning (0.01 sec per 100 SCAN calls)
redis-cli --bigkeys -i 0.01
# Filter by pattern
redis-cli --bigkeys --pattern 'user:*'
```
Output example:
```
# Scanning the entire keyspace...
Biggest list found "bikes:finished" has 1 items
Biggest string found "all_bikes" has 36 bytes
Biggest hash found "bike:1:stats" has 3 fields
Biggest stream found "race:france" has 4 entries
-------- summary -------
Total key length in bytes is 495 (avg len 9.00)
1 lists with 1 items (01.82% of keys, avg size 1.00)
16 strings with 149 bytes (29.09% of keys, avg size 9.31)
```
Reports biggest key per type, percentage of keys per type, and average sizes. Works on cluster replicas.
## Memory Usage Analysis
Scans for keys consuming the most memory.
```bash
# Find keys by memory consumption
redis-cli --memkeys
# With throttling
redis-cli --memkeys -i 0.01
# Custom sample count for nested types
redis-cli --memkeys --memkeys-samples 10
```
Output is similar to `--bigkeys` but reports byte sizes instead of element counts.
## Combined Analysis (--keystats)
Combines `--bigkeys` and `--memkeys` with distribution data.
```bash
redis-cli --keystats
redis-cli --keystats --top 20 # Show top 20 keys
redis-cli --keystats --cursor 12345 # Resume from a previous scan
redis-cli --keystats -i 0.01 # Throttled
```
Output includes:
- Top N key sizes ranked by memory
- Biggest key per type (by size and by element count)
- Percentile distribution of key sizes
- Per-type statistics (total keys, percentage, total size, average size)
## Hot Keys Detection
Identifies frequently accessed keys. Requires `maxmemory-policy` to be set to an LFU variant.
```bash
redis-cli --hotkeys
```
## Key Expiration Management
### Setting Expiry
```bash
# Set TTL in seconds
redis-cli EXPIRE mykey 3600
# Set TTL in milliseconds
redis-cli PEXPIRE mykey 5000
# Set expiry at specific Unix timestamp
redis-cli EXPIREAT mykey 1735689600
# Conditional expiry (Redis 7.0+)
redis-cli EXPIRE mykey 3600 NX # Only if no current expiry
redis-cli EXPIRE mykey 3600 XX # Only if already has expiry
redis-cli EXPIRE mykey 3600 GT # Only if new TTL > current TTL
redis-cli EXPIRE mykey 3600 LT # Only if new TTL < current TTL
```
### Checking Expiry
```bash
redis-cli TTL mykey # Seconds remaining (-1=none, -2=not exists)
redis-cli PTTL mykey # Milliseconds remaining
redis-cli EXPIRETIME mykey # Unix timestamp of expiry
```
### Removing Expiry
```bash
redis-cli PERSIST mykey # Make key permanent
```
### Hash Field Expiry (Redis 7.4+)
```bash
redis-cli HEXPIRE myhash 3600 FIELDS 2 field1 field2
redis-cli HTTL myhash 2 field1 field2
redis-cli HPERSIST myhash FIELDS 2 field1 field2
```
### Expiry Behavior
- Setting a key with `SET`, `GETSET`, or `*STORE` commands clears any existing TTL
- `DEL`, `RENAME`, and `MOVE` transfer or clear the TTL
- `EXPIRE` on a key with existing TTL updates the timeout
- Expired keys are deleted lazily or actively sampled (~10 times/sec, random sample of 20 keys)
## Mass Insertion
For bulk loading data into Redis, use the pipe mode which is significantly faster than individual commands.
```bash
# Generate Redis protocol from data and pipe it
cat data.txt | redis-cli --pipe
# With custom timeout (default 30 seconds)
cat data.txt | redis-cli --pipe --pipe-timeout 60
# The input file must use Redis protocol format:
# *<args>\r\n$<len>\r\n<arg>\r\n...
#
# Example for SET key value:
# *3\r\n$3\r\nSET\r\n$3\r\nkey\r\n$5\r\nvalue\r\n
```
See the [official mass insertion guide](https://redis.io/docs/latest/develop/clients/patterns/bulk-loading/) for generating protocol files from CSV or other data sources.
@@ -0,0 +1,429 @@
# Module Data Types
Commands for Redis module data types: JSON, Vector Sets, Probabilistic data structures, TimeSeries, and Full-Text Search (RediSearch).
## Table of Contents
- [JSON (RedisJSON Module)](#json-redisjson-module)
- [Vector Sets (Redis 8.0+)](#vector-sets-redis-80)
- [Bloom Filter](#bloom-filter)
- [Cuckoo Filter](#cuckoo-filter)
- [Top-K](#top-k)
- [Count-Min Sketch](#count-min-sketch)
- [T-Digest](#t-digest)
- [TimeSeries](#timeseries)
- [Full-Text Search (RediSearch)](#full-text-search-redisearch)
## JSON (RedisJSON Module)
```
JSON.SET key $ value [NX|XX] # Set JSON value at path
JSON.GET key [path [path ...]] # Get JSON value
JSON.MGET key [key ...] $ # Multi-get
JSON.DEL key [path] # Delete JSON value
JSON.TYPE key [path] # Get type at path
JSON.STRLEN key [path] # String length
JSON.OBJLEN key [path] # Object key count
JSON.OBJKEYS key [path] # Object keys
JSON.ARRLEN key [path] # Array length
JSON.ARRAPPEND key path value [...] # Append to array
JSON.ARRPOP key [path [index]] # Pop from array
JSON.ARRINSERT key path index value [...] # Insert into array
JSON.ARRINDEX key path value [start [stop]] # Find index of value
JSON.ARRTRIM key path start stop # Trim array to range
JSON.NUMINCRBY key path value # Increment number
JSON.NUMMULTBY key path value # Multiply number
JSON.STRAPPEND key [path] value # Append to string
JSON.STRLEN key [path] # String length
JSON.CLEAR key [path] # Clear container (array/object)
JSON.FORGET key [path] # Alias for JSON.DEL
JSON.MSET key path value [key path value ...] # Multi-set
JSON.TOGGLE key [path] # Toggle boolean value
JSON.MERGE key path value # Merge JSON
JSON.RESP key [path] # Get as RESP protocol
```
## Vector Sets (Redis 8.0+)
Vector sets store elements with associated vectors and support approximate nearest neighbor (ANN) similarity search using an HNSW (Hierarchical Navigable Small World) graph. Ideal for semantic search, recommendation systems, and AI embedding storage.
```
# Write
VADD key [REDUCE dim] (FP32 | VALUES num) vector element [CAS] [NOQUANT|Q8|BIN] [EF ef] [SETATTR json] [M numlinks]
# Add element with vector O(log(N))
VREM key element # Remove element O(log(N))
# Similarity search
VSIM key (ELE | FP32 | VALUES num) (vector | element) [WITHSCORES] [WITHATTRIBS] [COUNT n]
[EPSILON delta] [EF ef] [FILTER expr] [FILTER-EF max] [TRUTH] [NOTHREAD]
# Find similar elements O(log(N))
# Read
VEMB key element [RAW] # Get vector for element O(1)
VRANGE key start end [count] # Lexicographic range iteration O(log(K)+M)
VCARD key # Element count O(1)
VDIM key # Vector dimensionality O(1)
VISMEMBER key element # Check element exists O(1)
VLINKS key element [WITHSCORES] # HNSW graph neighbors O(1)
VRANDMEMBER key [count] # Random element(s) O(N)
VSETATTR key element "{ json }" # Set JSON attributes O(1)
VGETATTR key element # Get JSON attributes O(1)
VINFO key # Vector set metadata O(1)
```
**VADD vector input:**
- `VALUES 3 0.1 1.2 0.5 my-element` — string floats, platform-independent
- `FP32 <blob> my-element` — binary 32-bit float blob, must be little-endian
**VADD quantization options** (mutually exclusive, set on first VADD):
- `NOQUANT` — no quantization, full precision (most memory)
- `Q8` — signed 8-bit int quantization (default, good balance)
- `BIN` — binary quantization (fastest, least memory, lower recall)
**VSIM input modes:**
- `ELE element` — search by existing element in the set
- `VALUES num v1 v2 ...` — search by float vector
- `FP32 <blob>` — search by binary vector
**VSIM key options:**
- `WITHSCORES` — include similarity score (1 = identical, 0 = opposite)
- `WITHATTRIBS` — include JSON attributes for each result
- `COUNT n` — limit results (default 10)
- `EPSILON delta` — only return elements with distance < delta (similarity > 1-delta)
- `EF ef` — search exploration factor (higher = better recall, slower)
- `FILTER expr` — filter by attribute expression (e.g., `".year > 2020"`)
- `TRUTH` — exact linear scan (O(N)), for benchmarking recall quality
**VRANGE iteration** (Redis 8.4+):
Stateless lexicographic iteration. `start`/`end` use `[` inclusive, `(` exclusive, `-` min, `+` max:
```
VRANGE mykey - + 10 # First 10 elements
VRANGE mykey (last + 10 # Next 10 after "last"
VRANGE mykey - + -1 # All elements (caution: may be slow)
```
## Bloom Filter
Probabilistic data structure for membership testing. Returns "possibly in set" or "definitely not in set". Space-efficient with a configurable false-positive rate.
```
# Create with custom parameters (optional — auto-created on first ADD)
BF.RESERVE key error_rate capacity [EXPANSION expansion] [NONSCALING]
# Write
BF.ADD key item # Add single item O(k)
BF.MADD key item [item ...] # Add multiple items O(k*n)
# Query
BF.EXISTS key item # Check if item exists O(k)
BF.MEXISTS key item [item ...] # Check multiple items O(k*n)
# Info
BF.INFO key # Filter metadata (capacity, size, expansion, etc.)
# Persistence
BF.SCANDUMP key iter # Incremental dump (iter 0 = start)
BF.LOADCHUNK key iter data # Incremental restore
```
**Behavioral notes:**
- `BF.ADD` returns 1 if item was added (new), 0 if it may already exist (false positive on EXISTS doesn't mean it was added)
- Bloom filters can produce false positives but never false negatives
- `BF.RESERVE` lets you control the error rate and capacity upfront; without it, defaults are used
- Use `BF.SCANDUMP`/`BF.LOADCHUNK` for incremental backup/restore of large filters
## Cuckoo Filter
Alternative to Bloom filters with the additional ability to delete items and count occurrences. Supports "definitely in set" or "possibly not in set" semantics.
```
# Create (optional — auto-created on first ADD)
CF.RESERVE key capacity [BUCKETSIZE bucketsize] [MAXITERATIONS maxiterations] [EXPANSION expansion]
# Write
CF.ADD key item # Add item O(k+i)
CF.ADDNX key item # Add only if not exists O(k+i)
# Delete
CF.DEL key item # Delete item O(k+i)
# Query
CF.EXISTS key item # Check if item exists O(k+i)
CF.MEXISTS key item [item ...] # Check multiple items O(k*n)
# Count
CF.COUNT key item # Count occurrences O(k+i)
# Info
CF.INFO key # Filter metadata
# Persistence
CF.SCANDUMP key iter # Incremental dump
CF.LOADCHUNK key iter data # Incremental restore
```
**Behavioral notes:**
- Unlike Bloom filters, Cuckoo filters support deletion (`CF.DEL`)
- Cuckoo filters can contain the same item multiple times
- `CF.ADD` always succeeds (allows duplicates); use `CF.ADDNX` for unique inserts
- `CF.COUNT` returns the number of times an item was added (subject to false positives)
## Top-K
Tracks the K most frequent elements in a data stream. Useful for heavy-hitter detection and trending items.
```
# Create (required before use)
TOPK.RESERVE key topk [width depth decay]
# Write
TOPK.ADD key item [item ...] # Add items, returns expelled items if any O(n*k)
# Query
TOPK.QUERY key item [item ...] # Check if items are in top-K O(n)
TOPK.COUNT key item [item ...] # Get estimated counts O(n)
TOPK.LIST key # Return full top-K list O(k)
TOPK.INCRBY key item count [item count ...] # Increment item counts O(n*k)
# Info
TOPK.INFO key # Sketch metadata (k, width, depth, decay)
```
**Behavioral notes:**
- `TOPK.RESERVE` parameters: `topk` = number of top elements to track, `width`/`depth` = sketch dimensions, `decay` = probability decay
- `TOPK.ADD` returns the expelled element for each addition that enters the top-K, or nil
- Results are approximate — items in the top-K list are not guaranteed to be the actual top-K
## Count-Min Sketch
Estimates item frequencies in a data stream with configurable accuracy. Useful for counting occurrences without storing every item.
```
# Create (required before use, two methods)
CMS.INITBYDIM key width depth # Create by explicit dimensions
CMS.INITBYPROB key error_rate probability # Create by error/probability targets
# Write
CMS.INCRBY key item increment [item increment ...] # Increment counts O(n)
# Query
CMS.QUERY key item [item ...] # Get estimated counts O(n)
# Info
CMS.INFO key # Sketch metadata (width, depth, total)
# Merge
CMS.MERGE destkey numkeys key [key ...] [WEIGHTS weight [weight ...]] # Merge sketches
```
**Behavioral notes:**
- `CMS.INITBYPROB` is preferred — specify desired `error_rate` (accuracy) and `probability` (confidence)
- `CMS.QUERY` returns overestimates (never underestimates) — the count includes false positives from hash collisions
- `CMS.MERGE` combines multiple sketches; useful for aggregating distributed counters
## T-Digest
Estimates quantiles (percentiles) from a data stream. Useful for latency percentiles, value distributions, and histogram analysis.
```
# Create (required before use)
TDIGEST.CREATE key [COMPRESSION compression]
# Write
TDIGEST.ADD key value [value ...] # Add observations O(N)
# Quantile queries
TDIGEST.QUANTILE key quantile [quantile ...] # Value at quantile(s) O(log(N))
TDIGEST.CDF key value [value ...] # CDF: P(X <= value) O(log(N))
# Rank queries
TDIGEST.RANK key value [value ...] # Approximate rank O(log(N))
TDIGEST.REVRANK key value [value ...] # Reverse rank O(log(N))
TDIGEST.BYRANK key rank [rank ...] # Value at rank O(log(N))
TDIGEST.BYREVRANK key rank [rank ...] # Value at reverse rank O(log(N))
# Statistics
TDIGEST.MIN key # Minimum value O(1)
TDIGEST.MAX key # Maximum value O(1)
TDIGEST.TRIMMED_MEAN key low high # Mean of values between quantiles O(N)
# Management
TDIGEST.INFO key # Sketch metadata (capacity, merged/unmerged nodes, total weight)
TDIGEST.MERGE destkey numkeys key [key ...] # Merge sketches O(N)
TDIGEST.RESET key # Reset to empty O(1)
```
**Behavioral notes:**
- `COMPRESSION` controls accuracy vs memory (default: 100, higher = more accurate)
- `TDIGEST.QUANTILE 0.5` returns the approximate median
- `TDIGEST.CDF` returns the fraction of observations <= the given value
- After `TDIGEST.MERGE`, the destination sketch provides quantile estimates over the combined data
## TimeSeries
Store and query time series data (sensor readings, metrics, financial data). Timestamps are 64-bit integers in milliseconds. Supports aggregation, compaction rules, and label-based filtering.
```
# Create
TS.CREATE key [RETENTION ms] [ENCODING COMPRESSED|UNCOMPRESSED] [CHUNK_SIZE bytes]
[DUPLICATE_POLICY BLOCK|FIRST|LAST|MIN|MAX|SUM]
[IGNORE maxTimeDiff maxValDiff]
[LABELS label value ...] # O(1)
# Write
TS.ADD key timestamp value [RETENTION ms] [ON_DUPLICATE policy] # O(1), creates series if missing
[LABELS label value ...]
# timestamp: Unix ms, or * for server time
TS.MADD key timestamp value [key timestamp value ...] # O(N), batch add
TS.INCRBY key value [TIMESTAMP ts] [RETENTION ms] [LABELS ...] # O(1), counter/gauge
TS.DECRBY key value [TIMESTAMP ts] [RETENTION ms] [LABELS ...] # O(1), decrement
# Single-series query
TS.GET key [LATEST] # Latest sample O(1)
TS.RANGE key from to [LATEST] [FILTER_BY_TS ts...] # Range query O(n/m+k)
[FILTER_BY_VALUE min max] [COUNT n]
[ALIGN align] [AGGREGATION fn bucketDuration]
[BUCKETTIMESTAMP bt] [EMPTY]
TS.REVRANGE key from to [...] # Same, descending order
# Multi-series query (filter by labels)
TS.MGET [LATEST] [WITHLABELS | SELECTED_LABELS lbl...] # Latest from each series O(N)
FILTER label=value [...]
TS.MRANGE from to [LATEST] [FILTER_BY_TS ts...] # Range across series O(n/m+k)
[FILTER_BY_VALUE min max] [WITHLABELS | SELECTED_LABELS lbl...]
[COUNT n] [ALIGN align] [AGGREGATION fn bucketDuration]
FILTER label=value [...] [GROUPBY label REDUCE reducer]
TS.MREVRANGE from to [...] # Same, descending order
# Index
TS.QUERYINDEX filterExpr... # List keys by labels O(N)
# Compaction rules
TS.CREATERULE source dest AGGREGATION fn bucketDuration # O(1), dest must exist
TS.DELETERULE source dest # O(1)
# Management
TS.ALTER key [RETENTION ms] [LABELS label value ...] # O(1)
TS.INFO key # Series metadata O(1)
TS.DEL key from to # Delete range O(N)
```
**Aggregation functions:** `AVG`, `SUM`, `MIN`, `MAX`, `RANGE`, `COUNT`, `FIRST`, `LAST`, `STD.P`, `STD.S`, `VAR.P`, `VAR.S`, `TWA` (time-weighted avg), `countNaN`, `countAll` (Redis 8.6+)
**Timestamps:** Use `-` for earliest, `+` for latest in range queries.
**Label filter syntax:** `label=value` (exact), `label!=(value1,value2)` (exclude), `label=(v1,v2)` (OR), `label=` (exists). Filters are conjunctive (AND).
**DUPLICATE_POLICY** (on TS.CREATE): How to handle duplicate timestamps:
- `BLOCK` — reject duplicate (default)
- `FIRST` — keep first value
- `LAST` — keep latest value
- `MIN` / `MAX` / `SUM` — aggregate
**Compaction:** `TS.CREATERULE` automatically computes aggregation as data arrives. Only data added *after* rule creation is processed. Destination key must already exist.
## Full-Text Search (RediSearch)
Full-text search, secondary indexing, and aggregation over Redis hashes and JSON documents.
```
# Index management
FT.CREATE index [ON HASH|JSON] [PREFIX count prefix...]
[FILTER filter] [LANGUAGE lang] [TEMPORARY seconds]
[NOOFFSETS] [NOHL] [NOFIELDS] [NOFREQS]
[STOPWORDS count word...]
[SKIPINITIALSCAN]
SCHEMA field [AS alias] TEXT|TAG|NUMERIC|GEO|VECTOR|GEOSHAPE
[SORTABLE [UNF]] [NOINDEX] [...] # O(K) create, O(N) scan
FT.ALTER index [SKIPINITIALSCAN] SCHEMA ADD field ... # Add fields O(N)
FT.INFO index # Index stats O(1)
FT.DROPINDEX index [DD] # Drop index (DD=del docs) O(1)/O(N)
# Aliases
FT.ALIASADD alias index # Create alias O(1)
FT.ALIASDEL alias # Remove alias O(1)
FT.ALIASUPDATE alias index # Point alias to index O(1)
# Search
FT.SEARCH index query [NOCONTENT] [VERBATIM] [WITHSCORES] # O(N) for single-word
[FILTER field min max ...] [GEOFILTER field lon lat radius unit]
[RETURN count field [AS name] ...]
[SUMMARIZE [FIELDS count field...] [FRAGS n] [LEN n] [SEPARATOR s]]
[HIGHLIGHT [FIELDS count field...] [TAGS open close]]
[SLOP slop] [INORDER] [LANGUAGE lang] [EXPANDER exp]
[SCORER scorer] [EXPLAINSCORE] [PAYLOAD payload]
[SORTBY field [ASC|DESC]] [LIMIT offset count]
[PARAMS nargs name value ...] [DIALECT dialect]
[TIMEOUT ms]
# Aggregation pipeline
FT.AGGREGATE index query [VERBATIM] # Non-deterministic
[LOAD count field ...] [TIMEOUT ms]
[GROUPBY nargs prop... [REDUCE fn nargs arg... [AS name]]...]
[SORTBY nargs prop [ASC|DESC]... [MAX n]]
[APPLY expression AS name]...
[LIMIT offset count] [FILTER filter]
[WITHCURSOR [COUNT n] [MAXIDLE ms]]
[PARAMS nargs name value ...] [DIALECT dialect]
# Dictionary
FT.DICTADD dict word [word ...] # Add words O(1)
FT.DICTDEL dict word [word ...] # Remove words O(1)
FT.DICTDUMP dict # List words O(N)
# Synonyms
FT.SYNUPDATE index groupid [SKIPINITIALSCAN] term [term ...] # O(1)
FT.SYNDUMP index # O(N)
# Suggestions
FT.SUGADD key string score [INCR] [PAYLOAD payload] # O(1)
FT.SUGGET key prefix [FUZZY] [WITHSCORES] [WITHPAYLOADS] # O(n)
[MAX num] [DIALECT dialect]
FT.SUGDEL key string # O(1)
FT.SUGLEN key # O(1)
# Other
FT._LIST # List all indexes O(N)
FT.TAGVALS index field # Distinct tag values O(N)
FT.PROFILE index query [LIMITED] [DIALECT dialect] # Query profiling
FT.EXPLAIN index query [DIALECT dialect] # Show query execution plan
FT.SPELLCHECK index query [DISTANCE d] [DIALECT dialect] # Spell check
FT.CONFIG SET key value # Set runtime config
FT.CONFIG GET key # Get runtime config
# Cursors (for paginated FT.AGGREGATE)
FT.CURSOR READ index cursor [COUNT count] # Read next page
FT.CURSOR DEL index cursor # Delete cursor
```
**FT.CREATE field types:**
- `TEXT` — full-text searchable, supports stemming, phonetic matching
- `TAG` — exact match labels (categories, IDs)
- `NUMERIC` — range queries (prices, timestamps)
- `GEO` — geographic coordinates (lon, lat)
- `VECTOR` — vector similarity (KNN, cosine/L2/IP)
- `GEOSHAPE` — geometric shapes (SPHERICAL|FLAT)
**Query syntax (DIALECT 2+):**
- `hello world` — union (OR) of terms
- `"hello world"` — exact phrase
- `@field:term` — field-specific search
- `@price:[100 200]` — numeric range
- `@location:[-122.41 37.77 5 km]` — geo radius
- `*=>[KNN 10 @vec $blob]` — vector similarity (KNN)
- `-term` — exclude term
- `~term` — optional term
- `*` — match all documents
**FT.AGGREGATE pipeline stages:** `GROUPBY` + `REDUCE``SORTBY``APPLY``LIMIT``FILTER`. Available reducers: `COUNT`, `SUM`, `MIN`, `MAX`, `AVG`, `COUNT_DISTINCT`, `COUNT_DISTINCTISH`, `QUANTILE`, `STDDEV`, `FIRST_VALUE`, `RANDOM_SAMPLE`, `TOLIST`.
**Behavioral notes:**
- Use `DIALECT 2+` for vector queries and modern query syntax
- `FT.SEARCH` returns `[total_count, doc_id, field, value, ...]` array
- Without `SORTBY`, pagination (`LIMIT`) results are non-deterministic
- `FT.CREATE` with `PREFIX` auto-indexes matching keys; new keys are indexed on write
- In cluster mode, index and documents must be on the same shard (use hash tags)
- `SORTABLE` fields increase memory usage but enable fast sorting
- Maximum 1024 fields per index, 128 TEXT fields
@@ -0,0 +1,366 @@
# Server Administration
## Table of Contents
- [ACL Management](#acl-management)
- [Client Management](#client-management)
- [Configuration](#configuration)
- [Replication Acknowledgment](#replication-acknowledgment)
- [Persistence](#persistence)
- [Replication](#replication)
- [Server Lifecycle](#server-lifecycle)
## ACL Management
Redis ACL (Access Control List) controls which clients can execute which commands and access which keys. Available since Redis 6.0.
### User Management
```bash
# Create/modify user with rules
redis-cli ACL SETUSER username [rule ...]
# Delete user
redis-cli ACL DELUSER username [username ...]
# List all users
redis-cli ACL LIST
# Get detailed user info
redis-cli ACL GETUSER username
# Show current authenticated user
redis-cli ACL WHOAMI
```
### ACL Rules
Rules are applied left-to-right and cumulative (unless using `reset`):
```
# Enable/disable user
on # Enable user
off # Disable user (default for new users)
reset # Remove all rules (clean slate)
# Password
>password # Add password (SHA256 hash stored)
<password # Remove password
#password # Add SHA256 hash directly
# Command permissions
+command # Allow specific command
-command # Deny specific command
+@category # Allow command category (e.g., +@string, +@read)
-@category # Deny command category
+@all # Allow all commands
-@all # Deny all commands (default)
+|command # Allow command with subcommand (e.g., +|config|get)
# Key permissions
~pattern # Allow key pattern (~* = all keys, default: nothing)
%R~pattern # Read permission on pattern
%W~pattern # Write permission on pattern
~RW~pattern # Read+Write permission (same as ~pattern)
allkeys # Alias for ~*
# Pub/Sub channel permissions (Redis 6.2+)
&pattern # Allow channel pattern
allchannels # Allow all channels
# Selectors (Redis 7.0+) — independent permission sets
(+command ~pattern) # Additional permission scope
```
### ACL SETUSER Examples
```bash
# Create admin user
redis-cli ACL SETUSER admin on >strongpassword ~* +@all
# Create read-only user
redis-cli ACL SETUSER readonly on >password ~* +@read -@all
# Create user with limited key access
redis-cli ACL SETUSER app1 on >password ~app1:* +@read +@string +@hash -@all
# Reset user completely and redefine
redis-cli ACL SETUSER myuser reset on >newpass ~cache:* +@read +get +set
# User with selectors (Redis 7.0+)
redis-cli ACL SETUSER multi on +GET allkeys (+SET ~app1:*)
```
### ACL Maintenance
```bash
# Dry-run: check if user can execute command
redis-cli ACL DRYRUN username command [arg ...]
# Generate random password
redis-cli ACL GENPASS [bits] # Default 256 bits
# Save ACLs to config file
redis-cli ACL SAVE
# Load ACLs from config file
redis-cli ACL LOAD
# View ACL audit log
redis-cli ACL LOG [count]
redis-cli ACL LOG RESET # Clear log
# List command categories
redis-cli ACL CAT [category] # Without arg: list categories
```
## Client Management
### Client Information
```bash
# List all connected clients
redis-cli CLIENT LIST [TYPE normal|master|replica|pubsub] [ID id [id ...]]
# Get info about current connection
redis-cli CLIENT INFO
# Get current client ID
redis-cli CLIENT ID
# Get client name
redis-cli CLIENT GETNAME
```
`CLIENT LIST` output fields include: `id`, `addr`, `laddr`, `fd`, `name`, `age`, `idle`, `flags`, `db`, `sub`, `psub`, `ssub`, `multi`, `qbuf`, `qbuf-free`, `argv-mem`, `multi-mem`, `obl`, `oll`, `omem`, `tot-mem`, `cmds`, `redir`, `user`, `resp`, `lib-name`, `lib-ver`, `watch`, `io-thread`.
### Client Control
```bash
# Set client name (for identification in CLIENT LIST)
redis-cli CLIENT SETNAME my-app-worker
# Disconnect client
redis-cli CLIENT KILL ADDR ip:port
redis-cli CLIENT KILL ID client-id
redis-cli CLIENT KILL TYPE normal|master|replica|pubsub
redis-cli CLIENT KILL USER username
redis-cli CLIENT KILL SKIPME yes|no # Skip current connection
redis-cli CLIENT KILL LADDR ip:port # Kill by local address
redis-cli CLIENT KILL MAXAGE max-age # Kill connections older than max-age seconds
# Pause/unpause all clients
redis-cli CLIENT PAUSE timeout [WRITE|ALL] # Milliseconds
redis-cli CLIENT UNPAUSE
# Unblock a client blocked on blocking command
redis-cli CLIENT UNBLOCK client-id [TIMEOUT|ERROR]
```
### Client Tracking (Server-assisted Client Caching, Redis 6.0+)
```bash
# Enable tracking
redis-cli CLIENT TRACKING ON [REDIRECT client-id] [PREFIX prefix [prefix ...]] [BCAST] [OPTIN] [OPTOUT] [NOLOOP]
# Disable tracking
redis-cli CLIENT TRACKING OFF
# Get tracking info
redis-cli CLIENT TRACKINGINFO
# Opt-in/out caching control
redis-cli CLIENT CACHING YES|NO
```
### Client Settings
```bash
# Set client info metadata
redis-cli CLIENT SETINFO LIB-NAME my-client
redis-cli CLIENT SETINFO LIB-VER 1.0.0
# No-touch mode (skip key last-access-time update)
redis-cli CLIENT NO-TOUCH ON|OFF
# No-evict mode (reject eviction during client operations)
redis-cli CLIENT NO-EVICT ON|OFF
```
## Configuration
### Reading Configuration
```bash
# Get specific parameter
redis-cli CONFIG GET maxmemory
# Get with glob patterns (Redis 7.0+ supports multiple)
redis-cli CONFIG GET *max*
redis-cli CONFIG GET maxmemory *timeout*
# Get all configuration
redis-cli CONFIG GET '*'
```
### Modifying Configuration
```bash
# Set parameter at runtime
redis-cli CONFIG SET maxmemory 100mb
redis-cli CONFIG SET maxmemory-policy allkeys-lru
redis-cli CONFIG SET timeout 300
# Set multiple parameters in one call (Redis 7.0+)
redis-cli CONFIG SET maxmemory 100mb maxmemory-policy allkeys-lru
# Write current config to redis.conf
redis-cli CONFIG REWRITE
```
Common runtime parameters:
```
maxmemory # Max memory (e.g., 100mb, 1gb, 0 = unlimited)
maxmemory-policy # Eviction: allkeys-lru, volatile-lru, allkeys-lfu, etc.
timeout # Client idle timeout (seconds, 0 = disabled)
save # RDB save schedule (e.g., "900 1 300 10 60 10000")
appendonly # AOF persistence: yes|no
appendfsync # AOF sync: always|everysec|no
notify-keyspace-events # Keyspace notifications (e.g., "Ex" for expired events)
```
### Reset Statistics
```bash
redis-cli CONFIG RESETSTAT # Reset INFO statistics counters
```
## Replication Acknowledgment
### WAIT
Block until write commands are confirmed by the specified number of replicas.
```bash
# Wait for 2 replicas to confirm, up to 5 seconds
redis-cli SET mykey myvalue
redis-cli WAIT 2 5000
# Returns: number of replicas that confirmed (integer)
# Fire and forget (don't wait)
redis-cli WAIT 0 0
```
Useful for ensuring data durability across replicas before proceeding. The count reflects replicas that acknowledged writes up to the moment WAIT was issued.
### WAITAOF (Redis 7.2+)
Block until writes are confirmed as fsynced to AOF on local and/or replica nodes.
```bash
# Wait for local fsync + 1 replica AOF confirmation, up to 5 seconds
redis-cli WAITAOF 1 1 5000
# Returns: local:aof_fsynced, replicated:aof_fsynced_count
```
Parameters:
- `numlocal` — required local AOF fsync count (0 = don't wait for local)
- `numreplicas` — required replica AOF fsync count (0 = don't wait for replicas)
- `timeout` — milliseconds (0 = wait forever)
## Persistence
### RDB Snapshots
```bash
# Background save (non-blocking, forks a child process)
redis-cli BGSAVE
# Background saving started
# Synchronous save (blocks the server — avoid in production)
redis-cli SAVE
# Check last save time
redis-cli LASTSAVE
# (integer) 1735689600
# Check save progress
redis-cli INFO persistence | grep rdb_last_save_time
```
### AOF Persistence
```bash
# Rewrite AOF in background (compact the append-only file)
redis-cli BGREWRITEAOF
# Background append only file rewriting started
# Check AOF status
redis-cli INFO persistence | grep aof_enabled
# Force AOF rewrite via config
redis-cli CONFIG SET appendonly yes
redis-cli CONFIG SET appendfsync everysec # always|everysec|no
```
### Persistence Configuration
```bash
# RDB save schedule: save after N seconds if at least M keys changed
redis-cli CONFIG GET save
redis-cli CONFIG SET save "900 1 300 10 60 10000"
# AOF settings
redis-cli CONFIG GET appendonly
redis-cli CONFIG GET appendfsync
redis-cli CONFIG GET auto-aof-rewrite-percentage
```
## Replication
### Configure Replication
```bash
# Make current instance a replica of another Redis
redis-cli REPLICAOF host port
# OK
# Promote replica back to master
redis-cli REPLICAOF NO ONE
# OK
# Check replication status
redis-cli INFO replication
redis-cli ROLE
```
### Replication Info
```bash
redis-cli INFO replication | grep -E "role|connected_slaves|master_repl_offset"
```
## Server Lifecycle
### Shutdown
```bash
# Save and shutdown (blocks until complete)
redis-cli SHUTDOWN NOSAVE|SAVE
# Shutdown with save (default if not specified)
redis-cli SHUTDOWN SAVE
# Shutdown without saving
redis-cli SHUTDOWN NOSAVE
# Check if server is responding
redis-cli PING
```
### Failover (Redis 7.0+)
```bash
# Coordinated failover via sentinel-like mechanism
redis-cli FAILOVER [TO host port [FORCE]] [ABORT] [TIMEOUT milliseconds]
```