---
title: "Redis"
lang: "en"
author: "Mohammad Abu Mattar"
canonical: https://mkabumattar.com/redis
---

0

[Home](/)›[Cheatsheets](/cheatsheets)

Cheatsheets

# Redis

Redis reference guide covering commands, data types, keys, strings, lists, sets, hashes, sorted sets, transactions, pub/sub, and caching strategies.

10 Categories32 Sections145 ExamplesPublished: 28 Feb 2026

[Markdown for AI(opens in a new tab)](/redis/index.md "Open the plain-Markdown version of this page, for pasting into an AI tool")

Series

[Databases & Data Persistence](/series/databases--data-persistence)2/2

[PreviousPostgreSQL](/cheatsheets/postgresql)

All posts in this series (2)

Cheatsheets2

1.  [PostgreSQL](/cheatsheets/postgresql)
2.  [RedisYou are here](/cheatsheets/redis)

Redis reference guide covering commands, data types, keys, strings, lists, sets, hashes, sorted sets, transactions, pub/sub, and caching strategies.

[Getting Started](#category-getting-started)

-   [Redis CLI Basics](#section-redis-cli-basics)
-   [INFO Command and Server Stats](#section-info-command)
-   [Configuration Commands](#section-configuration-commands)
-   [Connection Pooling Concepts](#section-connection-pooling)

[Keys Management](#category-keys-management)

-   [Key Deletion and Existence](#section-key-deletion-existence)
-   [Key Expiration and TTL](#section-key-expiration-ttl)
-   [Key Scanning and Enumeration](#section-key-scanning)
-   [Key Type Checking and Operations](#section-key-type-operations)
-   [Key Renaming and Moving](#section-key-renaming)

[String Operations](#category-strings)

-   [String Get and Set Operations](#section-string-get-set)
-   [String Manipulation Commands](#section-string-manipulation)
-   [String Numeric Operations](#section-string-numeric-operations)
-   [String Bit Operations](#section-string-bit-operations)

[List Operations](#category-lists)

-   [List Push and Pop Operations](#section-list-push-pop)
-   [List Range Operations](#section-list-range-operations)
-   [List Blocking Operations](#section-list-blocking-operations)

[Set Operations](#category-sets)

-   [Set Add and Remove Operations](#section-set-add-remove)
-   [Set Operations (Union, Intersection, Difference)](#section-set-operations)
-   [Set Advanced Operations](#section-set-advanced)

[Hash Operations](#category-hashes)

-   [Hash Get and Set Operations](#section-hash-get-set)
-   [Hash Numeric Operations](#section-hash-numeric-operations)
-   [Hash Scanning and Enumeration](#section-hash-scan)

[Sorted Sets Operations](#category-sorted-sets)

-   [Sorted Set Add and Remove Operations](#section-sorted-set-add-remove)
-   [Sorted Set Range Queries](#section-sorted-set-range-query)
-   [Sorted Set Increment Operations](#section-sorted-set-increment)

[Transactions & Scripting](#category-transactions-scripting)

-   [Transaction Basics](#section-transactions-basics)
-   [Lua Scripting](#section-lua-scripting)

[Pub/Sub & Streams](#category-pubsub-streams)

-   [Pub/Sub Basics](#section-pubsub-basics)
-   [Redis Streams](#section-redis-streams)

[Advanced Features](#category-advanced-features)

-   [Persistence (RDB and AOF)](#section-persistence-rdb-aof)
-   [Replication and Clustering](#section-replication-cluster)
-   [Memory Optimization](#section-memory-optimization)

No commands found

Try adjusting your search term

## Getting Started

### Redis CLI Basics

Connect and interact with Redis using redis-cli command-line tool

#### Accessibility

Beginner

#### Best Practices

-   Always authenticate when connecting to production servers
-   Use connection pooling in applications
-   Specify explicit port and host for clarity
-   Use SELECT carefully in scripts to avoid database number mistakes

#### Common Errors

-   **Connection refused:** Start the Redis server, or correct the host and port
-   **Authentication required:** Wrong or missing password with -a flag
-   **Database index out of range:** Valid indices are 0-15 for default config

#### Keywords

redis-cliconnectionauthenticationselect database

[Learn more](https://redis.io/commands/docs/)

#### Connect to Local Redis Default

Opens interactive Redis CLI session on localhost port 6379

Code

Terminal window

```
redis-cli
```

Execution

```
1127.0.0.1:6379>
```

-   Default Redis server runs on port 6379
-   Requires Redis server to be running
-   Ctrl+C to exit the CLI

#### Connect to Remote Redis Server

Connect to Redis on host redis.example.com with port 6380 and password authentication

Code

Terminal window

```
redis-cli -h redis.example.com -p 6380 -a yourpassword
```

Execution

```
1redis.example.com:6380>
```

-   \-h specifies hostname or IP address
-   \-p specifies custom port
-   \-a provides password authentication

#### Execute Command from Command Line

Execute a single command without entering interactive mode

Code

Terminal window

```
redis-cli PING
```

Execution

```
1PONG
```

-   Useful for scripts and automation
-   Returns result to stdout

#### Select Database Index

Switch to database 1 (Redis has 16 databases by default, indexed 0-15)

Code

Terminal window

```
redis-cli127.0.0.1:6379> SELECT 1
```

Execution

```
1OK2127.0.0.1:6379[1]>
```

-   Each database has separate keyspace
-   Default is database 0
-   Useful for testing without affecting production data

### INFO Command and Server Stats

Retrieve detailed Redis server information and statistics

#### Accessibility

Beginner

#### Best Practices

-   Monitor memory usage regularly to avoid eviction
-   Check maxmemory policy matches your use case
-   Use specific sections when integrating with monitoring tools
-   Track connected\_clients to detect connection leaks

#### Common Errors

-   **Wrong number of arguments:** Use INFO section\_name for specific info
-   **Parsing INFO output:** Numbers are strings in bash, cast to int if needed

#### Keywords

INFOserver statisticsmemory usageconnected clients

[Learn more](https://redis.io/commands/info/)

#### Get All Server Information

Displays all available server information across all sections

Code

Terminal window

```
redis-cli INFO
```

Execution

```
1# Server2redis_version:7.0.03redis_mode:standalone4os:Linux 5.15.0 x86_645arch_bits:646uptime_in_seconds:34567uptime_in_days:08# Clients9connected_clients:4210blocked_clients:011# Memory12used_memory:104857613used_memory_human:1.00M14maxmemory:015# Stats16total_connections_received:15617total_commands_processed:8923
```

-   Output is formatted in sections starting with
-   Large output on busy servers
-   Shows uptime, client count, memory usage, commands processed

#### Get Specific Section Only

Retrieve memory statistics only (more targeted than INFO all)

Code

Terminal window

```
redis-cli INFO memory
```

Execution

```
1# Memory2used_memory:20971523used_memory_human:2.00M4used_memory_rss:41943045maxmemory:10737418246maxmemory_human:1.00G7maxmemory_policy:noeviction
```

-   Available sections: server, clients, memory, persistence, stats, replication, cpu, cluster, modules
-   Useful for monitoring specific metrics

#### Check Connected Clients and Commands

Monitor requests per second and total throughput metrics

Code

Terminal window

```
redis-cli INFO stats
```

Execution

```
1# Stats2total_connections_received:5233total_commands_processed:125434instantaneous_ops_per_sec:455evicted_keys:3
```

-   ops\_per\_sec shows current command rate
-   evicted\_keys indicates memory pressure
-   Useful for performance monitoring

### Configuration Commands

View and modify Redis server configuration at runtime

#### Accessibility

Intermediate

#### Best Practices

-   Test configuration changes on non-production first
-   Always rewrite config after runtime changes you want to keep
-   Set maxmemory-policy based on use case (volatile-lru for caching)
-   Monitor memory with CONFIG GET to prevent OOM errors

#### Common Errors

-   **ERR Unknown CONFIG subcommand:** Check spelling of parameter name
-   **Config value out of range:** Use a value inside the valid range

#### Keywords

CONFIG GETCONFIG SETruntime configurationpersistence settings

[Learn more](https://redis.io/commands/config-get/)

#### Get Configuration Value

Retrieve current value of maxmemory configuration parameter

Code

Terminal window

```
redis-cli CONFIG GET maxmemory
```

Execution

```
11) "maxmemory"22) "1073741824"
```

-   Returns array with parameter name and value
-   Value is in bytes

#### Get Multiple Configuration Parameters

Use wildcard patterns to retrieve related parameters

Code

Terminal window

```
redis-cli CONFIG GET "max*"
```

Execution

```
11) "maxmemory"22) "1073741824"33) "maxmemory-policy"44) "noeviction"
```

-   Supports glob patterns like max\*, \*memory\*
-   Useful for exploring configuration space

#### Set Configuration Value

Change maxmemory to 2GB at runtime without restart

Code

Terminal window

```
redis-cli CONFIG SET maxmemory 2147483648
```

Execution

```
1OK
```

-   Not all parameters can be changed at runtime
-   Changes persist only during session unless saved to config file

#### Rewrite Configuration to File

Save all runtime configuration changes to the config file

Code

Terminal window

```
redis-cli CONFIG REWRITE
```

Execution

```
1OK
```

-   Preserves comments and structure of original file
-   Makes runtime changes permanent

### Connection Pooling Concepts

Managing Redis client connections and connection pools

#### Accessibility

Intermediate

#### Best Practices

-   Use connection pooling in applications (min 5, max 20 connections)
-   Monitor connected\_clients in production
-   Set reasonable PING intervals in pools to detect dead connections
-   Use CLIENT SETNAME to identify connection sources in logs

#### Common Errors

-   **Too many connections:** Increase maxclients or fix connection leak in code
-   **Connection reset by peer:** Check network stability and firewall rules

#### Keywords

connection poolingpersistent connectionsclient listHELLO protocol

[Learn more](https://redis.io/commands/client-list/)

#### List All Connected Clients

Display list of all clients connected to Redis server

Code

Terminal window

```
redis-cli CLIENT LIST
```

Execution

```
1id=1 addr=127.0.0.1:45678 fd=8 name= age=15 idle=0 flags=N db=0 sub=0 psub=0 multi=-12id=2 addr=127.0.0.1:45679 fd=9 name= age=2 idle=1 flags=N db=0 sub=0 psub=0 multi=-1
```

-   Each line represents one client connection
-   idle shows seconds since last command
-   flags: N=normal, d=dirty, R=readonly, etc.

#### Get Client Connection Count

Quick way to check current number of connected clients

Code

Terminal window

```
redis-cli INFO clients | grep connected_clients
```

Execution

```
1connected_clients:8
```

-   Monitor this metric to detect connection leaks
-   Compare with maxclients setting

#### Kill Idle Client Connection

Terminate specific client connection by address

Code

Terminal window

```
redis-cli CLIENT KILL 127.0.0.1:45678
```

Execution

```
1OK
```

-   Useful for removing stuck or idle connections
-   Client will reconnect if pool is configured

#### Set Client Name for Tracking

Assign name to current connection for monitoring purposes

Code

Terminal window

```
redis-cli CLIENT SETNAME "app-worker-1"
```

Execution

```
1OK
```

-   Visible in CLIENT LIST output
-   Helpful for debugging multiple connections

## Keys Management

### Key Deletion and Existence

Check existence and delete keys from Redis database

#### Accessibility

Beginner

#### Best Practices

-   Use UNLINK for large keys to avoid blocking
-   Check EXISTS before expensive operations
-   Batch deletes with multiple keys to cut round trips
-   Be cautious with DEL on patterns (use SCAN+DEL instead)

#### Common Errors

-   **Key not found errors:** DEL returns 0 for non-existent keys, not an error
-   **Using DEL with patterns:** Use SCAN+DEL, pattern matching not supported

#### Keywords

DELEXISTSUNLINKkey deletion

[Learn more](https://redis.io/commands/del/)

#### Delete Single Key

Create and delete a key, DEL returns number of keys deleted

Code

Terminal window

```
redis-cli SET mykey "Hello"redis-cli DEL mykey
```

Execution

```
1OK2(integer) 1
```

-   Returns the count of keys actually deleted
-   Returns 0 if key doesn't exist
-   Synchronous operation

#### Delete Multiple Keys

Delete multiple keys in one command, returns total deleted count

Code

Terminal window

```
redis-cli DEL user:1 user:2 user:3 session:abc
```

Execution

```
1(integer) 4
```

-   More efficient than multiple DEL commands
-   Atomic operation, deletes all or none

#### Check If Key Exists

Returns 1 if key exists, 0 if it doesn't

Code

Terminal window

```
redis-cli EXISTS mykey
```

Execution

```
1(integer) 1
```

-   Fast O(1) operation
-   Can check multiple keys, returns sum of existing keys

#### Check Multiple Keys for Existence

Returns count of how many keys exist among the given ones

Code

Terminal window

```
redis-cli EXISTS user:1 user:2 user:3 nonexistent
```

Execution

```
1(integer) 3
```

-   Useful for batch existence checks

#### Asynchronous Key Deletion

Non-blocking deletion, especially useful for large keys

Code

Terminal window

```
redis-cli UNLINK large_list large_hash large_set
```

Execution

```
1(integer) 3
```

-   Faster than DEL for large data structures
-   Deletes in background thread
-   Same return value as DEL

### Key Expiration and TTL

Set and manage key expiration times

#### Accessibility

Beginner

#### Best Practices

-   Always set expiration on temporary data (sessions, OTPs, cache)
-   Use appropriate TTL: sessions 1-24 hours, OTP 5-15 minutes, cache based on freshness
-   Monitor expired keys with CONFIG GET "lazyfree-lazy-eviction"
-   Set slightly longer TTL than needed to avoid premature expiration

#### Common Errors

-   **Key immediately disappears:** Check TTL immediately after setting
-   **TTL returns -2:** Key was already expired and removed
-   **Too short TTL:** Users see errors when key expires during their session

#### Keywords

EXPIRETTLEXPIREATPEXPIREpersistence settings

[Learn more](https://redis.io/commands/expire/)

#### Set Key Expiration in Seconds

Set key to expire in 3600 seconds (1 hour)

Code

Terminal window

```
redis-cli SET session:token "abc123xyz"redis-cli EXPIRE session:token 3600
```

Execution

```
1OK2(integer) 1
```

-   Returns 1 if timeout set, 0 if key doesn't exist
-   Session keys typically use EXPIRE

#### Check Remaining Time To Live

Returns seconds remaining until key expires

Code

Terminal window

```
redis-cli TTL session:token
```

Execution

```
1(integer) 3598
```

-   Returns -1 if key exists but has no expiration
-   Returns -2 if key doesn't exist
-   Use PTTL for millisecond precision

#### Set Millisecond Expiration

Set key to expire in exactly 5000 milliseconds (5 seconds)

Code

Terminal window

```
redis-cli PEXPIRE rate-limit:user123 5000
```

Execution

```
1(integer) 1
```

-   Useful for rate limiting and short-lived data
-   PTTL returns milliseconds remaining

#### Set Expiration at Unix Timestamp

Set key to expire at specific Unix timestamp (Jan 1, 2024)

Code

Terminal window

```
redis-cli EXPIREAT cache:data 1704067200
```

Execution

```
1(integer) 1
```

-   timestamp is in seconds since Unix epoch
-   Useful when you know exact expiration time

#### Remove Key Expiration

Remove expiration from key, making it permanent

Code

Terminal window

```
redis-cli PERSIST session:token
```

Execution

```
1(integer) 1
```

-   Returns 1 if timeout removed, 0 if already permanent or doesn't exist

#### Set Value with Expiration in One Command

Set key with value and 300-second expiration in single command

Code

Terminal window

```
redis-cli SET otp:email@example.com "654321" EX 300
```

Execution

```
1OK
```

-   EX = expire in seconds, PX = expire in milliseconds
-   More efficient than SET followed by EXPIRE
-   NX/XX options work with EX/PX

### Key Scanning and Enumeration

Iterate through keys without blocking Redis server

#### Accessibility

Intermediate

#### Best Practices

-   Always use SCAN for large datasets, never use KEYS pattern
-   Handle cursor=0 as end condition in loops
-   Use MATCH pattern to filter results server-side
-   Implement timeout to prevent infinite loops

#### Common Errors

-   **Using KEYS pattern in production:** Blocks entire server, use SCAN instead
-   **Infinite loops:** Forget to increment cursor or return to 0
-   **No results:** Add COUNT higher or check pattern matches existing keys

#### Keywords

SCANpattern matchingcursor iterationnon-blocking enumeration

[Learn more](https://redis.io/commands/scan/)

#### Scan All Keys with Cursor

Start scanning from cursor 0, returns next cursor and matching keys

Code

Terminal window

```
redis-cli SCAN 0
```

Execution

```
11) "2048"22) 1) "user:profile:123"3   2) "session:token:abc"4   3) "cache:homepage"
```

-   Returns \[next\_cursor, \[keys\]\]
-   Continue with cursor 2048 to get more keys
-   O(1) per iteration, doesn't block server

#### Scan with Pattern Match

Scan only keys matching "user:\*" pattern

Code

Terminal window

```
redis-cli SCAN 0 MATCH "user:*"
```

Execution

```
11) "1024"22) 1) "user:profile:1"3   2) "user:profile:2"4   3) "user:settings:100"
```

-   Pattern matching happens on server side
-   Still uses cursor iteration, not all-at-once retrieval

#### Scan with Count Hint

Return approximately 100 keys per iteration

Code

Terminal window

```
redis-cli SCAN 0 COUNT 100
```

Execution

```
11) "512"22) 1) "cache:data:1"3   2) "cache:data:2"4   3) "cache:data:3"
```

-   COUNT is hint, not strict count
-   Larger COUNT may return many keys
-   Useful for batch operations

#### Complete Scan Iteration in Bash

Loop through all keys matching pattern until cursor returns to 0

Code

Terminal window

```
cursor=0while true; do  result=$(redis-cli SCAN $cursor MATCH "session:*" COUNT 50)  cursor=$(echo "$result" | head -1)  echo "$result" | tail -1  [[ $cursor -eq 0 ]] && breakdone
```

Execution

```
1session:user12session:user23session:user34[... more sessions ...]
```

-   Proper way to enumerate all keys when using SCAN
-   Safe for production use

#### Scan Hash Fields

Scan fields of hash without loading all fields at once

Code

Terminal window

```
redis-cli HSCAN user:1:profile 0
```

Execution

```
11) "0"22) 1) "name"3   2) "John Doe"4   3) "email"5   4) "john@example.com"
```

-   Works similarly to SCAN with cursor-based iteration
-   Also available as SSCAN for sets, ZSCAN for sorted sets

### Key Type Checking and Operations

Determine and manipulate key data types

#### Accessibility

Intermediate

#### Best Practices

-   Check TYPE before operations that expect specific data type
-   Use DUMP/RESTORE for backup or cross-instance migration
-   Monitor MEMORY USAGE for large keys
-   Document your key naming conventions for type inference

#### Common Errors

-   **WRONGTYPE operation:** Wrong operation for key type (e.g., LPUSH on string)
-   **DUMP not matching between versions:** Different Redis versions may serialize differently

#### Keywords

TYPEDUMPRESTORECOPYMIGRATE

[Learn more](https://redis.io/commands/type/)

#### Check Key Data Type

Returns the data type of specified key

Code

Terminal window

```
redis-cli SET mystring "hello"redis-cli LPUSH mylist "item1"redis-cli TYPE mystringredis-cli TYPE mylist
```

Execution

```
1OK2(integer) 13string4list
```

-   Returns: string, list, set, zset, hash, stream
-   Returns "none" for non-existent keys

#### Dump and Restore Key

Serialize key content for backup or transfer

Code

Terminal window

```
redis-cli SET backup-key "important data"redis-cli DUMP backup-key
```

Execution

```
1OK2"\x00\x10important data\x09\x00\x8f\xf6\x8f\xf6\x00\x00\x00\x00"
```

-   Returns serialized value in Redis protocol format
-   Can be restored with RESTORE command in different instance

#### Copy Key to New Name

Create copy of key with new name

Code

Terminal window

```
redis-cli SET original-key "data"redis-cli COPY original-key backup-key
```

Execution

```
1OK2(integer) 1
```

-   Returns 1 on success, 0 if destination already exists
-   Use REPLACE option to overwrite destination

#### Get Key Memory Usage

Returns memory consumption of key in bytes

Code

Terminal window

```
redis-cli MEMORY USAGE mykey
```

Execution

```
1(integer) 56
```

-   Includes Redis internal overhead
-   Useful for finding keys that consume the most memory

### Key Renaming and Moving

Rename keys or move them to different databases

#### Accessibility

Intermediate

#### Best Practices

-   Use RENAMENX for safe renames to prevent data loss
-   Separate concerns by database when appropriate
-   Plan key naming conventions to minimize renaming
-   Consider key migration strategy for growing applications

#### Common Errors

-   **ERR no such key:** Source key doesn't exist
-   **Destination already exists:** Use RENAMENX to check first

#### Keywords

RENAMERENAMENXMOVEatomic operations

[Learn more](https://redis.io/commands/rename/)

#### Rename Key

Rename key atomically, old key is replaced with new name

Code

Terminal window

```
redis-cli SET old-name "content"redis-cli RENAME old-name new-nameredis-cli GET new-name
```

Execution

```
1OK2OK3"content"
```

-   Returns error if source key doesn't exist
-   Overwrites destination key if it exists

#### Rename Only If New Name Doesn't Exist

Rename only if destination key doesn't already exist

Code

Terminal window

```
redis-cli RENAMENX temp-data permanent-data
```

Execution

```
1(integer) 1
```

-   Returns 1 if renamed, 0 if destination exists
-   Useful for conditional renames

#### Move Key to Different Database

Atomically move key from one database to another

Code

Terminal window

```
redis-cli SELECT 0127.0.0.1:6379[0]> SET migration-key "data"127.0.0.1:6379[0]> MOVE migration-key 1127.0.0.1:6379[0]> SELECT 1127.0.0.1:6379[1]> GET migration-key
```

Execution

```
1OK2(integer) 13"data"
```

-   Returns 1 on success, 0 if key doesn't exist or destination exists
-   Useful for segregating data by type

## String Operations

### String Get and Set Operations

Store and retrieve string values with various options

#### Accessibility

Beginner

#### Best Practices

-   Use EX/PX directly in SET instead of separate EXPIRE command
-   Use MSET/MGET for multiple keys to reduce round trips
-   Use NX for locks and single-execution patterns
-   Validate JSON content before storing as strings

#### Common Errors

-   **Value too large: 512MB is max, compress if needed:**
-   **SET with NX returns nil:** Key already exists, use DEL first if needed

#### Keywords

SETGETGETSETMGETMSET

[Learn more](https://redis.io/commands/set/)

#### Set and Get Simple String

Basic string storage and retrieval

Code

Terminal window

```
redis-cli SET user:1:name "Alice"redis-cli GET user:1:name
```

Execution

```
1OK2"Alice"
```

-   Strings can be up to 512MB
-   GET returns nil if key doesn't exist

#### Get Multiple Keys At Once

Set multiple key-value pairs and retrieve them together

Code

Terminal window

```
redis-cli MSET user:1:name "Alice" user:2:name "Bob" user:3:name "Charlie"redis-cli MGET user:1:name user:2:name user:3:name
```

Execution

```
1OK21) "Alice"32) "Bob"43) "Charlie"
```

-   MGET is more efficient than multiple GET commands
-   Returns nil for non-existent keys in array

#### Get and Set New Value Atomically

Retrieve old value while setting new one in one operation

Code

Terminal window

```
redis-cli SET config:api-key "old-key-123"redis-cli GETSET config:api-key "new-key-456"
```

Execution

```
1OK2"old-key-123"
```

-   Returns BEFORE value, not after
-   Useful for rotating tokens or credentials

#### Set with Expiration Options

Set strings with automatic expiration in seconds (EX) or milliseconds (PX)

Code

Terminal window

```
redis-cli SET cache:homepage "<html>...</html>" EX 3600redis-cli SET cache:sidebar "{\"items\": [...]}" PX 5000
```

Execution

```
1OK2OK
```

-   EX = expire in seconds, PX = expire in milliseconds
-   Common pattern for cache data

#### Set Only If Key Doesn't Exist

Use NX to set only if key doesn't exist

Code

Terminal window

```
redis-cli SET user:registration:lock "processing" NXredis-cli SET user:registration:lock "done" NX
```

Execution

```
1OK2(nil)
```

-   Returns OK on success, nil if key already exists
-   Useful for distributed locks and single-execution patterns

#### Set Only If Key Already Exists

Use XX to set only if key already exists

Code

Terminal window

```
redis-cli SET counter "0"redis-cli SET counter "1" XXredis-cli SET nonexistent "value" XX
```

Execution

```
1OK2OK3(nil)
```

-   XX = only update existing keys
-   Prevents creating new keys accidentally

### String Manipulation Commands

Modify and manipulate string values

#### Accessibility

Intermediate

#### Best Practices

-   Use APPEND for building logs or messages incrementally
-   Validate string length before SETRANGE to avoid unexpected results
-   Use GETRANGE for extracting parts (email domain, etc.)
-   Consider JSON if frequent string manipulation is needed

#### Common Errors

-   **String not mutable like in programming languages:** Must use APPEND/SETRANGE
-   **Offset exceeds string length:** SETRANGE will extend with nulls

#### Keywords

APPENDSTRLENGETRANGESETRANGESUBSTR

[Learn more](https://redis.io/commands/append/)

#### Append to String

Add text to end of existing string, returns new length

Code

Terminal window

```
redis-cli SET message "Hello"redis-cli APPEND message " World"redis-cli GET message
```

Execution

```
1OK2(integer) 113"Hello World"
```

-   If key doesn't exist, APPEND creates it
-   Returns the length of string after appending

#### Get String Length

Get length of string value in characters

Code

Terminal window

```
redis-cli SET filename "document.pdf"redis-cli STRLEN filename
```

Execution

```
1OK2(integer) 12
```

-   Returns 0 for non-existent keys
-   O(1) operation

#### Get Substring from String

Extract substring using start and end positions

Code

Terminal window

```
redis-cli SET email "user@example.com"redis-cli GETRANGE email 0 3redis-cli GETRANGE email 5 -1
```

Execution

```
1OK2"user"3"example.com"
```

-   Supports negative indices from end of string
-   \-1 means last character

#### Set Substring in String

Replace portion of string starting at offset

Code

Terminal window

```
redis-cli SET data "Hello World"redis-cli SETRANGE data 6 "Redis"redis-cli GET data
```

Execution

```
1OK2(integer) 113"Hello Redis"
```

-   Extends with null bytes if necessary
-   Returns length of resulting string

### String Numeric Operations

Increment, decrement, and perform math on numeric strings

#### Accessibility

Intermediate

#### Best Practices

-   Use INCR for atomic counters without race conditions
-   Use INCRBY for batch increments (multiple page views)
-   INCRBYFLOAT for metrics like temperature, prices
-   Always verify numeric format before INCR/DECR

#### Common Errors

-   **ERR value is not an integer or out of range:** String is not numeric
-   **Negative numbers with INCR:** Results in negative counter, validate in code

#### Keywords

INCRDECRINCRBYDECRBYINCRBYFLOATGETEX

[Learn more](https://redis.io/commands/incr/)

#### Increment Integer Value

Increment numeric string by 1, returns new value

Code

Terminal window

```
redis-cli SET counter "10"redis-cli INCR counterredis-cli GET counter
```

Execution

```
1OK2(integer) 113"11"
```

-   String must be valid integer format
-   Returns error if not numeric
-   Atomic operation, safe for concurrent access

#### Increment by Specific Amount

Add specific value to numeric string

Code

Terminal window

```
redis-cli SET page-views:today "1000"redis-cli INCRBY page-views:today 50
```

Execution

```
1OK2(integer) 1050
```

-   Works with negative values for subtraction
-   Useful for counters and metrics

#### Decrement Value

Decrement value by 1 or specific amount

Code

Terminal window

```
redis-cli SET inventory:item-5 "100"redis-cli DECR inventory:item-5redis-cli DECRBY inventory:item-5 10
```

Execution

```
1OK2(integer) 993(integer) 89
```

-   Useful for stock management
-   DECRBY with negative number acts as increment

#### Increment Float Value

Add decimal increment to numeric string

Code

Terminal window

```
redis-cli SET temperature "20.5"redis-cli INCRBYFLOAT temperature 0.3redis-cli GET temperature
```

Execution

```
1OK2"20.8"3"20.8"
```

-   Accuracy of 17 digits
-   Returns new value as string

#### Get and Update Expiration

Get value and update its expiration in one command

Code

Terminal window

```
redis-cli SET rate-limit:ip "5" EX 60redis-cli GETEX rate-limit:ip EX 120
```

Execution

```
1OK2"5"
```

-   More efficient than GET + EXPIRE
-   Can also use EXAT, PERSIST options

### String Bit Operations

Bitwise operations on string values

#### Accessibility

Advanced

#### Best Practices

-   Use bit operations for compact flag/status storage
-   Combine with BITCOUNT to count set flags without reading them
-   Use BITOP for set operations on binary data
-   Document bit positions in comments for clarity

#### Common Errors

-   **BITOP result needs storage:** Must specify dest key in BITOP
-   **Confusing byte vs bit positions:** BITCOUNT uses bytes, bit operations use bits

#### Keywords

SETBITGETBITBITCOUNTBITOPBITPOS

[Learn more](https://redis.io/commands/setbit/)

#### Set Individual Bit

Set specific bit position and retrieve its value

Code

Terminal window

```
redis-cli SETBIT flags 7 1redis-cli GETBIT flags 7redis-cli GET flags
```

Execution

```
1(integer) 02(integer) 13"\x01"
```

-   Bit position is 0-indexed
-   Returns previous bit value
-   Useful for compact flag storage

#### Count Set Bits

Count number of 1 bits in string

Code

Terminal window

```
redis-cli SET bitmap "foobar"redis-cli BITCOUNT bitmap
```

Execution

```
1OK2(integer) 26
```

-   Can specify byte range to count
-   Useful for HyperLogLog-like operations

#### Bitwise Operations Between Values

Perform AND operation between two string values

Code

Terminal window

```
redis-cli SET key1 "foobar"redis-cli SET key2 "abcdef"redis-cli BITOP AND dest key1 key2redis-cli GET dest
```

Execution

```
1OK2OK3(integer) 64"`bc`ab"
```

-   Supports AND, OR, XOR, NOT operations
-   Returns length of result

#### Find First Set Bit

Find position of first bit set to 1

Code

Terminal window

```
redis-cli SETBIT bits 10 1redis-cli BITPOS bits 1
```

Execution

```
1(integer) 02(integer) 10
```

-   Can search for 0 bits as well
-   Returns -1 if no such bit exists

## List Operations

### List Push and Pop Operations

Add and remove elements from list begins and ends

#### Accessibility

Beginner

#### Best Practices

-   Use lists for queues and stacks (FIFO/LIFO patterns)
-   Batch pop operations to reduce network round trips
-   Avoid accessing middle elements frequently (use sets instead)
-   Monitor list length to detect unexpectedly large lists

#### Common Errors

-   **Using LINDEX on large lists:** O(n) operation, slow for millions
-   **Empty list operations:** LPOP on empty list returns nil, not error

#### Keywords

LPUSHRPUSHLPOPRPOPLLENLINDEX

[Learn more](https://redis.io/commands/lpush/)

#### Push Elements to List

Add elements to left (beginning) of list, returns list length

Code

Terminal window

```
redis-cli LPUSH notifications "message1"redis-cli LPUSH notifications "message2" "message3"redis-cli LLEN notifications
```

Execution

```
1(integer) 12(integer) 33(integer) 3
```

-   LPUSH adds to beginning, RPUSH adds to end
-   Returns length after push operation
-   Can push multiple items at once

#### Pop Elements from List

Remove and return element from left or right side

Code

Terminal window

```
redis-cli LPOP notificationsredis-cli RPOP notificationsredis-cli LLEN notifications
```

Execution

```
1"message3"2"message1"3(integer) 1
```

-   LPOP removes from beginning (newest first LIFO)
-   RPOP removes from end
-   Returns nil if list is empty

#### Pop Multiple Elements

Remove multiple elements from list in single command

Code

Terminal window

```
redis-cli RPUSH queue "task1" "task2" "task3" "task4"redis-cli LPOP queue 2
```

Execution

```
1(integer) 421) "task1"32) "task2"
```

-   COUNT parameter specifies how many to pop
-   Reduces round trips for batch processing

#### Get Element at Index

Access element at specific position without removing it

Code

Terminal window

```
redis-cli LINDEX notifications 0redis-cli LINDEX notifications -1
```

Execution

```
1"message2"2"message1"
```

-   0 is first element, -1 is last element
-   Returns nil if index out of range
-   O(n) operation, slower for large lists

#### Get List Length

Return number of elements in list

Code

Terminal window

```
redis-cli LLEN notifications
```

Execution

```
1(integer) 2
```

-   Returns 0 for empty or non-existent keys
-   O(1) operation

### List Range Operations

Get, set, and trim ranges of list elements

#### Accessibility

Intermediate

#### Best Practices

-   Use LRANGE with 0 -1 to get all elements (up to reasonable size)
-   LTRIM to keep only recent items (e.g., last 1000 messages)
-   Don't use LINSERT on large lists (O(n) operation)
-   Use LMOVE for atomic queue rotation

#### Common Errors

-   **LSET on non-existent index:** Out of range error, size list first
-   **LINSERT with wrong pivot:** Returns -1, value not found in list

#### Keywords

LRANGELSETLTRIMLINSERTLMOVE

[Learn more](https://redis.io/commands/lrange/)

#### Get Range of Elements

Get elements between start and end indices (inclusive)

Code

Terminal window

```
redis-cli RPUSH mylist "one" "two" "three" "four" "five"redis-cli LRANGE mylist 0 2redis-cli LRANGE mylist -2 -1
```

Execution

```
1(integer) 521) "one"32) "two"43) "three"51) "four"62) "five"
```

-   Supports negative indices from end
-   0 to -1 returns all elements
-   Returns empty array if range is invalid

#### Trim List to Range

Keep only elements in specified range, delete others

Code

Terminal window

```
redis-cli LTRIM mylist 0 2redis-cli LRANGE mylist 0 -1
```

Execution

```
1OK21) "one"32) "two"43) "three"
```

-   Efficient way to limit list size
-   Commonly used to keep only recent items

#### Set Element at Index

Update element at specific position

Code

Terminal window

```
redis-cli LSET mylist 1 "TWO"redis-cli LINDEX mylist 1
```

Execution

```
1OK2"TWO"
```

-   Returns error if index out of range
-   O(n) operation

#### Insert Element Before or After Position

Insert element before or after first occurrence of pivot value

Code

Terminal window

```
redis-cli LINSERT mylist BEFORE "TWO" "1.5"redis-cli LRANGE mylist 0 -1
```

Execution

```
1(integer) 421) "one"32) "1.5"43) "TWO"54) "three"
```

-   Returns -1 if pivot not found
-   O(n) operation, slow for large lists

#### Move Element Between Lists

Atomically move element from source to destination list

Code

Terminal window

```
redis-cli RPUSH source "a" "b" "c"redis-cli LMOVE source dest LEFT RIGHTredis-cli LRANGE source 0 -1redis-cli LRANGE dest 0 -1
```

Execution

```
1(integer) 32"a"31) "b"42) "c"51) "a"
```

-   LEFT=pop from left, RIGHT=pop from right
-   Destination receives from left or right
-   Useful for rotating between lists

### List Blocking Operations

Block and wait for list operations with timeout

#### Accessibility

Advanced

#### Best Practices

-   Use BLPOP for worker processes waiting on task queues
-   Set appropriate timeout (0 for infinite, or business timeout)
-   Use BRPOPLPUSH for task states (pending→processing→done)
-   Handle nil return when timeout occurs

#### Common Errors

-   **Blocking forever:** Set reasonable timeout to prevent zombie connections
-   **Wrong order of arguments:** Timeout is last parameter

#### Keywords

BLPOPBRPOPBRPOPLPUSHBLMOVEtimeout

[Learn more](https://redis.io/commands/blpop/)

#### Blocking Pop Left

Block until element available in list or timeout reached

Code

Terminal window

```
redis-cli BLPOP task-queue 0# On another client:# LPUSH task-queue "process-image.jpg"
```

Execution

```
1# Waits until element available or timeout21) "task-queue"32) "process-image.jpg"
```

-   Timeout 0 = wait forever
-   Returns \[key, value\] when element available
-   Multiple clients can block on same key

#### Blocking Pop with Timeout

Return nil if nothing available after 5 seconds

Code

Terminal window

```
redis-cli BLPOP empty-queue 5
```

Execution

```
1# Waits 5 seconds then returns nil2(nil)
```

-   Timeout in seconds
-   Useful for poll-based checking

#### Blocking Pop from Multiple Queues

Wait for element from any of multiple lists

Code

Terminal window

```
redis-cli BLPOP queue1 queue2 queue3 0
```

Execution

```
11) "queue2"22) "item-from-queue2"
```

-   Returns as soon as element available in any list
-   Last parameter is timeout
-   Useful for priority queue patterns

#### Block and Move Between Lists

Atomically pop from one list and push to another with blocking

Code

Terminal window

```
redis-cli BLMOVE source dest LEFT RIGHT 5
```

Execution

```
1"moved-element"
```

-   Returns popped element or nil on timeout
-   Atomic operation, no race conditions

#### Blocking Pop and Push Pattern

Pop from pending, push to processing atomically

Code

Terminal window

```
redis-cli BRPOPLPUSH pending-tasks processing-tasks 10
```

Execution

```
1"task-123"
```

-   Useful for task processing with automatic movement
-   Element stays in processing list until explicitly removed

## Set Operations

### Set Add and Remove Operations

Manage set membership and size

#### Accessibility

Beginner

#### Best Practices

-   Use sets for membership testing (fast O(1) lookups)
-   Use sets for unique collections (tags, followers, permissions)
-   Use SCAN for large sets instead of SMEMBERS
-   Batch SADD operations when possible

#### Common Errors

-   **Using SMEMBERS on large set:** Returns all at once, may block server
-   **Expecting ordered results:** Sets have no order, use sorted sets if needed

#### Keywords

SADDSREMSCARDSMEMBERSSISMEMBER

[Learn more](https://redis.io/commands/sadd/)

#### Add Elements to Set

Add members to set, duplicates are ignored

Code

Terminal window

```
redis-cli SADD tags "python" "redis" "database"redis-cli SADD tags "python"redis-cli SCARD tags
```

Execution

```
1(integer) 32(integer) 03(integer) 3
```

-   Returns count of newly added members (not duplicates)
-   Second SADD returns 0 because "python" already exists

#### Check Set Membership

Check if element is member of set

Code

Terminal window

```
redis-cli SISMEMBER tags "python"redis-cli SISMEMBER tags "go"
```

Execution

```
1(integer) 12(integer) 0
```

-   Returns 1 if member, 0 if not
-   O(1) operation

#### Check Multiple Members

Check membership of multiple elements in single command

Code

Terminal window

```
redis-cli SMISMEMBER tags "python" "redis" "go"
```

Execution

```
11) (integer) 122) (integer) 133) (integer) 0
```

-   Returns array of 1/0 for each element

#### Remove Elements from Set

Remove members from set, returns count removed

Code

Terminal window

```
redis-cli SREM tags "database" "go"redis-cli SCARD tags
```

Execution

```
1(integer) 12(integer) 2
```

-   Only "database" was removed (exists), "go" returned count 1

#### Get All Set Members

Return all members of set (unordered)

Code

Terminal window

```
redis-cli SMEMBERS tags
```

Execution

```
11) "python"22) "redis"
```

-   Order is not guaranteed
-   Use SCAN for large sets to avoid blocking
-   Returns array of members

### Set Operations (Union, Intersection, Difference)

Combine and compare sets

#### Accessibility

Intermediate

#### Best Practices

-   Use SINTER for access control (user has all required permissions)
-   Use SUNION for OR logic (has role-A OR role-B)
-   Use SDIFF to find exclusive items (users who haven't redeemed)
-   Use \*STORE to cache results of expensive operations

#### Common Errors

-   **Empty result from SINTER:** Check all sets contain expected members
-   **Wrong argument order for SDIFF:** First set minus others, not symmetric

#### Keywords

SINTERSUNIONSDIFFSINTERSTORESUNIONSTORESDIFFSTORE

[Learn more](https://redis.io/commands/sinter/)

#### Find Common Elements (Intersection)

Find elements common to both sets

Code

Terminal window

```
redis-cli SADD users:online "alice" "bob" "charlie"redis-cli SADD users:premium "bob" "charlie" "dave"redis-cli SINTER users:online users:premium
```

Execution

```
1(integer) 32(integer) 331) "bob"42) "charlie"
```

-   Returns only members in ALL specified sets
-   Useful for finding users with multiple properties

#### Combine All Elements (Union)

Get all unique members from both sets

Code

Terminal window

```
redis-cli SUNION users:online users:premium
```

Execution

```
11) "alice"22) "bob"33) "charlie"44) "dave"
```

-   Combines all elements, removes duplicates
-   Useful for permissions (any admin OR any moderator)

#### Find Unique Elements (Difference)

Find elements in first set but not in others

Code

Terminal window

```
redis-cli SDIFF users:online users:premium
```

Execution

```
11) "alice"
```

-   Order of sets matter (first set minus others)
-   Useful for finding exclusive members

#### Store Operation Result

Perform operation and store result in new set

Code

Terminal window

```
redis-cli SINTERSTORE premium-online users:online users:premiumredis-cli SMEMBERS premium-online
```

Execution

```
1(integer) 221) "bob"32) "charlie"
```

-   \*STORE variants return count of result elements
-   Useful for caching computed results

#### Find Multi-Set Intersection

Find members in all three sets

Code

Terminal window

```
redis-cli SADD readers "alice" "bob" "charlie" "dave"redis-cli SADD writers "bob" "charlie" "eve"redis-cli SADD editors "charlie" "frank"redis-cli SINTER readers writers editors
```

Execution

```
11) "charlie"
```

-   Only "charlie" is in readers AND writers AND editors

### Set Advanced Operations

Advanced set operations and management

#### Accessibility

Intermediate

#### Best Practices

-   Use SPOP for removing random samples
-   Use SRANDMEMBER for sampling without removal
-   Use SMOVE for state transitions between sets
-   Use SSCAN for large sets instead of SMEMBERS

#### Common Errors

-   **SPOP on empty set:** Returns nil without error
-   **SMOVE with non-existent member:** Returns 0, not error

#### Keywords

SPOPSRANDMEMBERSMOVESSCAN

[Learn more](https://redis.io/commands/spop/)

#### Remove and Return Random Member

Remove and return random element(s) from set

Code

Terminal window

```
redis-cli SADD lottery-pool "ticket-1" "ticket-2" "ticket-3" "ticket-4" "ticket-5"redis-cli SPOP lottery-poolredis-cli SPOP lottery-pool 2
```

Execution

```
1(integer) 52"ticket-3"31) "ticket-1"42) "ticket-5"
```

-   Single member removes one, with count removes multiple
-   Useful for random selection and removal (lottery, queue)

#### Get Random Members Without Removal

Return random members without removing them

Code

Terminal window

```
redis-cli SRANDMEMBER users:activeredis-cli SRANDMEMBER users:active 3
```

Execution

```
1"bob"21) "alice"32) "charlie"43) "bob"
```

-   Count can exceed set size (with repetition)
-   Negative count allows duplicates

#### Move Member Between Sets

Move member from source set to destination set

Code

Terminal window

```
redis-cli SADD users:online "alice"redis-cli SMOVE users:online users:offline "alice"redis-cli SISMEMBER users:online "alice"redis-cli SISMEMBER users:offline "alice"
```

Execution

```
1(integer) 12(integer) 13(integer) 04(integer) 1
```

-   Returns 1 if moved, 0 if not found in source
-   Atomic operation

#### Scan Large Set

Iterate through set using cursor without blocking

Code

Terminal window

```
redis-cli SSCAN users:active 0 COUNT 50
```

Execution

```
11) "2048"22) 1) "user:1"3   2) "user:2"4   3) "user:3"
```

-   Returns \[cursor, \[members\]\]
-   Use cursor 0 to start, continue until 0 returned

## Hash Operations

### Hash Get and Set Operations

Store and retrieve hash field-value pairs

#### Accessibility

Beginner

#### Best Practices

-   Use hashes for multi-field objects (user profiles, configs)
-   Set multiple fields at once to reduce network calls
-   Use HSCAN for large hashes instead of HGETALL
-   Structure as hash instead of multiple strings for related data

#### Common Errors

-   **Using HGETALL on large hash:** May block server, use HSCAN instead
-   **Field not found:** HGET returns nil, not an error

#### Keywords

HSETHGETHMSETHMGETHGETALLHDEL

[Learn more](https://redis.io/commands/hset/)

#### Set and Get Hash Fields

Set multiple hash fields and retrieve individual ones

Code

Terminal window

```
redis-cli HSET user:1 name "Alice" email "alice@example.com" age "30"redis-cli HGET user:1 nameredis-cli HGET user:1 email
```

Execution

```
1(integer) 32"Alice"3"alice@example.com"
```

-   HSET can set multiple field-value pairs at once
-   Returns count of new fields added
-   HGET returns nil if field doesn't exist

#### Get Multiple Hash Fields

Retrieve multiple fields in single command

Code

Terminal window

```
redis-cli HMGET user:1 name age country
```

Execution

```
11) "Alice"22) "30"33) (nil)
```

-   Returns array with nil for non-existent fields
-   More efficient than multiple HGET calls

#### Get All Hash Fields and Values

Retrieve all field-value pairs from hash

Code

Terminal window

```
redis-cli HGETALL user:1
```

Execution

```
11) "name"22) "Alice"33) "email"44) "alice@example.com"55) "age"66) "30"
```

-   Returns flattened array \[field1, value1, field2, value2, ...\]
-   For large hashes, use HSCAN to avoid blocking

#### Delete Hash Fields

Remove fields from hash, returns count deleted

Code

Terminal window

```
redis-cli HDEL user:1 age countryredis-cli HLEN user:1
```

Execution

```
1(integer) 12(integer) 2
```

-   "age" was deleted (1), "country" didn't exist (not counted)
-   HLEN shows remaining fields

#### Check Field Existence

Check if specific field exists in hash

Code

Terminal window

```
redis-cli HEXISTS user:1 nameredis-cli HEXISTS user:1 age
```

Execution

```
1(integer) 12(integer) 0
```

-   Returns 1 if exists, 0 if not
-   O(1) operation

### Hash Numeric Operations

Increment and perform math on hash fields

#### Accessibility

Intermediate

#### Best Practices

-   Use HINCRBY for counters in hash fields
-   Use HINCRBYFLOAT for averaged metrics
-   Use HSETNX to prevent overwriting configured values
-   Validate numeric fields before incrementing

#### Common Errors

-   **ERR hash value is not an integer:** Field contains non-numeric value
-   **HSETNX on existing field:** Returns 0, field not updated

#### Keywords

HINCRBYHINCRBYFLOATHSETNX

[Learn more](https://redis.io/commands/hincrby/)

#### Increment Integer Hash Field

Decrement (negative increment) stock field in hash

Code

Terminal window

```
redis-cli HSET product:1 price 100 stock 50redis-cli HINCRBY product:1 stock -5redis-cli HGET product:1 stock
```

Execution

```
1(integer) 22(integer) 453"45"
```

-   Useful for inventory management
-   Returns new value after increment

#### Increment Float Hash Field

Add decimal value to hash field

Code

Terminal window

```
redis-cli HSET stats:page daily-avg 2.5redis-cli HINCRBYFLOAT stats:page daily-avg 0.3redis-cli HGET stats:page daily-avg
```

Execution

```
1(integer) 12"2.8"3"2.8"
```

-   Useful for floating point metrics
-   Returns new value as string

#### Set Field Only If Doesn't Exist

Set field only if it doesn't already have a value

Code

Terminal window

```
redis-cli HSETNX user:profile avatar "default.jpg"redis-cli HSETNX user:profile avatar "custom.jpg"
```

Execution

```
1(integer) 12(integer) 0
```

-   Returns 1 if field set, 0 if already existed
-   Useful for defaults and initialization

### Hash Scanning and Enumeration

Iterate through hash fields without blocking

#### Accessibility

Intermediate

#### Best Practices

-   Use HKEYS/HVALS when you know hash is small
-   Use HSCAN for large hashes with millions of fields
-   Monitor HLEN to detect abnormal growth
-   Use field names with consistent prefixes for HSCAN patterns

#### Common Errors

-   **HGETALL on large hash:** Can block server, use HSCAN instead
-   **MATCH in HSCAN without results:** Pattern might not match fields

#### Keywords

HSCANHKEYSHVALSHLENHSTRLEN

[Learn more](https://redis.io/commands/hscan/)

#### Get All Hash Field Names

Return all field names from hash

Code

Terminal window

```
redis-cli HKEYS user:1
```

Execution

```
11) "name"22) "email"33) "phone"
```

-   Order not guaranteed
-   Use HSCAN for large hashes instead

#### Get All Hash Values

Return all values without field names

Code

Terminal window

```
redis-cli HVALS user:1
```

Execution

```
11) "Alice"22) "alice@example.com"33) "555-1234"
```

-   Returns array of values only

#### Get Hash Field Count

Count number of fields in hash

Code

Terminal window

```
redis-cli HLEN user:1
```

Execution

```
1(integer) 3
```

-   O(1) operation
-   Returns 0 for non-existent hash

#### Scan Hash Fields with Pattern

Scan hash fields matching pattern without blocking

Code

Terminal window

```
redis-cli HSCAN config:app 0 MATCH "*-timeout" COUNT 10
```

Execution

```
11) "2048"22) 1) "api-timeout"3   2) "30000"4   3) "db-timeout"5   4) "5000"
```

-   Returns \[cursor, \[field1, value1, field2, value2, ...\]\]
-   Cursor-based iteration like SCAN

#### Get String Length of Hash Field Value

Return byte length of specific field's value

Code

Terminal window

```
redis-cli HSTRLEN user:1 email
```

Execution

```
1(integer) 19
```

-   Useful for validation without retrieving value

## Sorted Sets Operations

### Sorted Set Add and Remove Operations

Manage sorted set members with scores

#### Accessibility

Intermediate

#### Best Practices

-   Use sorted sets for leaderboards, rankings, scored data
-   Use ZREVRANGE 0 n-1 for top-N queries
-   Batch ZADD operations to reduce round trips
-   Monitor ZCARD to detect unusual growth

#### Common Errors

-   **Score is not a number:** Must be numeric or inf/-inf
-   **Confusing ZRANGE order: 0 is lowest score, not first added:**

#### Keywords

ZADDZREMZCARDZRANGEZREVRANGEZSCORE

[Learn more](https://redis.io/commands/zadd/)

#### Add Members with Scores

Add members to sorted set with numeric scores

Code

Terminal window

```
redis-cli ZADD leaderboard 100 "player1" 150 "player2" 120 "player3"redis-cli ZCARD leaderboard
```

Execution

```
1(integer) 32(integer) 3
```

-   Members sorted by score in ascending order
-   Duplicate members update score

#### Get Range by Index

Get members in score order, optionally with scores

Code

Terminal window

```
redis-cli ZRANGE leaderboard 0 -1redis-cli ZRANGE leaderboard 0 -1 WITHSCORES
```

Execution

```
11) "player1"22) "player3"33) "player2"41) "player1"52) "100"63) "player3"74) "120"85) "player2"96) "150"
```

-   0 = lowest score, -1 = highest score
-   WITHSCORES returns interleaved scores

#### Get Range in Reverse Order

Get top scorers in descending order

Code

Terminal window

```
redis-cli ZREVRANGE leaderboard 0 2 WITHSCORES
```

Execution

```
11) "player2"22) "150"33) "player3"44) "120"55) "player1"66) "100"
```

-   ZREVRANGE returns highest scores first
-   Common pattern for leaderboards

#### Get Member Rank

Get position of member in sorted set

Code

Terminal window

```
redis-cli ZRANK leaderboard "player1"redis-cli ZREVRANK leaderboard "player1"
```

Execution

```
1(integer) 02(integer) 2
```

-   ZRANK = position from low to high
-   ZREVRANK = position from high to low
-   0-indexed

#### Get Member Score

Retrieve score of specific member

Code

Terminal window

```
redis-cli ZSCORE leaderboard "player2"
```

Execution

```
1"150"
```

-   Returns nil if member doesn't exist

#### Remove Members

Remove members from sorted set

Code

Terminal window

```
redis-cli ZREM leaderboard "player3" "nonexistent"redis-cli ZCARD leaderboard
```

Execution

```
1(integer) 12(integer) 2
```

-   Returns count of actually removed members

### Sorted Set Range Queries

Query sorted sets by score or lexicographical range

#### Accessibility

Intermediate

#### Best Practices

-   Use ZRANGEBYSCORE for score-based filtering (ratings > 4.0)
-   Use ZCOUNT to quickly find count of items in range
-   Combine with LIMIT for pagination of large ranges
-   Use ZRANGEBYLEX for alphabetical listings

#### Common Errors

-   **Wrong syntax for ranges:** Use (9 for exclusive, not <>9
-   **ZRANGEBYLEX without equal scores:** Only works if all scores are equal

#### Keywords

ZRANGEBYSCOREZREVRANGEBYSCOREZRANGEBYLEXZCOUNTZLEXCOUNT

[Learn more](https://redis.io/commands/zrangebyscore/)

#### Get Members in Score Range

Get all members with scores in range \[7, 9\]

Code

Terminal window

```
redis-cli ZADD product-scores 8.2 "item-1" 7.5 "item-2" 9.1 "item-3" 6.8 "item-4"redis-cli ZRANGEBYSCORE product-scores 7 9 WITHSCORES
```

Execution

```
11) "item-2"22) "7.5"33) "item-1"44) "8.2"55) "item-3"66) "9.1"
```

-   Inclusive range by default
-   Use (score for exclusive range

#### Query with Score Limits

Get range with exclusive upper bound and pagination

Code

Terminal window

```
redis-cli ZRANGEBYSCORE product-scores 7 (9 LIMIT 0 2
```

Execution

```
11) "item-2"22) "item-1"
```

-   (9 means score < 9 (exclusive)
-   LIMIT offset count for pagination

#### Get All Members with Minimum Score

Use +inf for scores greater than value

Code

Terminal window

```
redis-cli ZRANGEBYSCORE product-scores 8 +inf
```

Execution

```
11) "item-1"22) "item-3"
```

-   \-inf for minimum scores
-   inf without + means non-existent

#### Count Members in Score Range

Count members without retrieving them

Code

Terminal window

```
redis-cli ZCOUNT product-scores 7 9
```

Execution

```
1(integer) 3
```

-   Returns count of members in range
-   O(log n) operation

#### Lexicographical Range (Members with Equal Scores)

Query members lexicographically when scores are equal

Code

Terminal window

```
redis-cli ZADD colors 0 "black" 0 "blue" 0 "green" 0 "red"redis-cli ZRANGEBYLEX colors "[b" "[g"
```

Execution

```
11) "black"22) "blue"33) "green"
```

-   All members must have same score
-   "\[" = inclusive, "(" = exclusive boundary

### Sorted Set Increment Operations

Modify scores and manage sorted set members

#### Accessibility

Intermediate

#### Best Practices

-   Use ZINCRBY to update scores atomically
-   Use ZPOPMIN for processing by priority
-   Use BZPOPMIN for worker processes
-   Validate score updates don't cause data anomalies

#### Common Errors

-   **Score overflow:** Redis handles large numbers but plan for growth
-   **BZPOPMIN timing out:** Check if producer is adding items

#### Keywords

ZINCRBYZPOPMINZPOPMAXBZPOPMINBZPOPMAX

[Learn more](https://redis.io/commands/zincrby/)

#### Increment Member Score

Increase score of member, returns new score

Code

Terminal window

```
redis-cli ZADD ratings user:1 4.5redis-cli ZINCRBY ratings 0.5 user:1redis-cli ZSCORE ratings user:1
```

Execution

```
1(integer) 12"5"3"5"
```

-   Negative value decreases score
-   Creates member if doesn't exist

#### Pop Lowest Scoring Member

Remove and return lowest scoring members

Code

Terminal window

```
redis-cli ZPOPMIN priority-queue 2
```

Execution

```
11) "task-1"22) "1"33) "task-2"44) "2"
```

-   Returns \[member1, score1, member2, score2, ...\]
-   Useful for processing queues by priority

#### Pop Highest Scoring Member

Remove and return highest scoring members

Code

Terminal window

```
redis-cli ZPOPMAX leaderboard 1
```

Execution

```
11) "player2"22) "150"
```

-   Opposite of ZPOPMIN

#### Blocking Pop Operations

Block until lowest score member available

Code

Terminal window

```
redis-cli BZPOPMIN priority:queue 0
```

Execution

```
11) "priority:queue"22) "item-id"33) "1"
```

-   Returns \[key, member, score\] on timeout nil
-   Useful for task processing

## Transactions & Scripting

### Transaction Basics

Execute commands atomically with MULTI and EXEC

#### Accessibility

Intermediate

#### Best Practices

-   Use transactions for related operations that must happen together
-   Keep transactions short to minimize lock contention
-   Use WATCH for optimistic locking on critical data
-   Handle nil return from EXEC (transaction aborted)

#### Common Errors

-   **Can't nest MULTI:** Already in transaction raises error
-   **WATCH key changed:** EXEC returns nil, must retry logic

#### Keywords

MULTIEXECDISCARDWATCHatomic operations

[Learn more](https://redis.io/commands/multi/)

#### Simple Transaction

Queue commands and execute atomically

Code

Terminal window

```
redis-cli127.0.0.1:6379> MULTI127.0.0.1:6379> SET key1 "value1"127.0.0.1:6379> SET key2 "value2"127.0.0.1:6379> GET key1127.0.0.1:6379> EXEC
```

Execution

```
1OK2QUEUED3QUEUED4QUEUED51) OK62) OK73) "value1"
```

-   Commands return QUEUED when in transaction
-   EXEC returns array of results
-   All commands execute or none if error

#### Cancel Transaction

Cancel transaction without executing queued commands

Code

Terminal window

```
redis-cli127.0.0.1:6379> MULTI127.0.0.1:6379> SET key1 "value"127.0.0.1:6379> DISCARD127.0.0.1:6379> GET key1
```

Execution

```
1OK2QUEUED3OK4(nil)
```

-   DISCARD returns OK
-   All queued commands are discarded

#### Monitor Key and Abort on Change

Monitor key and only execute if unchanged

Code

Terminal window

```
redis-cli127.0.0.1:6379> SET account:1:balance "1000"127.0.0.1:6379> WATCH account:1:balance127.0.0.1:6379> MULTI127.0.0.1:6379> DECRBY account:1:balance 100127.0.0.1:6379> EXEC
```

Execution

```
1OK2OK3OK4QUEUED51) (integer) 900
```

-   If key changed between WATCH and EXEC, transaction aborts
-   Returns nil if transaction aborted

#### Optimistic Lock with WATCH

Implement optimistic locking pattern

Code

Terminal window

```
redis-cli WATCH mykeyvalue=$(redis-cli GET mykey)# ... check value in application ...redis-cli MULTIredis-cli SET mykey "newvalue"# ... other commands ...redis-cli EXEC
```

Execution

```
1OK2"oldvalue"3OK4QUEUED51) OK
```

-   Application decides whether to commit
-   Useful for non-critical updates

### Lua Scripting

Execute Lua scripts atomically on server

#### Accessibility

Advanced

#### Best Practices

-   Use Lua for atomic operations combining multiple commands
-   Preload scripts with SCRIPT LOAD for frequent use
-   Keep scripts focused and simple for maintainability
-   Use EVALSHA after preloading to reduce network traffic

#### Common Errors

-   **Script not found:** EVALSHA returns error if script not loaded
-   **KEYS vs ARGV indexing:** KEYS/ARGV are 1-indexed in Lua

#### Keywords

EVALEVALSHASCRIPT LOADSCRIPT FLUSHatomic Lua execution

[Learn more](https://redis.io/commands/eval/)

#### Execute Simple Lua Script

Execute inline Lua script with zero keys

Code

Terminal window

```
redis-cli EVAL "return 'Hello from Lua'" 0
```

Execution

```
1"Hello from Lua"
```

-   "0" = number of key arguments following
-   Script returns result to client

#### Lua Script with Key and Argument

Access Redis keys from Lua script

Code

Terminal window

```
redis-cli EVAL "return redis.call('GET', KEYS[1])" 1 mykey
```

Execution

```
1"value"
```

-   KEYS\[1\] = first key argument
-   ARGV indexing starts at 1 (not 0)

#### Increment with Constraint

Conditional increment only if under limit

Code

Terminal window

```
redis-cli EVAL "local current = redis.call('GET', KEYS[1])if tonumber(current) < tonumber(ARGV[1]) then  redis.call('INCR', KEYS[1])  return 1endreturn 0" 1 counter 100
```

Execution

```
1(integer) 1
```

-   Atomic constraint check and update
-   Returns 1 if incremented, 0 if limit reached

#### Preload Script with SHA

Load script once, execute many times by SHA

Code

Terminal window

```
redis-cli SCRIPT LOAD "return 'cached script'"# Save SHA returned: abc123...redis-cli EVALSHA abc123... 0
```

Execution

```
1"abc123def456..."2"cached script"
```

-   Reduces bandwidth for frequently used scripts
-   More efficient than EVAL for repeated calls

#### Script Management

Check script existence, clear cache, terminate running

Code

Terminal window

```
redis-cli SCRIPT EXISTS sha1 sha2 sha3redis-cli SCRIPT FLUSHredis-cli SCRIPT KILL
```

Execution

```
11) (integer) 122) (integer) 03(integer) 34OK
```

-   SCRIPT EXISTS returns array of 1/0 for each SHA
-   SCRIPT FLUSH clears script cache (careful in production!)

## Pub/Sub & Streams

### Pub/Sub Basics

Publish and subscribe to message channels

#### Accessibility

Intermediate

#### Best Practices

-   Use pub/sub for real-time notifications, not persistent queues
-   Publish count indicates delivery, but no guarantee of processing
-   Combine with persistence (streams) for critical messages
-   Use pattern subscriptions for dynamic channel names

#### Common Errors

-   **Message loss if no subscribers:** Pub/sub doesn't queue messages
-   **Client stalled in subscribe mode:** Can't run other commands

#### Keywords

PUBLISHSUBSCRIBEUNSUBSCRIBEmessage broadcastchannels

[Learn more](https://redis.io/commands/publish/)

#### Subscribe to Channel

Subscribe to "news" channel and wait for messages

Code

Terminal window

```
# Terminal 1redis-cli127.0.0.1:6379> SUBSCRIBE news
```

Execution

```
1Reading messages... (press Ctrl-C to quit)21) "subscribe"32) "news"43) (integer) 1
```

-   Client blocks in subscribe mode
-   Receives confirmation message with subscription count

#### Publish Message

Publish message to channel

Code

Terminal window

```
# Terminal 2redis-cli PUBLISH news "Breaking news!"
```

Execution

```
1(integer) 1
```

-   Returns number of subscribers that received message
-   Message sent immediately to all subscribers

#### Receive Published Message

Subscriber receives published message

Code

Terminal window

```
# Terminal 1 receiving
```

Execution

```
11) "message"22) "news"33) "Breaking news!"
```

-   Array format \[type, channel, message\]
-   Continues waiting for more messages

#### Subscribe to Multiple Channels

Subscribe to multiple channels at once

Code

Terminal window

```
redis-cli127.0.0.1:6379> SUBSCRIBE sports weather cryptocurrency
```

Execution

```
1Reading messages...21) "subscribe"32) "sports"43) (integer) 151) "subscribe"62) "weather"73) (integer) 281) "subscribe"92) "cryptocurrency"103) (integer) 3
```

-   Subscription count increases per channel
-   Client receives messages from any subscribed channel

#### Pattern Subscription

Subscribe to channels matching pattern

Code

Terminal window

```
redis-cli PSUBSCRIBE "user:*:notification"
```

Execution

```
11) "psubscribe"22) "user:*:notification"33) (integer) 1
```

-   Receives messages from matching dynamic channels
-   Pattern matching on server side

### Redis Streams

Persistent, ordered message queues

#### Accessibility

Advanced

#### Best Practices

-   Use streams for persistent, ordered message queues
-   Use consumer groups for distributed message processing
-   Acknowledge messages after processing to track progress
-   Monitor pending messages to detect stuck consumers

#### Common Errors

-   **Group already exists:** XGROUP CREATE returns error if exists
-   **Format error in ID:** Must use milliseconds-sequence format

#### Keywords

XADDXREADXRANGEXGROUPstream consumer groups

[Learn more](https://redis.io/commands/xadd/)

#### Add Message to Stream

Add messages to stream with auto-generated timestamp ID

Code

Terminal window

```
redis-cli XADD events "*" type "user_login" user "alice" ip "192.168.1.1"redis-cli XADD events "*" type "user_logout" user "bob"
```

Execution

```
1"1704067200000-0"2"1704067201000-0"
```

-   "\*" = auto-generate ID from milliseconds
-   ID format = timestamp-sequence

#### Read Stream Range

Read all messages in stream (oldest to newest)

Code

Terminal window

```
redis-cli XRANGE events - +
```

Execution

```
11) 1) "1704067200000-0"2   2) 1) "type"3      2) "user_login"4      3) "user"5      4) "alice"6      5) "ip"7      6) "192.168.1.1"82) 1) "1704067201000-0"9   2) 1) "type"10      2) "user_logout"11      3) "user"12      4) "bob"
```

-   "-" = minimum ID, "+" = maximum ID
-   Returns all messages with data

#### Read New Messages from Position

Read new messages after specific position

Code

Terminal window

```
redis-cli XREAD COUNT 2 STREAMS events "1704067200000-0"
```

Execution

```
11) 1) "events"2   2) 1) 1) "1704067201000-0"3      2) 1) "type"4         2) "user_logout"
```

-   Returns messages after provided ID
-   COUNT limits returned messages

#### Create Consumer Group

Create processor group and read undelivered messages

Code

Terminal window

```
redis-cli XGROUP CREATE events mygroup 0redis-cli XREADGROUP GROUP mygroup consumer1 STREAMS events ">"
```

Execution

```
1OK21) 1) "events"3   2) 1) 1) "1704067200000-0"4      2) 1) "type"5         2) "user_login"
```

-   "0" = start from beginning
-   ">" = new messages not yet delivered

#### Acknowledge Message Processing

Acknowledge processed message and check pending

Code

Terminal window

```
redis-cli XACK events mygroup "1704067200000-0"redis-cli XPENDING events mygroup
```

Execution

```
1(integer) 121) (integer) 03   2) "1704067201000-0"4   3) "1704067201000-0"5   4) 1) 1) "consumer1"6      2) (integer) 1
```

-   XACK removes from pending list
-   XPENDING shows unacknowledged messages

## Advanced Features

### Persistence (RDB and AOF)

Save and restore Redis data with RDB snapshots and AOF logs

#### Accessibility

Advanced

#### Best Practices

-   Use AOF for critical data requiring durability
-   Use RDB for snapshots and faster recovery
-   Enable both for maximum protection
-   Monitor disk space used by persistence files

#### Common Errors

-   **SAVE blocks server:** Use BGSAVE in production instead
-   **AOF file too large:** Schedule regular BGREWRITEAOF

#### Keywords

SAVEBGSAVEBGREWRITEAOFpersistence modesdata durability

[Learn more](https://redis.io/commands/save/)

#### Manual RDB Snapshot

Create RDB snapshot synchronously (blocks server)

Code

Terminal window

```
redis-cli SAVE
```

Execution

```
1OK
```

-   Blocking operation, avoid in production
-   Saves to dump.rdb file

#### Background RDB Snapshot

Trigger RDB snapshot in background thread

Code

Terminal window

```
redis-cli BGSAVE
```

Execution

```
1Background saving started
```

-   Non-blocking, server continues operations
-   Check LASTSAVE for completion

#### Check Last Save Time

Get Unix timestamp of last successful RDB save

Code

Terminal window

```
redis-cli LASTSAVE
```

Execution

```
1(integer) 1704067890
```

-   Returns seconds since epoch
-   Useful for monitoring backup freshness

#### Rewrite AOF Log

Trigger AOF log compaction in background

Code

Terminal window

```
redis-cli BGREWRITEAOF
```

Execution

```
1Background append only file rewriting started
```

-   Reduces AOF file size by removing redundant commands
-   Non-blocking operation

### Replication and Clustering

Set up master-replica replication and Redis Cluster

#### Accessibility

Advanced

#### Best Practices

-   Use replication for high availability
-   Monitor replication lag to detect issues
-   Test failover procedures regularly
-   Use cluster for automatic sharding at scale

#### Common Errors

-   **Replication lag too high:** Network issues or slow replica disk
-   **Cluster slots unbalanced:** Rebalance using redis-cli --cluster

#### Keywords

REPLICAOFreplicationmaster-replicacluster nodesfailover

[Learn more](https://redis.io/commands/replicaof/)

#### Configure Replica

Configure server as replica of master

Code

Terminal window

```
redis-cli REPLICAOF master-host 6379redis-cli INFO replication
```

Execution

```
1OK2# Replication3role:slave4master_host:master-host5master_port:63796master_link_status:up7master_repl_offset:1234567
```

-   Starts syncing from master
-   Receives all write commands from master

#### Stop Replication

Stop replication and become standalone master

Code

Terminal window

```
redis-cli REPLICAOF NO ONE
```

Execution

```
1OK
```

-   Keeps data already synced
-   Stops receiving updates from old master

#### Check Replica Lag

Monitor master replication offset

Code

Terminal window

```
redis-cli INFO replication | grep master_repl_offset
```

Execution

```
1master_repl_offset:9876543
```

-   Indicates how much data replica has from master

#### Cluster Info

Check Redis Cluster status

Code

Terminal window

```
redis-cli CLUSTER INFO
```

Execution

```
1cluster_state:ok2cluster_slots_assigned:163843cluster_slots_ok:163844cluster_slots_pfail:05cluster_slots_fail:0
```

-   Shows slot distribution and health

### Memory Optimization

Monitor and optimize Redis memory usage

#### Accessibility

Advanced

#### Best Practices

-   Monitor used\_memory/used\_memory\_rss ratio for fragmentation
-   Set maxmemory-policy based on use case
-   Use volatile-lru for cache-like data
-   Use noeviction for critical non-expiring data

#### Common Errors

-   **Out of memory:** Set maxmemory or eviction policy
-   **Wrong eviction policy:** Choose based on data type and use

#### Keywords

memory managementeviction policiesmaxmemorykey expirationmemory stats

[Learn more](https://redis.io/commands/info/)

#### Check Memory Stats

Get detailed memory usage breakdown

Code

Terminal window

```
redis-cli INFO memory
```

Execution

```
1# Memory2used_memory:10485763used_memory_human:1.00M4used_memory_rss:20971525used_memory_rss_human:2.00M6allocator_active:15728647allocator_allocated:10485768used_memory_peak:11000009used_memory_peak_human:1.05M
```

-   used\_memory = Redis internal memory
-   used\_memory\_rss = OS allocated memory (higher due to fragmentation)

#### Set Memory Limit

Set max memory to 2GB with LRU eviction policy

Code

Terminal window

```
redis-cli CONFIG SET maxmemory 2147483648redis-cli CONFIG SET maxmemory-policy allkeys-lru
```

Execution

```
1OK2OK
```

-   Policies: noeviction, allkeys-lru, volatile-lru, allkeys-random, etc.
-   allkeys-lru = evict any key using LRU

#### Eviction Policy Behavior

How volatile-lru eviction picks keys

Code

Terminal window

```
# When maxmemory reached with volatile-lru:# Evicts keys with expiration, using LRU algorithm
```

Execution

```
1# Only keys with TTL are eligible2# LRU tracks least recently used
```

-   Applies only to keys with EXPIRE set
-   Safer than allkeys as it preserves important data

#### Analyze Key Memory Usage

Get Redis memory analysis and recommendations

Code

Terminal window

```
redis-cli --ldb# Alternative: MEMORY DOCTOR commandredis-cli MEMORY DOCTOR
```

Execution

```
1Sam, I'm sorry. I don't see much to worry about...2# or detailed advice about memory issues
```

-   Provides optimization suggestions
-   Shows potential memory leaks

Was this useful?

## Share

[Facebook](https://facebook.com/sharer/sharer.php?u=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fredis "Share on Facebook")[Twitter](https://twitter.com/intent/tweet/?text=Redis&url=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fredis "Share on Twitter")[LinkedIn](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fredis&title=Redis&summary=Redis%20reference%20guide%20covering%20commands%2C%20data%20types%2C%20keys%2C%20strings%2C%20lists%2C%20sets%2C%20hashes%2C%20sorted%20sets%2C%20transactions%2C%20pub%2Fsub%2C%20and%20caching%20strategies.&source=https://mkabumattar.com "Share on LinkedIn")[WhatsApp](https://wa.me/?text=Redis%20https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fredis "Share on WhatsApp")[Telegram](https://t.me/share/url?url=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fredis&text=Redis "Share on Telegram")[Reddit](https://www.reddit.com/submit?url=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fredis&title=Redis "Share on Reddit")[Hacker News](http://news.ycombinator.com/submitlink?u=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fredis&t=Redis "Share on Hacker News")[Pinterest](https://pinterest.com/pin/create/button/?url=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fredis&media=&description=Redis%20reference%20guide%20covering%20commands%2C%20data%20types%2C%20keys%2C%20strings%2C%20lists%2C%20sets%2C%20hashes%2C%20sorted%20sets%2C%20transactions%2C%20pub%2Fsub%2C%20and%20caching%20strategies. "Share on Pinterest")[Email](<mailto:?subject=Redis&body=Check out this article: https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fredis>)

## Comments

## You might also enjoy

More posts on similar topics

## [PostgreSQL](/cheatsheets/postgresql)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Reference

PostgreSQL reference guide covering psql commands, database creation, tables, queries, functions, joins, transactions, indexes, and advanced SQL operations.

[read more](/cheatsheets/postgresql)

## [Chef](/cheatsheets/chef)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Reference

Chef is an Infrastructure as Code platform for automating infrastructure configuration, deployment, and management. This cheatsheet covers Chef concepts, commands, patterns, and best practices for man

[read more](/cheatsheets/chef)

## [Docker Compose](/cheatsheets/docker-compose)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Reference

Docker Compose is a tool for defining and running multi-container Docker applications. It uses a YAML file to configure application services, networks, and volumes. This cheatsheet provides a quick re

[read more](/cheatsheets/docker-compose)

## [Dockerfile](/cheatsheets/dockerfile)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Reference

This cheat sheet covers the core Dockerfile instructions, best practices, and common pitfalls for building small, secure Docker images. Each section pairs a Dockerfile snippet with the build output it

[read more](/cheatsheets/dockerfile)

## [Ansible](/cheatsheets/ansible)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Reference

Ansible is an automation tool for configuration management, application deployment, and orchestration. This cheatsheet is a quick reference for common Ansible tasks, modules, and best practices.

[read more](/cheatsheets/ansible)

## [SSH](/cheatsheets/ssh)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Reference

export const components = { h1: 'h1', h2: 'h2', h3: 'h3', h4: 'h4', h5: 'h5', h6: 'h6', p: 'p', a: 'a', ul: 'ul', ol: 'ol', li: 'li', code: 'code', pre: 'pre', strong: 'str

[read more](/cheatsheets/ssh)

6 related posts
