On this page

Redis Cheat Sheet

Quick reference for Redis data types, essential commands, common patterns, Lua scripting, and cluster operations.

Deep dive: Redis Internals | Redis Caching Patterns | Redis Streams

Redis, Valkey and licensing (as of late 2026)

  • Redis 7.4 (March 2024) moved from BSD to a dual RSALv2 / SSPLv1 licence. Redis 8.0 (May 2025) added AGPLv3 as a third option and folded the former Stack modules (JSON, Query Engine/Search, time series, Bloom and other probabilistic types) into "Redis Open Source".
  • Valkey is the Linux Foundation fork of Redis 7.2.4 (BSD-3), backed by AWS, Google, Oracle and others. It is wire- and command-compatible with Redis 7.2, and its 8.x/9.x lines add their own features (multi-threaded I/O improvements, per-slot cluster stats, numbered databases in cluster mode in 9.0). Managed services such as ElastiCache and Memorystore offer Valkey.
  • Everything on this sheet works on both unless marked Redis 7.4+ / 8.0+ (features added after the fork, which Valkey may implement differently or not at all).

Connection & Server

CommandDescription
redis-cliConnect to local Redis
redis-cli -h host -p 6379 -a passwordConnect with auth (visible in ps and shell history; prefer the next two)
REDISCLI_AUTH=secret redis-cli -h hostPassword via env var
redis-cli --user app --askpassACL user, prompt for password
redis-cli -u redis://user:pass@host:6379/0Connect with a URI (rediss:// for TLS)
redis-cli --tlsConnect with TLS
PINGTest connection (returns PONG)
AUTH passwordAuthenticate (as the default user)
AUTH username passwordAuthenticate as an ACL user (6.0+)
HELLO 3Switch the connection to RESP3 protocol
SELECT 0Switch to database 0
DBSIZENumber of keys in current DB
INFOServer info and stats
INFO memoryMemory usage details
INFO keyspaceKeys per database
CONFIG GET maxmemoryGet config value
CONFIG SET maxmemory 1gbSet config at runtime
MONITORReal-time command stream (debug only)
SLOWLOG GET 10Last 10 slow commands
CLIENT LISTConnected clients
FLUSHDBDelete all keys in current DB
FLUSHALLDelete all keys in all DBs
FLUSHALL ASYNCSame, freeing memory in a background thread
INFO commandstatsCalls and latency per command
LATENCY DOCTORHuman-readable latency analysis
CONFIG REWRITEPersist CONFIG SET changes to redis.conf
CLIENT KILL ID 42Disconnect a client
CLIENT NO-EVICT onExempt this connection from client eviction (7.0+)
redis-cli --bigkeys / --memkeysFind the largest keys (sampled with SCAN)
redis-cli --hotkeysMost-accessed keys (needs an LFU eviction policy)
redis-cli --latency / --latency-historyMeasure round-trip latency
redis-cli --statRolling stats every second
redis-cli --scan --pattern 'user:*'List keys safely (SCAN under the hood)

Data Types & Commands

Strings

The simplest type. Stores text, numbers, or binary data up to 512 MB.

SET key "value"                  -- Set a key
SET key "value" EX 3600          -- Set with 1 hour TTL
SET key "value" NX               -- Set only if not exists
SET key "value" XX               -- Set only if exists
SET key "value" PX 500           -- TTL in milliseconds
SET key "value" KEEPTTL          -- Overwrite but keep the existing TTL (6.0+)
SET key "new" GET                -- Set and return old value (6.2+; replaces GETSET)
SET key "value" NX GET           -- NX combined with GET (7.0+)
SETNX key "value"                -- Set if not exists (deprecated: use SET ... NX)
MSET k1 "v1" k2 "v2"            -- Set multiple
MSETNX k1 "v1" k2 "v2"          -- Set multiple only if none exist
GET key                          -- Get value
MGET k1 k2 k3                   -- Get multiple
GETSET key "new"                 -- Set and return old value (deprecated since 6.2: use SET key "new" GET)
GETDEL key                       -- Get and delete (6.2+)
GETEX key EX 60                  -- Get and change TTL (6.2+; PERSIST to remove it)
INCR counter                     -- Increment by 1
INCRBY counter 5                 -- Increment by 5
DECR counter                     -- Decrement by 1
INCRBYFLOAT price 0.5            -- Increment float
APPEND key " more"               -- Append to string
STRLEN key                       -- String length
GETRANGE key 0 4                 -- Substring

Hashes

Key-value pairs within a key. Perfect for objects.

HSET user:1 name "Alice" age 30 email "alice@ex.com"
HGET user:1 name                 -- Get single field
HMGET user:1 name email          -- Get multiple fields
HGETALL user:1                   -- Get all fields and values
HDEL user:1 email                -- Delete field
HEXISTS user:1 name              -- Check field exists
HKEYS user:1                     -- All field names
HVALS user:1                     -- All values
HLEN user:1                      -- Number of fields
HINCRBY user:1 age 1             -- Increment numeric field
HSETNX user:1 name "Bob"         -- Set field only if not exists
HSCAN user:1 0 MATCH "pref:*"    -- Iterate a large hash safely
HRANDFIELD user:1 2 WITHVALUES   -- Random fields (6.2+)
-- HMSET is deprecated: HSET accepts multiple field/value pairs since 4.0

Per-field expiry (Redis 7.4+, Valkey 9.0+):

HEXPIRE session:abc 3600 FIELDS 1 csrf_token    -- TTL on one field
HTTL session:abc FIELDS 1 csrf_token            -- Remaining field TTL
HPERSIST session:abc FIELDS 1 csrf_token        -- Remove field TTL
HSETEX session:abc EX 600 FIELDS 1 otp 123456   -- Set field(s) with TTL (Redis 8.0+)
HGETEX session:abc EX 600 FIELDS 1 otp          -- Get field(s) and set TTL (Redis 8.0+)
HGETDEL session:abc FIELDS 1 otp                -- Get and delete field(s) (Redis 8.0+)

Lists

Ordered collection of strings. Stored as a quicklist (a linked list of compact listpack nodes; small lists are a single listpack), so push/pop at either end is O(1) and access by index is O(n).

LPUSH queue "item1"              -- Push to head
RPUSH queue "item2"              -- Push to tail
LPOP queue                       -- Pop from head
RPOP queue                       -- Pop from tail
BLPOP queue 30                   -- Blocking pop (30s timeout)
BRPOP queue 30                   -- Blocking pop from tail
LLEN queue                       -- List length
LRANGE queue 0 -1                -- Get all elements
LRANGE queue 0 9                 -- Get first 10
LINDEX queue 0                   -- Get by index
LSET queue 0 "new"               -- Set by index
LTRIM queue 0 99                 -- Keep only first 100
LPOS queue "item1"               -- Find position
LMOVE src dst LEFT RIGHT         -- Move between lists (6.2+; replaces RPOPLPUSH)
BLMOVE src dst RIGHT LEFT 30     -- Blocking move: reliable-queue pattern
LMPOP 2 q:high q:low LEFT COUNT 10  -- Pop up to 10 from the first non-empty list (7.0+)

Sets

Unordered collection of unique strings.

SADD tags "redis" "cache" "db"   -- Add members
SREM tags "db"                   -- Remove member
SISMEMBER tags "redis"           -- Check membership
SMEMBERS tags                    -- All members
SCARD tags                       -- Set size
SRANDMEMBER tags 2               -- 2 random members
SPOP tags                        -- Remove and return random
SUNION tags1 tags2               -- Union
SINTER tags1 tags2               -- Intersection
SDIFF tags1 tags2                -- Difference (in tags1 not in tags2)
SUNIONSTORE dest tags1 tags2     -- Store union result
SMISMEMBER tags "redis" "x"      -- Check several members at once (6.2+)
SINTERCARD 2 tags1 tags2 LIMIT 100  -- Size of intersection without building it (7.0+)
SSCAN tags 0 MATCH "re*"         -- Iterate a large set safely

Sorted Sets

Like sets but each member has a score. Sorted by score.

ZADD leaderboard 100 "alice"     -- Add with score
ZADD leaderboard 95 "bob" 110 "charlie"
ZSCORE leaderboard "alice"       -- Get score
ZRANK leaderboard "alice"        -- Rank (0-based, low to high)
ZREVRANK leaderboard "alice"     -- Rank (high to low)
ZRANGE leaderboard 0 9           -- Bottom 10 (lowest scores first)
ZRANGE leaderboard 0 9 REV WITHSCORES  -- Top 10 (high to low, 6.2+)
ZREVRANGE leaderboard 0 9        -- Top 10 (deprecated since 6.2: use ZRANGE ... REV)
ZRANGE lb 90 100 BYSCORE         -- Members with score 90-100 (6.2+)
ZRANGE lb (90 100 BYSCORE        -- "(" = exclusive bound: 90 < score <= 100
ZRANGE lb +inf -inf BYSCORE REV LIMIT 0 10  -- Highest scores, paginated
ZRANGEBYSCORE lb 90 100          -- Members with score 90-100 (deprecated: ZRANGE ... BYSCORE)
ZRANGEBYSCORE lb -inf +inf       -- All by score (deprecated form)
ZCARD leaderboard                -- Set size
ZCOUNT leaderboard 90 100        -- Count in score range
ZINCRBY leaderboard 5 "alice"    -- Increment score
ZREM leaderboard "bob"           -- Remove member
ZREMRANGEBYRANK lb 0 -4          -- Keep only top 3
ZRANGEBYSCORE lb 90 100 LIMIT 0 5 -- Paginate (deprecated form)
ZRANGE lb 90 100 BYSCORE LIMIT 0 5 -- Paginate (current form)
ZPOPMIN lb 5                     -- Pop 5 lowest (ZPOPMAX for highest)
BZPOPMIN lb 30                   -- Blocking pop (priority queue)
ZMSCORE lb "alice" "bob"         -- Several scores at once (6.2+)
ZRANK lb "alice" WITHSCORE       -- Rank and score together (7.2+)

JSON, Search and Probabilistic Types (Redis 8.0+ built in; modules on older Redis; Valkey ships valkey-json and valkey-bloom modules)

JSON.SET user:1 $ '{"name":"Alice","tags":["a","b"]}'
JSON.GET user:1 $.name
JSON.ARRAPPEND user:1 $.tags '"c"'
BF.ADD seen "url-1"                  -- Bloom filter
BF.EXISTS seen "url-1"
FT.CREATE idx ON JSON PREFIX 1 user: SCHEMA $.name AS name TEXT
FT.SEARCH idx "@name:alice"

HyperLogLog, Bitmaps, Geo

PFADD visitors:2026-11-09 "u1" "u2"  -- Approximate distinct count (~0.81% error, 12 KB max)
PFCOUNT visitors:2026-11-09
SETBIT active:2026-11-09 42 1        -- User 42 active today
BITCOUNT active:2026-11-09
GEOADD shops 77.59 12.97 "blr"       -- longitude first, then latitude
GEOSEARCH shops FROMLONLAT 77.6 12.9 BYRADIUS 10 km ASC  -- 6.2+; replaces GEORADIUS

Streams

Append-only log structure for event streaming.

XADD stream * field1 value1      -- Append entry (auto-ID)
XADD stream 1234-0 field1 value1 -- Append with specific ID
XLEN stream                      -- Stream length
XRANGE stream - +                -- All entries
XRANGE stream - + COUNT 10       -- First 10 entries
XREVRANGE stream + -             -- Reverse order
XREAD COUNT 10 STREAMS stream 0  -- Read from beginning
XREAD BLOCK 5000 STREAMS s $     -- Block-read new entries (5s)

XADD stream MAXLEN ~ 100000 * f v   -- Append and cap length (~ = efficient approximate trim)
XADD stream MINID ~ 1730000000000 * f v  -- Trim entries older than an ID / timestamp (6.2+)
XTRIM stream MAXLEN ~ 100000     -- Trim separately
XINFO STREAM stream              -- Length, first/last entry, groups

-- Consumer groups
XGROUP CREATE stream group 0     -- Create consumer group
XGROUP CREATE stream group $ MKSTREAM  -- Only new messages; create stream if missing
XREADGROUP GROUP group consumer COUNT 10 STREAMS stream >
XREADGROUP GROUP group consumer COUNT 10 BLOCK 5000 STREAMS stream >  -- Block up to 5 s
XREADGROUP GROUP group consumer STREAMS stream 0  -- Re-read MY pending (unacked) messages
XACK stream group id             -- Acknowledge message
XPENDING stream group            -- Pending messages info
XPENDING stream group IDLE 60000 - + 10  -- Entries idle > 60 s (6.2+)
XCLAIM stream group consumer 60000 id -- Claim stale message
XAUTOCLAIM stream group consumer 60000 0-0 COUNT 10  -- Scan and claim idle messages (6.2+)
XINFO GROUPS stream              -- Lag and pending per group (lag field 7.0+)
XINFO CONSUMERS stream group     -- Per-consumer pending and idle time
XGROUP DELCONSUMER stream group consumer  -- Remove a dead consumer
XGROUP SETID stream group 0      -- Rewind a group (replay)

Consumer group lifecycle:

  1. Each worker reads with XREADGROUP ... > (only never-delivered messages); each message goes to one consumer in the group.
  2. Delivered messages sit in that consumer's Pending Entries List (PEL) until XACK.
  3. On restart, a worker first reads its own PEL with ID 0, then switches to >.
  4. A janitor (or each worker) runs XAUTOCLAIM to take over messages idle longer than a timeout from crashed consumers.
  5. Check the delivery count in XPENDING; move messages delivered too many times to a dead-letter stream and XACK them.

WARNING

XACK does not delete the entry from the stream; only trimming (MAXLEN/MINID/XTRIM) or XDEL frees memory. Without trimming, a stream grows forever.


Key Management

CommandDescription
EXISTS keyCheck if key exists
DEL keyDelete key (blocking)
UNLINK keyDelete key (non-blocking)
TYPE keyGet key type
RENAME key newkeyRename key
EXPIRE key 3600Set TTL in seconds
EXPIRE key 3600 NXOnly if no TTL yet (also XX, GT, LT; 7.0+)
EXPIRETIME keyAbsolute expiry as Unix time (7.0+)
COPY src dstCopy a key (6.2+)
RENAMENX key newkeyRename only if target doesn't exist
TOUCH keyUpdate last-access time
OBJECT FREQ keyAccess frequency (LFU policies only)
OBJECT IDLETIME keySeconds since last access (LRU policies)
PEXPIRE key 60000Set TTL in milliseconds
EXPIREAT key timestampSet expiry at Unix time
TTL keyRemaining TTL in seconds
PTTL keyRemaining TTL in milliseconds
PERSIST keyRemove expiry
KEYS patternFind keys (NEVER in production)
SCAN 0 MATCH "user:*" COUNT 100Iterate keys safely (repeat with the returned cursor until it is 0)
SCAN 0 TYPE streamIterate only keys of one type (6.0+)
OBJECT ENCODING keyInternal encoding (listpack replaced ziplist in 7.0)
MEMORY USAGE keyMemory used by key
DUMP keySerialize key
RESTORE key 0 dataDeserialize key

WARNING

Never use KEYS * in production. It blocks the server. Always use SCAN instead.


Common Patterns

Cache-Aside Pattern

Read:  Check cache -> miss -> read DB -> write cache -> return
Write: Write DB -> invalidate cache
-- Read: check cache first
GET user:123
-- If nil, read from DB and cache
SET user:123 "{json}" EX 3600

-- Write: invalidate after DB write
DEL user:123

Distributed Lock

-- Acquire lock (NX = only if not exists, EX = TTL)
SET lock:resource unique_id NX EX 30

-- Release lock (only if we own it) -- use Lua for atomicity
EVAL "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end" 1 lock:resource unique_id

Rate Limiter (Sliding Window)

-- Using sorted set for sliding window
ZADD ratelimit:user:123 <now_ms> <request_id>
ZREMRANGEBYSCORE ratelimit:user:123 0 <now_ms - window_ms>
ZCARD ratelimit:user:123
EXPIRE ratelimit:user:123 <window_seconds>

Send these four in one MULTI ... EXEC (or a Lua script / function) so concurrent requests can't interleave between the trim and the count.

Transactions and Optimistic Locking

WATCH balance:42                 -- abort EXEC if this key changes
GET balance:42
MULTI
DECRBY balance:42 10
INCRBY balance:7 10
EXEC                             -- nil reply = someone changed balance:42, retry

MULTI/EXEC is atomic (no other client runs in between) but has no rollback: if one command errors at runtime, the others still apply.

Pub/Sub

-- Subscriber
SUBSCRIBE channel
PSUBSCRIBE "events:*"           -- Pattern subscribe

-- Publisher
PUBLISH channel "message"

-- Sharded Pub/Sub in Cluster (7.0+): message stays on the shard that owns the channel's slot
SSUBSCRIBE orders:{eu}
SPUBLISH orders:{eu} "message"

-- Introspection
PUBSUB CHANNELS "events:*"
PUBSUB NUMSUB channel

Pub/Sub is fire-and-forget: subscribers that are disconnected miss messages. Use Streams when you need replay or acknowledgements.

Session Storage

-- Store session as hash
HSET session:abc123 user_id 42 role "admin" created_at 1234567890
EXPIRE session:abc123 86400     -- 24 hour TTL

-- Extend session on activity
EXPIRE session:abc123 86400     -- Reset TTL

-- Get session
HGETALL session:abc123

Counter with Expiry

-- Page view counter (daily)
INCR pageviews:2026-03-18:/home
EXPIRE pageviews:2026-03-18:/home 172800  -- Keep 2 days

Leaderboard

-- Add/update score
ZINCRBY leaderboard 10 "player:42"

-- Get top 10
ZREVRANGE leaderboard 0 9 WITHSCORES

-- Get player rank (1-based)
ZREVRANK leaderboard "player:42"  -- Add 1 for 1-based

-- Top 10 with the current (non-deprecated) syntax
ZRANGE leaderboard 0 9 REV WITHSCORES

Client-Side Caching (6.0+)

HELLO 3                          -- RESP3 for push notifications
CLIENT TRACKING ON               -- server remembers keys this client read
GET user:123                     -- later writes to user:123 push an invalidation message
CLIENT TRACKING ON BCAST PREFIX user:   -- broadcast mode: invalidations for a prefix

Lua Scripting

Why Lua?

  • Atomic execution (no other commands run during script)
  • Reduce round trips (multiple operations in one call)
  • Complex conditional logic

Basic Syntax

EVAL "return redis.call('GET', KEYS[1])" 1 mykey
-- KEYS[1] = first key argument
-- ARGV[1] = first non-key argument

-- Multi-command script
EVAL "
  local current = redis.call('GET', KEYS[1])
  if current then
    return redis.call('INCR', KEYS[1])
  else
    redis.call('SET', KEYS[1], ARGV[1])
    return tonumber(ARGV[1])
  end
" 1 counter 100

Common Lua Scripts

-- Compare and delete (safe lock release)
EVAL "
  if redis.call('GET', KEYS[1]) == ARGV[1] then
    return redis.call('DEL', KEYS[1])
  end
  return 0
" 1 lock:resource owner_id

-- Rate limiter (fixed window)
EVAL "
  local key = KEYS[1]
  local limit = tonumber(ARGV[1])
  local window = tonumber(ARGV[2])
  local current = redis.call('INCR', key)
  if current == 1 then
    redis.call('EXPIRE', key, window)
  end
  if current > limit then
    return 0
  end
  return 1
" 1 ratelimit:user:123 100 60

-- Get or set with TTL
EVAL "
  local val = redis.call('GET', KEYS[1])
  if val then
    return val
  end
  redis.call('SET', KEYS[1], ARGV[1], 'EX', ARGV[2])
  return ARGV[1]
" 1 cache:key "computed_value" 3600

Loading Scripts

-- Load script and get SHA
SCRIPT LOAD "return redis.call('GET', KEYS[1])"
-- Returns SHA hash

-- Execute by SHA (more efficient)
EVALSHA <sha> 1 mykey

-- Check if script is cached
SCRIPT EXISTS <sha>

-- Read-only variants (can run on replicas, 7.0+)
EVAL_RO "return redis.call('GET', KEYS[1])" 1 mykey
EVALSHA_RO <sha> 1 mykey

WARNING

The script cache is not persisted or replicated as a library: after a restart or failover EVALSHA returns NOSCRIPT, and clients must fall back to EVAL. Functions (below) fix this. Always pass every key a script touches in KEYS, or it breaks in Cluster.

Functions (Redis 7.0+, Valkey)

Functions are named, versioned libraries stored in the dataset: they are persisted (RDB/AOF) and replicated, so they survive restarts and failovers.

#!lua name=ratelimit

local function hit(keys, args)
  local current = redis.call('INCR', keys[1])
  if current == 1 then
    redis.call('EXPIRE', keys[1], tonumber(args[2]))
  end
  return current <= tonumber(args[1]) and 1 or 0
end

local function peek(keys, args)
  return tonumber(redis.call('GET', keys[1]) or '0')
end

redis.register_function('rl_hit', hit)
redis.register_function{
  function_name = 'rl_peek',
  callback = peek,
  flags = { 'no-writes' }        -- allows FCALL_RO and running on replicas
}
# Load (REPLACE to update an existing library)
redis-cli -x FUNCTION LOAD REPLACE < ratelimit.lua
FCALL rl_hit 1 ratelimit:user:123 100 60   -- name, numkeys, keys..., args...
FCALL_RO rl_peek 1 ratelimit:user:123
FUNCTION LIST WITHCODE LIBRARYNAME ratelimit
FUNCTION DELETE ratelimit
FUNCTION DUMP                    -- serialize all libraries (then FUNCTION RESTORE elsewhere)
FUNCTION STATS                   -- currently running function, engines
EVAL scriptsFunctions
IdentitySHA1 of the sourceLibrary + function name
Survives restart / failoverNo (cache only)Yes (persisted and replicated)
Shared helpersCopy-paste per scriptLocal functions within a library
Read-only on replicasEVAL_ROno-writes flag + FCALL_RO

ACLs (Users and Permissions, 6.0+)

-- App user: password, only keys under cache:*, read/write string and key commands
ACL SETUSER app on >s3cret ~cache:* +@read +@write -@dangerous

-- Read-only user on all keys, no Pub/Sub channels
ACL SETUSER reporting on >pw ~* resetchannels +@read

-- Worker: only its stream, only the commands it needs, and its channels
ACL SETUSER worker on >pw ~jobs:* &jobs:* +xreadgroup +xack +xadd +subscribe

-- Separate read and write key patterns (7.0+): %R~ read-only, %W~ write-only
ACL SETUSER etl on >pw %R~src:* %W~dst:* +@all

-- Selectors (7.0+): extra permission sets in parentheses
ACL SETUSER svc on >pw ~app:* +@all (~audit:* +get)

-- Lock down the default user (used by clients that AUTH with just a password)
ACL SETUSER default off
CommandDescription
ACL WHOAMICurrent user
ACL LISTAll users and rules (as config lines)
ACL GETUSER appOne user's rules
ACL CAT / ACL CAT writeCommand categories / commands in a category
ACL DRYRUN app SET cache:x 1Would this user be allowed? (7.0+)
ACL LOG 10Recent denied commands and failed logins
ACL DELUSER appDelete user
ACL SAVE / ACL LOADWrite / reload the aclfile
ACL GENPASSGenerate a strong random password

Rule syntax: on/off enable, >pass add password, ~pattern keys, &pattern Pub/Sub channels, +cmd / -cmd / +@category, allkeys, allcommands, nopass, reset. Since 7.0, new users get no channel access by default (acl-pubsub-default resetchannels).


Cluster Operations

Cluster Info

CommandDescription
CLUSTER INFOCluster state overview
CLUSTER NODESAll nodes and slots
CLUSTER SLOTSSlot-to-node mapping (deprecated since 7.0)
CLUSTER SHARDSShards, their slot ranges and nodes (7.0+, replaces CLUSTER SLOTS)
CLUSTER COUNTKEYSINSLOT 1234Keys in a slot
CLUSTER MYIDCurrent node ID
CLUSTER KEYSLOT keyHash slot for a key

Cluster Management

CommandDescription
CLUSTER MEET host portAdd node to cluster
CLUSTER ADDSLOTS 0 1 2 ... 5460Assign hash slots
CLUSTER REPLICATE node_idMake current node a replica
CLUSTER FAILOVERManual failover (run on the replica to promote)
READONLYAllow reads from this replica connection
CLUSTER RESETReset cluster config
CLUSTER FORGET node_idRemove node from cluster

redis-cli Cluster Mode

# Connect in cluster mode
redis-cli -c -h host -p 6379

# Create cluster
redis-cli --cluster create host1:6379 host2:6379 host3:6379 \
  host4:6379 host5:6379 host6:6379 --cluster-replicas 1

# Check cluster health
redis-cli --cluster check host:6379

# Reshard
redis-cli --cluster reshard host:6379

# Add node
redis-cli --cluster add-node new_host:6379 existing_host:6379

# Rebalance slots
redis-cli --cluster rebalance host:6379

Hash Tags (Force Same Slot)

-- Keys with same hash tag go to same slot
SET {user:123}.profile "data"
SET {user:123}.settings "data"
-- Both in same slot, can use in multi-key commands

Only the part between the first { and the next } is hashed. Multi-key commands, transactions and scripts across different slots fail with CROSSSLOT. Cluster mode supports only database 0 in Redis (Valkey 9.0 added numbered databases in cluster mode).


Memory Optimization

Eviction Policies

PolicyDescription
noevictionReturn error when full (default)
allkeys-lruEvict least recently used
allkeys-lfuEvict least frequently used
volatile-lruLRU among keys with TTL
volatile-lfuLFU among keys with TTL
volatile-ttlEvict keys with shortest TTL
allkeys-randomRandom eviction
volatile-randomRandom among keys with TTL

Memory Commands

INFO memory                      -- Memory overview
MEMORY USAGE key                 -- Bytes used by key
MEMORY DOCTOR                    -- Memory issues diagnosis
MEMORY STATS                     -- Detailed memory stats
CONFIG SET maxmemory 2gb         -- Set memory limit
CONFIG SET maxmemory-policy allkeys-lru
MEMORY PURGE                     -- Ask the allocator (jemalloc) to release dirty pages

INFO memory fields to watch: used_memory (data), used_memory_rss (what the OS sees), mem_fragmentation_ratio (> 1.5 is high; CONFIG SET activedefrag yes helps). Leave headroom: forks for BGSAVE/AOF rewrite use copy-on-write and can double memory under heavy writes.


Persistence

ModeDescriptionData SafetyPerformance
RDBPoint-in-time snapshotsMay lose last minutesBetter
AOFAppend every writeBetter durabilitySlower
RDB + AOFBoth enabledBest durabilitySlowest
NoneNo persistenceData loss on restartFastest
-- Manual snapshot
BGSAVE

-- Manual AOF rewrite
BGREWRITEAOF

-- Last save timestamp
LASTSAVE

-- Wait until the write reached 1 replica (up to 100 ms)
WAIT 1 100

-- Wait until the write is fsynced to the local AOF and 1 replica's AOF (7.2+)
WAITAOF 1 1 100
# redis.conf essentials
appendonly yes
appendfsync everysec         # always | everysec | no  (everysec: lose at most ~1 s)
save 3600 1 300 100 60 10000 # RDB snapshot rules (seconds changes)
aof-use-rdb-preamble yes     # fast restarts: RDB base + AOF tail

Since 7.0, AOF is multi-part: a base file plus incremental files in appenddirname (default appendonlydir/), tracked by a manifest.


When to Use X vs Y

DecisionChoice AChoice BUse A WhenUse B When
Data typeStringHashSingle value, counterObject with fields
QueueListStreamSimple FIFOConsumer groups, persistence
Unique itemsSetSorted SetNo ordering neededNeed ranking/scoring
CachingString + EXHash + EXPIRESimple key-valueMultiple fields per cache entry
MessagingPub/SubStreamsFire-and-forgetNeed delivery guarantees
CounterINCRSorted SetSimple counterNeed ranking of counters
LockSET NX EXRedlockSingle instanceDistributed cluster (disputed safety: add fencing tokens, or use a consensus store for correctness-critical locks)
Server-side logicEVAL scriptFunctionOne-off or ad hocReused logic that must survive restarts/failover
EngineRedis 8ValkeyWant built-in JSON/Search/probabilistic, accept RSAL/SSPL/AGPLWant BSD licence, cloud-provider managed offering

Troubleshooting

ProblemDiagnosis
High latencySLOWLOG GET 10, check INFO commandstats
Memory too highMEMORY DOCTOR, check INFO memory
Too many connectionsCLIENT LIST, check INFO clients
Keys not expiringCheck maxmemory-policy, run INFO keyspace
Cluster slot errorsCLUSTER INFO, CLUSTER NODES
Replication lagINFO replication, check master_link_status
NOAUTH / WRONGPASSCheck user with ACL LOG, AUTH username password
NOPERMACL DRYRUN user CMD args to see which rule blocks it
CROSSSLOTKeys in different slots: use a common hash tag {...}
OOM command not allowedmaxmemory reached with noeviction: raise it or choose an eviction policy
Big keysredis-cli --bigkeys, MEMORY USAGE key

Test Yourself
  1. What command sets a key only if it does not already exist? SET key "value" NX or SETNX key "value"

  2. How do you get all fields and values of a hash? HGETALL key

  3. What command blocks until an element is available in a list (with 30s timeout)? BLPOP queue 30

  4. How do you get the top 10 members of a sorted set from highest to lowest score? ZRANGE leaderboard 0 9 REV (6.2+; the older ZREVRANGE leaderboard 0 9 still works but is deprecated)

  5. What command should you NEVER use in production to find keys? KEYS * -- use SCAN instead.

  6. How do you delete a key without blocking the server? UNLINK key

  7. What Lua function executes a Redis command inside a script? redis.call('COMMAND', KEYS[1], ARGV[1])

  8. How do you force keys with the same hash tag into the same cluster slot? Wrap the common part in braces: {user:123}.profile and {user:123}.settings

  9. What eviction policy evicts the least recently used key? allkeys-lru

  10. How do you create a consumer group for a Redis Stream? XGROUP CREATE stream group 0

Common Gotchas

  • Using KEYS * in production. It blocks the single-threaded Redis server while scanning all keys. Use SCAN with COUNT for safe iteration.
  • Forgetting to set TTLs on cache keys. Without expiry, Redis fills up and either returns errors (noeviction) or evicts keys you may still need.
  • Using DEL on large keys. Deleting a key with millions of elements blocks Redis. Use UNLINK for non-blocking deletion.
  • Not using Lua for multi-step atomic operations. Without Lua, another client can modify state between your GET and SET, causing race conditions.
  • Relying on EVALSHA after a failover. The script cache is empty on the new primary; handle NOSCRIPT or use Functions.
  • Leaving the default user with no password. Anyone who can reach the port has full access (including CONFIG SET and FLUSHALL). Use ACL users, protected-mode yes, and never expose 6379 to the internet.
  • Unbounded streams. XACK does not delete; add MAXLEN ~ or MINID ~ to XADD.
  • Using SELECT for tenant separation. Numbered databases share one memory pool and one thread, and Redis Cluster only has DB 0. Use key prefixes or separate instances.
  • New code on deprecated commands. GETSET, SETNX, HMSET, ZREVRANGE, ZRANGEBYSCORE, RPOPLPUSH, GEORADIUS and CLUSTER SLOTS still work but have replacements listed above.

One-Liner Summary

Redis is an in-memory data structure store that makes caching, queuing, rate limiting, and real-time leaderboards trivially fast -- just remember commands execute on a single main thread (I/O threads only help with networking), so never block it.