Connection & Info

redis-cli                                          # Connect (default localhost:6379)
redis-cli -h <host> -p <port>                      # Connect to specific host/port
redis-cli --tls -u <conn_string> --cacert name.crt # Connect using TLS and CA

PING                   # Test connection (returns PONG)
INFO                   # Get server statistics and information
CONFIG GET *           # View all configuration parameters
HELLO                  # Basic server info

Key Operations

KEYS *                          # List all keys — NEVER in production, O(N) blocks server
SCAN 0                          # Iterate through keys safely (cursor-based)
SCAN 0 MATCH user:* COUNT 100   # Filtered cursor iteration

EXISTS <key>                    # Check if key exists
DEL <key>                       # Delete a key
TYPE <key>                      # Get the data type of a key
TTL <key>                       # Get time to live in seconds
EXPIRE <key> <seconds>          # Set expiration time
PERSIST <key>                   # Remove expiration from key
RENAME <oldkey> <newkey>        # Rename a key
MEMORY USAGE <key>              # Bytes consumed by key

String Operations

The atomic unit. Max 512 MB per value.

SET <key> <value>                    # Set a string value
SET <key> <value> EX <seconds>       # Set with expiration (replaces SETEX)
SET <key> <value> NX                 # Set only if not exists (replaces SETNX)
GET <key>                            # Get a string value
GETSET <key> <value>                 # Atomic swap — set and return old value
MGET <key1> <key2> ...               # Get multiple values

INCR <key>                           # Increment integer value by 1
DECR <key>                           # Decrement integer value by 1
INCRBY <key> <increment>             # Increment by specific amount
INCRBYFLOAT <key> <increment>        # Increment by float

APPEND <key> <value>                 # Append to string
STRLEN <key>                         # Get string length
GETRANGE <key> <start> <end>         # Get substring
SETRANGE <key> <offset> <value>      # Overwrite part of string

# Examples
SET user:1:name "Alice"
SET user:2:data "{\"hello\": \"world\"}"
SET session:user123 "alice" EX 3600
SET user:3:bin "\x63\x69\x61\x6F"   # Write in hex format
INCR visits
INCRBY visits 10

Hash Operations

The natural fit for structured objects. More memory-efficient than a JSON string when fields are accessed individually.

HSET <key> <field> <value>           # Set hash field (also accepts multiple field-value pairs)
HGET <key> <field>                   # Get hash field value
HMGET <key> <field1> <field2>        # Get multiple fields
HGETALL <key>                        # Get all fields and values
HDEL <key> <field>                   # Delete hash field
HKEYS <key>                          # Get all field names
HVALS <key>                          # Get all values
HLEN <key>                           # Get number of fields
HEXISTS <key> <field>                # Check if field exists
HINCRBY <key> <field> <increment>    # Increment hash field
HSCAN <key> <cursor>                 # Iterate hash fields

# Example
HSET user:1 name "Alice" age 30 role "architect"
HGET user:1 name
HGETALL user:1
HINCRBY user:1 age 1

List Operations

Backed by a doubly-linked list (or listpack for small sizes).

LPUSH <key> <value>                          # Push to list head
RPUSH <key> <value>                          # Push to list tail
LPOP <key>                                   # Pop from list head
RPOP <key>                                   # Pop from list tail
LRANGE <key> <start> <stop>                  # Get range (LRANGE key 0 -1 for all)
LLEN <key>                                   # Get list length
LINDEX <key> <index>                         # Get element by index
LSET <key> <index> <value>                   # Set element by index
LINSERT <key> BEFORE|AFTER <pivot> <value>   # Insert element
LTRIM <key> <start> <stop>                   # Trim list to range
BLPOP <key> <timeout>                        # Blocking pop from head
BRPOP <key> <timeout>                        # Blocking pop from tail
RPOPLPUSH <source> <dest>                    # Pop from one list, push to another
BRPOPLPUSH <source> <dest> <timeout>         # Blocking version

# Example
LPUSH jobs:queue job:3 job:2 job:1
RPUSH jobs:queue job:4
LRANGE jobs:queue 0 -1
BRPOP jobs:queue 30

Set Operations

Unordered collection of unique members (hashtable internally).

SADD <key> <member>                          # Add member to set
SMEMBERS <key>                               # Get all set members
SISMEMBER <key> <member>                     # O(1) membership check
SREM <key> <member>                          # Remove member from set
SCARD <key>                                  # Get set cardinality (size)
SPOP <key>                                   # Remove and return random member
SRANDMEMBER <key> <count>                    # Get random member(s)
SSCAN <key> <cursor>                         # Iterate set members

# Set algebra — great for tag intersection, friend-of-friend
SDIFF <key1> <key2>                          # Set difference
SINTER <key1> <key2>                         # Set intersection
SUNION <key1> <key2>                         # Set union
SDIFFSTORE <dest> <key1> <key2>              # Store difference result
SINTERSTORE <dest> <key1> <key2>             # Store intersection result
SUNIONSTORE <dest> <key1> <key2>             # Store union result

# Example
SADD tags:redis post:1 post:3
SADD tags:backend post:2 post:3
SINTER tags:redis tags:backend               # {post:3}

Sorted Set / ZSET Operations

The killer feature. Members sorted by a float score. O(log N) for most ops.

ZADD <key> <score> <member>                  # Add member with score
ZRANGE <key> <start> <stop>                  # Get range by index
ZRANGE <key> 0 -1 WITHSCORES REV            # Top to bottom with scores
ZRANGEBYSCORE <key> <min> <max>              # Get range by score
ZREVRANGE <key> <start> <stop>               # Get range in reverse order
ZREM <key> <member>                          # Remove member
ZCARD <key>                                  # Get sorted set size
ZCOUNT <key> <min> <max>                     # Count members in score range
ZINCRBY <key> <increment> <member>           # Increment member score
ZRANK <key> <member>                         # Get member rank (ascending)
ZREVRANK <key> <member>                      # Get member rank (descending)
ZSCORE <key> <member>                        # Get member score
ZREMRANGEBYRANK <key> <start> <stop>         # Remove by rank range
ZREMRANGEBYSCORE <key> <min> <max>           # Remove by score range
ZUNIONSTORE <dest> <numkeys> <key...>        # Union of sorted sets
ZINTERSTORE <dest> <numkeys> <key...>        # Intersection of sorted sets
ZSCAN <key> <cursor>                         # Iterate sorted set members
ZPOPMIN <key> <count>                        # Pop members with lowest scores
ZPOPMAX <key> <count>                        # Pop members with highest scores

# Use cases: leaderboards, priority queues, time-series indexes, geo
ZADD leaderboard 9500 "alice" 8200 "bob" 7100 "charlie"
ZRANGEBYSCORE leaderboard 8000 +inf
ZINCRBY leaderboard 300 "bob"

JSON (RedisJSON)

Nested documents with JSONPath access. Prefer over a serialized String when fields change independently.

JSON.SET <key> $ '<json>'          # Set JSON document
JSON.GET <key>                     # Get full document
JSON.GET <key> $.field             # Get specific field (JSONPath)
JSON.SET <key> $.field <value>     # Update specific field
JSON.NUMINCRBY <key> $.field <n>   # Increment numeric field
JSON.ARRAPPEND <key> $.array <val> # Append to array
JSON.DEL <key> $.field             # Delete field

# Example
JSON.SET user:1 $ '{"name":"Alice","age":30,"tags":["redis","architect"]}'
JSON.GET user:1 $.name
JSON.SET user:1 $.age 31
JSON.ARRAPPEND user:1 $.tags '"cache"'

Stream Operations

An append-only log with consumer groups — Kafka-lite.

XADD <key> * <field> <value>                        # Add entry to stream (* = auto ID)
XREAD STREAMS <key> <id>                            # Read from stream
XRANGE <key> <start> <end>                          # Get range of entries
XLEN <key>                                          # Get stream length

# Consumer groups
XGROUP CREATE <key> <group> <id>                    # Create consumer group
XREADGROUP GROUP <group> <consumer> STREAMS <key> > # Read as consumer
XACK <key> <group> <id>                             # Acknowledge message
XPENDING <key> <group>                              # Check pending messages
XAUTOCLAIM <key> <group> <consumer> <min-idle> 0    # Reclaim stale messages

# Example
XADD events:orders * order_id 42 amount 199.99 user alice
XGROUP CREATE events:orders shipping $ MKSTREAM
XREADGROUP GROUP shipping worker1 COUNT 5 STREAMS events:orders >
XACK events:orders shipping <message-id>

Pub/Sub (Messaging)

Fire-and-forget broadcast — no persistence, no consumer groups.

PUBLISH <channel> <message>        # Send message to channel
SUBSCRIBE <channel>                # Subscribe to channel(s)
PSUBSCRIBE <pattern>               # Subscribe using pattern matching
UNSUBSCRIBE <channel>              # Unsubscribe from channel
PUBSUB CHANNELS                    # List active channels
PUBSUB NUMSUB <channel>            # Get subscriber count for channels

# Example
# Terminal 1 - subscriber
SUBSCRIBE channel:notifications

# Terminal 2 - publisher
PUBLISH channel:notifications '{"event":"order_paid","id":42}'

# Pattern subscribe
PSUBSCRIBE channel:*

Transactions

MULTI          # Start transaction block
EXEC           # Execute all commands in transaction
DISCARD        # Cancel transaction
WATCH <key>    # Watch key for optimistic locking (CAS)
UNWATCH        # Clear all watched keys

Lua Scripting

Scripts run atomically on the server — no other commands execute in between. Use for read-modify-write sequences without transaction overhead.

EVAL <script> <numkeys> <key...> <arg...>   # Execute Lua script
EVALSHA <sha1> <numkeys> <key...> <arg...>  # Execute cached script
SCRIPT LOAD <script>                         # Load script into cache
SCRIPT EXISTS <sha1>                         # Check if script is cached
SCRIPT FLUSH                                 # Remove all cached scripts
SCRIPT KILL                                  # Kill running script

TypeScript example — rate limiter:

import { createClient } from 'redis'

const redis = createClient()
await redis.connect()

// KEYS[1] = rate limit key, ARGV[1] = limit, ARGV[2] = window TTL in seconds
const rateLimiter = `
  local current = redis.call('INCR', KEYS[1])
  if current == 1 then
    redis.call('EXPIRE', KEYS[1], ARGV[2])
  end
  return current
`

const key = 'ratelimit:user:42'
// In production: use SCRIPT LOAD + EVALSHA (or the client's built-in method) instead of EVAL
const count = await redis.eval(rateLimiter, { keys: [key], arguments: ['10', '60'] })
console.log(count <= 10 ? 'allowed' : 'rate limited')

Bit Operations (Bitmaps)

SETBIT <key> <offset> <value>              # Set bit at offset
GETBIT <key> <offset>                      # Get bit at offset
BITCOUNT <key>                             # Count set bits
BITOP AND|OR|XOR|NOT <destkey> <key...>    # Bitwise operations
BITPOS <key> <bit>                         # Find first bit set/clear

HyperLogLog (Cardinality Estimation)

Approximate unique count, fixed 12 KB, < 1% error.

PFADD <key> <element...>                   # Add elements
PFCOUNT <key...>                           # Get approximate count
PFMERGE <destkey> <sourcekey...>           # Merge HyperLogLogs

# Example
PFADD page:views:2024-01-01 user:1 user:2 user:3 user:1   # duplicates ignored
PFCOUNT page:views:2024-01-01                              # ≈ 3
PFMERGE page:views:week page:views:2024-01-01 page:views:2024-01-02

Probabilistic (Bloom Filter)

Built-in from Redis 8 via RedisBloom. Set membership with no false negatives.

BF.ADD <key> <item>                        # Add item to Bloom filter
BF.EXISTS <key> <item>                     # Check membership (may false-positive; never false-negative)
BF.MADD <key> <item...>                    # Add multiple items

# Example
BF.ADD blocklist "spam@example.com"
BF.EXISTS blocklist "spam@example.com"     # 1
BF.MADD blocklist "a@b.com" "c@d.com"

Geospatial

Coordinates encoded into a Sorted Set score. O(log N) radius queries.

GEOADD <key> <long> <lat> <member>                               # Add location
GEODIST <key> <member1> <member2> <unit>                         # Get distance
GEOPOS <key> <member>                                            # Get coordinates
GEOHASH <key> <member>                                           # Get geohash string
GEOSEARCH <key> FROMLONLAT <long> <lat> BYRADIUS <radius> <unit> # Query from coordinates
GEOSEARCH <key> FROMMEMBER <member> BYRADIUS <radius> <unit>     # Query from member

# Example
GEOADD locations 13.361389 38.115556 "Palermo" 15.087269 37.502669 "Catania"
GEODIST locations Palermo Catania km
GEOSEARCH locations FROMLONLAT 15 37 BYRADIUS 200 km ASC COUNT 5 WITHCOORD WITHDIST

Time Series (RedisTimeSeries)

Append-only timestamped metrics with built-in downsampling and aggregation.

TS.CREATE <key> RETENTION <ms> LABELS <label> <value>   # Create time series
TS.ADD <key> * <value>                                   # Add entry (* = auto timestamp)
TS.RANGE <key> <from> <to> COUNT <n>                    # Query range
TS.MGET FILTER <label>=<value>                           # Multi-key label query
TS.CREATERULE <src> <dest> AGGREGATION <func> <bucket>   # Downsampling rule

# Example
TS.CREATE cpu:host1 RETENTION 86400000 LABELS host host1 metric cpu
TS.ADD cpu:host1 * 72.5
TS.RANGE cpu:host1 - + COUNT 10
TS.CREATERULE cpu:host1 cpu:host1:5m AGGREGATION avg 300000

Vector Sets

Fixed-dimension float vectors for approximate nearest-neighbor search. Powers semantic search and RAG pipelines.

VADD <key> VALUES <dim> <v1> <v2> ... <member>   # Add vector
VSIM <key> VALUES <dim> <v1> <v2> ... COUNT <n>  # k-nearest neighbors
VCARD <key>                                       # Count vectors
VREM <key> <member>                               # Remove vector

# Example
VADD doc:embeddings VALUES 3 1.0 0.2 0.8 "doc:1"
VADD doc:embeddings VALUES 3 0.9 0.3 0.7 "doc:2"
VSIM doc:embeddings VALUES 3 1.0 0.1 0.9 COUNT 3

Database & Admin

SELECT <db>    # Switch to database number (0–15 by default)
FLUSHDB        # Clear current database
FLUSHALL       # Clear all databases
DBSIZE         # Get number of keys in current database
MONITOR        # Watch all commands in real-time (debug only)
SAVE           # Synchronous save to disk
BGSAVE         # Background save to disk
MOVE <key> <db> # Atomically move key to another database

Memory & Performance

MEMORY USAGE <key>         # Get memory used by key
MEMORY STATS               # Memory allocation stats
MEMORY DOCTOR              # Memory usage report
SLOWLOG GET <count>        # Get slow queries
SLOWLOG LEN                # Get slow log length
SLOWLOG RESET              # Clear slow log

Connection Management

CLIENT LIST                # List connected clients
CLIENT KILL <ip:port>      # Kill client connection
CLIENT SETNAME <name>      # Set client name
CLIENT GETNAME             # Get client name

Debug & Introspection

TYPE <key>                   # Get data type
OBJECT ENCODING <key>        # Get internal encoding (listpack vs hashtable)
OBJECT REFCOUNT <key>        # Get reference count
OBJECT IDLETIME <key>        # Get idle time in seconds
DEBUG OBJECT <key>           # Get debug info about key
DUMP <key>                   # Serialize key value
RESTORE <key> <ttl> <data>   # Restore serialized value

Cluster Commands

CLUSTER INFO                 # Get cluster information
CLUSTER NODES                # List all nodes
CLUSTER SLOTS                # Get slot assignments
CLUSTER KEYSLOT <key>        # Get hash slot for key

# CLI cluster management
redis-cli --cluster create host1:6379 host2:6379 ... --cluster-replicas 1
redis-cli --cluster rebalance host1:6379
redis-cli --cluster reshard host1:6379

CLI Options & Modes

redis-cli --scan --pattern "user:*"      # Search for keys by pattern
redis-cli --bigkeys                       # Find biggest keys
redis-cli --stat                          # Show continuous stats
redis-cli --latency                       # Measure latency
redis-cli --latency-history               # Latency history
redis-cli --intrinsic-latency <seconds>   # Measure system latency
redis-cli --rdb <filename>                # Download RDB backup
redis-cli --pipe                          # Pipe mode for mass insertion
redis-cli --csv                           # Output in CSV format
redis-cli --ldb                           # Start Lua debugger
redis-cli --eval <file> <keys> , <args>   # Execute Lua script from file