Redis Cheat Sheet

Complete Redis command reference covering all data types, pub/sub, transactions, Lua scripting, persistence, clustering, and common patterns like caching and rate limiting.

On This Page

Connection

CommandDescription
redis-cliConnect to local Redis server on default port 6379
redis-cli -h <host> -p <port>Connect to a remote Redis server
redis-cli -a <password>Connect with password authentication
redis-cli --tls -h <host> -p 6380Connect using TLS encryption
AUTH <password>Authenticate to the server after connecting
AUTH <username> <password>Authenticate with ACL username and password (Redis 6+)
PINGTest connection (returns PONG if alive)
SELECT <db>Switch to a different database (0-15 by default)
QUITClose the connection
INFOGet server information and statistics
INFO serverGet only server section info
CONFIG GET <parameter>Get a configuration parameter value
CONFIG SET <parameter> <value>Set a configuration parameter at runtime
DBSIZEReturn the number of keys in the current database
FLUSHDBDelete all keys in the current database
FLUSHALLDelete all keys in all databases
CLIENT LISTList all connected clients
CLIENT SETNAME <name>Set a name for the current connection

Strings

CommandDescription
SET key valueSet a key to a string value
SET key value EX 60Set a key with a 60-second expiration
SET key value PX 5000Set a key with a 5000-millisecond expiration
SET key value NXSet only if the key does not already exist
SET key value XXSet only if the key already exists
SETNX key valueSet key only if it does not exist (atomic)
GET keyGet the value of a key
GETDEL keyGet the value and delete the key (Redis 6.2+)
GETSET key valueSet a new value and return the old value
MSET key1 val1 key2 val2Set multiple keys at once
MGET key1 key2 key3Get multiple values at once
INCR keyIncrement integer value by 1
INCRBY key 10Increment integer value by 10
INCRBYFLOAT key 1.5Increment float value by 1.5
DECR keyDecrement integer value by 1
DECRBY key 5Decrement integer value by 5
APPEND key " more"Append a string to the existing value
STRLEN keyGet the length of the string value
GETRANGE key 0 4Get a substring (bytes 0 through 4)
SETRANGE key 6 "world"Overwrite part of the string starting at offset 6

Lists

CommandDescription
LPUSH key val1 val2Push values to the head (left) of a list
RPUSH key val1 val2Push values to the tail (right) of a list
LPOP keyRemove and return the first element
RPOP keyRemove and return the last element
LPOP key 3Remove and return up to 3 elements from the head (Redis 6.2+)
LLEN keyGet the length of a list
LRANGE key 0 -1Get all elements in a list
LRANGE key 0 9Get the first 10 elements
LINDEX key 0Get element at index 0 (head)
LSET key 0 "new"Set the value at index 0
LINSERT key BEFORE "pivot" "val"Insert value before the pivot element
LINSERT key AFTER "pivot" "val"Insert value after the pivot element
LREM key 2 "val"Remove first 2 occurrences of value
LTRIM key 0 99Trim list to keep only elements 0-99
RPOPLPUSH src dstPop from src tail and push to dst head
LMOVE src dst LEFT RIGHTMove element between lists (Redis 6.2+)
BLPOP key 30Blocking pop from head with 30s timeout
BRPOP key 30Blocking pop from tail with 30s timeout

Sets

CommandDescription
SADD key member1 member2Add members to a set
SREM key member1Remove a member from a set
SMEMBERS keyGet all members of a set
SISMEMBER key memberCheck if member exists in set (returns 1 or 0)
SMISMEMBER key m1 m2 m3Check multiple members at once (Redis 6.2+)
SCARD keyGet the number of members in a set
SPOP keyRemove and return a random member
SPOP key 3Remove and return 3 random members
SRANDMEMBER keyReturn a random member without removing it
SRANDMEMBER key 5Return 5 random distinct members
SUNION key1 key2Return the union of multiple sets
SUNIONSTORE dest key1 key2Store the union in a destination set
SINTER key1 key2Return the intersection of multiple sets
SINTERSTORE dest key1 key2Store the intersection in a destination set
SDIFF key1 key2Return members in key1 but not in key2
SDIFFSTORE dest key1 key2Store the difference in a destination set
SMOVE src dst memberMove a member from one set to another

Sorted Sets

CommandDescription
ZADD key score memberAdd a member with a score to a sorted set
ZADD key NX score memberAdd only if the member does not exist
ZADD key XX score memberUpdate score only if the member exists
ZADD key GT score memberUpdate only if new score is greater (Redis 6.2+)
ZREM key memberRemove a member from a sorted set
ZSCORE key memberGet the score of a member
ZRANK key memberGet the rank (index) of a member (ascending)
ZREVRANK key memberGet the rank of a member (descending)
ZRANGE key 0 -1Get all members sorted by score ascending
ZRANGE key 0 -1 WITHSCORESGet all members with their scores
ZREVRANGE key 0 9Get top 10 members (highest score first)
ZRANGEBYSCORE key 10 100Get members with scores between 10 and 100
ZRANGEBYSCORE key -inf +infGet all members by score range
ZCOUNT key 10 100Count members with scores between 10 and 100
ZCARD keyGet the number of members in a sorted set
ZINCRBY key 5 memberIncrement the score of a member by 5
ZREMRANGEBYRANK key 0 2Remove members by rank range
ZREMRANGEBYSCORE key 0 100Remove members by score range
ZUNIONSTORE dest 2 key1 key2Store the union of sorted sets
ZINTERSTORE dest 2 key1 key2Store the intersection of sorted sets
ZPOPMIN keyRemove and return the member with the lowest score
ZPOPMAX keyRemove and return the member with the highest score

Hashes

CommandDescription
HSET key field valueSet a field in a hash
HSET key f1 v1 f2 v2Set multiple fields at once
HGET key fieldGet the value of a hash field
HMGET key f1 f2 f3Get multiple field values at once
HGETALL keyGet all fields and values in a hash
HDEL key fieldDelete a field from a hash
HEXISTS key fieldCheck if a field exists (returns 1 or 0)
HLEN keyGet the number of fields in a hash
HKEYS keyGet all field names in a hash
HVALS keyGet all values in a hash
HINCRBY key field 1Increment an integer field by 1
HINCRBYFLOAT key field 0.5Increment a float field by 0.5
HSETNX key field valueSet a field only if it does not exist
HSCAN key 0 MATCH pattern*Incrementally iterate over hash fields
HRANDFIELD key 3Return 3 random field names (Redis 6.2+)
HRANDFIELD key 3 WITHVALUESReturn 3 random fields with values (Redis 6.2+)

Keys & Expiry

CommandDescription
KEYS pattern*Find keys matching a pattern (avoid in production)
SCAN 0 MATCH pattern* COUNT 100Incrementally iterate keys (production-safe)
EXISTS keyCheck if a key exists (returns 1 or 0)
EXISTS key1 key2 key3Count how many of the keys exist
TYPE keyGet the data type of a key
RENAME key newkeyRename a key
RENAMENX key newkeyRename only if newkey does not exist
DEL key1 key2Delete keys (blocking)
UNLINK key1 key2Delete keys asynchronously (non-blocking)
EXPIRE key 60Set a key to expire in 60 seconds
PEXPIRE key 5000Set expiry in milliseconds
EXPIREAT key 1707667200Set expiry at a Unix timestamp
TTL keyGet remaining time to live in seconds (-1 = no expiry, -2 = not found)
PTTL keyGet remaining TTL in milliseconds
PERSIST keyRemove the expiry from a key (make it persistent)
DUMP keySerialize a key's value
RESTORE key 0 <serialized>Deserialize and restore a key
OBJECT ENCODING keyGet internal encoding of a key's value
OBJECT REFCOUNT keyGet reference count of a key's value
RANDOMKEYReturn a random key from the database
COPY src dstCopy a key to a new key (Redis 6.2+)

Pub/Sub

CommandDescription
SUBSCRIBE channel1 channel2Subscribe to one or more channels
UNSUBSCRIBE channel1Unsubscribe from a channel
PUBLISH channel "message"Publish a message to a channel
PSUBSCRIBE pattern*Subscribe to channels matching a pattern
PUNSUBSCRIBE pattern*Unsubscribe from pattern-matched channels
PUBSUB CHANNELSList active channels with subscribers
PUBSUB CHANNELS pattern*List active channels matching a pattern
PUBSUB NUMSUB channelGet subscriber count for a channel
PUBSUB NUMPATGet the count of unique pattern subscriptions

Transactions

CommandDescription
MULTIStart a transaction block
EXECExecute all queued commands in the transaction
DISCARDDiscard all queued commands and exit transaction
WATCH key1 key2Watch keys for changes (optimistic locking)
UNWATCHUnwatch all previously watched keys

Transaction Example (Optimistic Locking)

WATCH mykey
val = GET mykey
val = val + 1
MULTI
SET mykey $val
EXEC
# EXEC returns nil if mykey was modified by another client

Lua Scripting

CommandDescription
EVAL "return 1+1" 0Execute a Lua script with no keys
EVAL "return redis.call('GET',KEYS[1])" 1 mykeyExecute a script that reads a key
EVAL "redis.call('SET',KEYS[1],ARGV[1])" 1 mykey myvalExecute a script that sets a key
EVALSHA <sha1> 1 mykeyExecute a cached script by its SHA1 hash
SCRIPT LOAD "return 1"Load a script into the cache and return its SHA1
SCRIPT EXISTS <sha1>Check if a script exists in the cache
SCRIPT FLUSHRemove all scripts from the cache
SCRIPT KILLKill a currently running Lua script

Lua Script Example (Atomic Compare-and-Set)

# Atomic compare-and-set: only update if current value matches
EVAL "
  if redis.call('GET', KEYS[1]) == ARGV[1] then
    return redis.call('SET', KEYS[1], ARGV[2])
  else
    return nil
  end
" 1 mykey "old_value" "new_value"

Persistence (RDB/AOF)

CommandDescription
BGSAVETrigger a background RDB snapshot
SAVETrigger a synchronous RDB snapshot (blocks server)
LASTSAVEGet the Unix timestamp of the last successful save
BGREWRITEAOFTrigger a background AOF rewrite
CONFIG SET save "60 1000"Auto-save RDB if 1000 keys changed in 60 seconds
CONFIG SET appendonly yesEnable AOF persistence at runtime
CONFIG SET appendfsync everysecSet AOF fsync policy (always, everysec, no)
CONFIG SET aof-use-rdb-preamble yesUse RDB+AOF hybrid format for faster loads
DEBUG SLEEP 0Check if a BGSAVE is in progress

Persistence Options Comparison

FeatureRDB (Snapshots)AOF (Append Only File)
How it worksPoint-in-time binary snapshotsLogs every write operation
File sizeCompactLarger (can be compacted via rewrite)
Data loss riskMinutes of data between snapshotsAt most 1 second with everysec fsync
Restart speedFast (load binary dump)Slower (replay all operations)
Best forBackups, disaster recoveryMinimal data loss requirements

Cluster Commands

CommandDescription
CLUSTER INFOGet cluster state and statistics
CLUSTER NODESList all nodes in the cluster
CLUSTER MYIDGet the node ID of the current node
CLUSTER MEET <ip> <port>Add a node to the cluster
CLUSTER FORGET <node-id>Remove a node from the cluster
CLUSTER REPLICATE <node-id>Make current node a replica of the given master
CLUSTER SLOTSGet the mapping of hash slots to nodes
CLUSTER KEYSLOT <key>Get the hash slot for a given key
CLUSTER COUNTKEYSINSLOT <slot>Count keys in a specific hash slot
CLUSTER ADDSLOTS <slot> [slot ...]Assign hash slots to the current node
CLUSTER DELSLOTS <slot> [slot ...]Remove hash slot assignments from the current node
CLUSTER FAILOVERForce a replica to perform a manual failover
CLUSTER RESET SOFTSoft reset: clear slot assignments and known nodes
CLUSTER RESET HARDHard reset: flush data and generate a new node ID
redis-cli --cluster create h1:p1 h2:p2 h3:p3 --cluster-replicas 1Create a cluster with 3 masters and 3 replicas
redis-cli --cluster reshard <host>:<port>Reshard hash slots between nodes
redis-cli --cluster check <host>:<port>Check the cluster for configuration errors

Common Patterns

Caching Pattern (Cache-Aside)

Check cache first. On miss, load from database and store in cache with a TTL to prevent stale data.

# Pseudocode for cache-aside pattern
value = GET "cache:user:123"
if value is nil:
    value = db.query("SELECT * FROM users WHERE id=123")
    SET "cache:user:123" value EX 300    # Cache for 5 minutes
return value

# Invalidate on update
DEL "cache:user:123"

Rate Limiting (Sliding Window)

Limit API calls per user using a sorted set with timestamps. Clean up expired entries on each check.

# Allow 100 requests per 60 seconds per user
MULTI
ZREMRANGEBYSCORE "ratelimit:user:42" 0 (NOW - 60)
ZADD "ratelimit:user:42" NOW NOW
ZCARD "ratelimit:user:42"
EXPIRE "ratelimit:user:42" 60
EXEC
# If ZCARD result > 100, reject the request

Rate Limiting (Fixed Window Counter)

Simple counter-based rate limiting. Lighter than the sliding window but less precise at boundaries.

# Allow 100 requests per minute
key = "ratelimit:user:42:" + current_minute
count = INCR key
if count == 1:
    EXPIRE key 60
if count > 100:
    reject request

Session Management

Store user sessions as Redis hashes with automatic expiry. Fast reads/writes for session data.

# Create session
HSET "session:abc123" user_id 42 role "admin" created_at 1707667200
EXPIRE "session:abc123" 3600       # 1 hour TTL

# Read session
HGETALL "session:abc123"

# Refresh session TTL on activity
EXPIRE "session:abc123" 3600

# Destroy session (logout)
DEL "session:abc123"

Distributed Lock (Redlock Pattern)

Use SET NX with an expiry to implement a simple distributed lock. Always include a unique token for safe release.

# Acquire lock (only if not held)
SET "lock:resource" "unique-token-abc" NX EX 30

# Release lock (only if we hold 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-token-abc"

Leaderboard

Use sorted sets for real-time leaderboards with O(log N) inserts and O(log N + M) range queries.

# Add or update a player's score
ZADD "leaderboard:game1" 1500 "player:42"

# Get top 10 players
ZREVRANGE "leaderboard:game1" 0 9 WITHSCORES

# Get a player's rank (0-indexed, highest first)
ZREVRANK "leaderboard:game1" "player:42"

# Increment a player's score
ZINCRBY "leaderboard:game1" 50 "player:42"

Frequently Asked Questions

What is Redis and what is it used for?

Redis (Remote Dictionary Server) is an open-source, in-memory data structure store used as a database, cache, message broker, and streaming engine. It supports data structures such as strings, lists, sets, sorted sets, hashes, bitmaps, and streams. Redis is widely used for caching, session management, real-time analytics, rate limiting, leaderboards, and pub/sub messaging due to its sub-millisecond response times.

What is the difference between RDB and AOF persistence in Redis?

RDB (Redis Database) creates point-in-time snapshots of the dataset at specified intervals. It produces compact binary files ideal for backups but may lose data between snapshots. AOF (Append Only File) logs every write operation, providing better durability since you can configure it to fsync every second or on every write. AOF files are larger but can be rewritten to stay compact. Many production deployments use both RDB and AOF together for the best combination of fast restarts (RDB) and minimal data loss (AOF).

How does Redis Cluster handle data sharding?

Redis Cluster automatically partitions data across multiple nodes using hash slots. The key space is divided into 16,384 hash slots, and each node in the cluster is responsible for a subset of these slots. When a key is stored, Redis computes its hash slot using CRC16(key) mod 16384 and routes it to the correct node. Redis Cluster also provides high availability through automatic failover: each master node can have one or more replica nodes that take over if the master fails.