- How Do Redis Commands Work?
- Redis commands are:
- sent as plain text over TCP (default port 6379),
- case-insensitive for names (
SET == set),
- usually space-separated:
COMMAND key [arg1] [arg2].
- You can execute commands using:
redis-cli (interactive shell)
- Redis client libraries (Python, Node, Java, Go, ...)
- scripts / automation tools
- Key Management Commands
- These commands operate on keys regardless of their value type.
| Command |
Description |
Example |
SET key value |
Set key to hold the string value (overwrites any existing value). |
SET mykey "hello" |
GET key |
Get the value of key (or (nil) if not exists). |
GET mykey |
DEL key [key ...] |
Delete one or more keys; returns number of keys removed. |
DEL mykey otherkey |
EXISTS key [key ...] |
Return the number of keys that exist out of the given list. |
EXISTS mykey |
KEYS pattern |
Return all keys matching the pattern (use carefully in production). |
KEYS user:* |
SCAN cursor [MATCH pattern] [COUNT n] |
Incrementally iterate over keys (safer alternative to KEYS). |
SCAN 0 MATCH "user:*" COUNT 100 |
EXPIRE key seconds |
Set a time-to-live (TTL) in seconds. |
EXPIRE session:123 3600 |
TTL key |
Return remaining TTL in seconds (-1 = no TTL, -2 = key does not exist). |
TTL session:123 |
RENAME key newkey |
Rename key to newkey (overwrites newkey if exists). |
RENAME user:1 user:001 |
TYPE key |
Return the type of value stored at key (string, hash, list, set, zset, ...). |
TYPE user:1 |
# Example: simple lifecycle of a key
SET temp "value"
EXPIRE temp 10
TTL temp # see remaining life
GET temp # value until it expires
- String Commands
- Strings are the most basic Redis data type. They can store:
- text (JSON, HTML, tokens, ...)
- numbers (for counters)
- binary blobs
| Command |
Description |
Example |
SET key value |
Set the string value of a key. |
SET page:home "<html>...</html>" |
GET key |
Get the value of a key. |
GET page:home |
SETNX key value |
Set key only if it does not already exist (NX = not exists). |
SETNX lock:job1 1 |
INCR key |
Increment numeric value stored at key by 1 (creates key with value 0 if missing). |
INCR page:views |
INCRBY key increment |
Increment by a specified integer. |
INCRBY page:views 10 |
DECR key, DECRBY |
Decrement integer value (symmetrical to INCR). |
DECR stock:widgets |
APPEND key value |
Append the string value to the existing value. |
APPEND log "error: something happened\n" |
MSET key value [key value ...] |
Set multiple keys at once. |
MSET user:1:name "Alice" user:1:age "30" |
MGET key [key ...] |
Get multiple keys at once. |
MGET user:1:name user:1:age |
# Example: a simple page view counter
INCR page:/home
INCR page:/home
GET page:/home # "2"
- Hash Commands
- Hashes store field–value pairs under one key. They are good for:
- user profiles (name, email, age)
- configuration objects
- small structured records
| Command |
Description |
Example |
HSET key field value |
Set field in hash to value (creates hash if missing). |
HSET user:1 name "Alice" |
HGET key field |
Get value of field in hash. |
HGET user:1 name |
HMSET key field value [field value ...] |
Set multiple fields in hash (deprecated, but still widely used; new: HSET with multiple field/value pairs). |
HSET user:1 name "Alice" age "30" |
HGETALL key |
Get all fields and values in the hash. |
HGETALL user:1 |
HDEL key field [field ...] |
Delete one or more fields. |
HDEL user:1 age |
HLEN key |
Get number of fields in hash. |
HLEN user:1 |
HEXISTS key field |
Check if field exists in hash. |
HEXISTS user:1 email |
# Example: storing a user as a hash
HSET user:42 name "Alice" email "alice@example.com" age "30"
HGET user:42 email
HGETALL user:42
- List Commands
- Lists are ordered collections of strings. Efficient for:
- queues
- log-like data
- message buffers
| Command |
Description |
Example |
LPUSH key value [value ...] |
Push value(s) to the left (head) of the list. |
LPUSH queue "job1" |
RPUSH key value [value ...] |
Push value(s) to the right (tail) of the list. |
RPUSH queue "job2" |
LPOP key, RPOP key |
Remove and return first/last element. |
LPOP queue |
LRANGE key start stop |
Get sub-list by index range (0-based, inclusive; -1 = last). |
LRANGE queue 0 -1 |
LLEN key |
Get list length. |
LLEN queue |
BLPOP key [key ...] timeout |
Blocking pop from left; waits if list is empty. |
BLPOP queue 0 |
# Example: simple FIFO queue
RPUSH jobs "job1"
RPUSH jobs "job2"
LPOP jobs # "job1"
LPOP jobs # "job2"
- Set Commands
- Sets are unordered collections of unique strings. Good for:
- tags
- unique elements (no duplicates)
- simple membership queries
| Command |
Description |
Example |
SADD key member [member ...] |
Add one or more members to the set. |
SADD tags "redis" "database" |
SMEMBERS key |
Get all set members. |
SMEMBERS tags |
SISMEMBER key member |
Check if member is in the set (returns 1 or 0). |
SISMEMBER tags "redis" |
SREM key member [member ...] |
Remove one or more members. |
SREM tags "database" |
SCARD key |
Count members of set. |
SCARD tags |
SINTER key [key ...] |
Set intersection of multiple sets. |
SINTER tags:post1 tags:post2 |
SUNION key [key ...] |
Set union of multiple sets. |
SUNION tags:post1 tags:post3 |
SDIFF key [key ...] |
Set difference. |
SDIFF tags:all tags:archived |
# Example: tracking unique visitors by day
SADD visitors:2025-01-01 "user1"
SADD visitors:2025-01-01 "user2"
SCARD visitors:2025-01-01 # 2 unique visitors
- Sorted Set Commands (ZSET)
- Sorted sets are sets where each member has an associated numeric score.
- They are ideal for:
- leaderboards
- ranking by score (points, timestamps)
- time-series-ish use cases
| Command |
Description |
Example |
ZADD key score member [score member ...] |
Add member(s) with scores to sorted set. |
ZADD leaderboard 100 "alice" 200 "bob" |
ZRANGE key start stop [WITHSCORES] |
Get elements by rank (ascending, 0 = lowest score). |
ZRANGE leaderboard 0 -1 WITHSCORES |
ZREVRANGE key start stop [WITHSCORES] |
Get elements by rank (descending, highest score first). |
ZREVRANGE leaderboard 0 9 WITHSCORES |
ZINCRBY key increment member |
Increment score of member by given amount. |
ZINCRBY leaderboard 50 "alice" |
ZREM key member [member ...] |
Remove member(s) from sorted set. |
ZREM leaderboard "alice" |
ZRANK key member, ZREVRANK |
Get rank of member (0-based). |
ZRANK leaderboard "alice" |
# Example: game leaderboard
ZADD leaderboard 100 "alice"
ZADD leaderboard 200 "bob"
ZINCRBY leaderboard 50 "alice" # alice now 150
ZREVRANGE leaderboard 0 -1 WITHSCORES # bob then alice
- Transactions and Pipelining
- Redis supports a simple transaction mechanism using:
MULTI – start transaction
EXEC – execute queued commands
DISCARD – cancel transaction
- Pipelining is a client-side optimization where multiple commands are sent at once without waiting for individual replies.
# Example: a transaction
MULTI
INCR counter
INCR counter
GET counter
EXEC
- For optimistic locking, you can use:
WATCH key – watch keys for modifications
- if key changes before
EXEC, transaction aborts
# Pseudocode for WATCH usage
WATCH balance:user:1
current = GET balance:user:1
if current >= 10:
MULTI
DECRBY balance:user:1 10
INCRBY balance:store 10
EXEC
else:
UNWATCH
- Publish/Subscribe Commands (Pub/Sub)
- Redis includes a basic publish/subscribe messaging system.
- It is suitable for:
- lightweight notifications
- real-time updates broadcast
| Command |
Description |
Example |
SUBSCRIBE channel [channel ...] |
Subscribe to one or more channels. |
SUBSCRIBE news sports |
PUBLISH channel message |
Publish a message to a channel. |
PUBLISH news "breaking: ..." |
PSUBSCRIBE pattern [pattern ...] |
Subscribe to channels matching pattern. |
PSUBSCRIBE news.* |
# Terminal 1
SUBSCRIBE chat
# Terminal 2
PUBLISH chat "hello world"
- Server & Introspection Commands
- These help monitor and manage the Redis server.
| Command |
Description |
Example |
INFO |
Show server statistics (memory, clients, keys, CPU, etc.). |
INFO |
DBSIZE |
Return number of keys in the current database. |
DBSIZE |
FLUSHDB |
Delete all keys in the current database. |
FLUSHDB |
FLUSHALL |
Delete all keys in all databases. |
FLUSHALL |
CONFIG GET pattern |
Get configuration parameters. |
CONFIG GET maxmemory |
CONFIG SET parameter value |
Change configuration at runtime. |
CONFIG SET maxmemory 512mb |
- Putting It All Together: Small Example Application
- Imagine a mini application that needs:
- a user profile (hash)
- a login counter (string counter)
- a list of recent actions (list)
- a global leaderboard (sorted set)
# 1) Create user profile
HSET user:100 name "Alice" email "alice@example.com"
# 2) Increase login counter
INCR user:100:logins
# 3) Add an action to the activity list (keep last 50)
LPUSH user:100:actions "logged_in"
LTRIM user:100:actions 0 49
# 4) Update score in leaderboard
ZINCRBY leaderboard 10 "user:100"
# 5) Show top 3 users
ZREVRANGE leaderboard 0 2 WITHSCORES