Redis Cheatsheet - Keys, Strings, Hash & Expire Commands

For developers using Redis as a cache who must care about memory and TTL strategy. The commands are easy, but big keys blowing up memory, hot keys concentrating load on one node, and cache penetration/avalanche are the real business problems. By the end you can pick the right command per data structure, use INFO memory and object encoding to find top memory consumers, understand the RDB/AOF persistence trade-off, and use SCAN/UNLINK to handle big keys without blocking the instance.

Databases·43 commands·Last updated 2026-07-21
redisCachingnosqlMemory

Typical Use Case

Caching and key-value store ops: connect, basic read/write, inspect memory and keyspace, troubleshoot memory growth, cache stampede/avalanche, connection exhaustion, and RDB/AOF persistence and recovery.

Connection 6

redis-cli -h 127.0.0.1 -p 6379 -a password
Connect to instance, -a specifies password (warns about security)
redis-cli --scan --pattern "user:*"
Safely scan matching keys, avoid KEYS (blocking)
redis-cli -r 5 -i 1 INFO memory
Collect memory info every second, 5 times, for monitoring
AUTH password
Authenticate after connecting
SELECT 0
Switch to database 0 (not supported in cluster mode)
DBSIZE
View number of keys in current database

Data Structure 11

SET key value EX 300
Set key-value with 300s expiry, atomic operation
GET key
Get string value
MSET k1 v1 k2 v2
Batch set, reduces round trips
HSET user:1 name "tom" age 30
Set hash fields
HGETALL user:1
Get all hash fields and values
LPUSH queue task1
Left push to list (head)
BRPOP queue 30
Blocking right pop (tail), 30s timeout
ZADD rank 100 "user1" 200 "user2"
Add sorted set members with scores
ZRANGE rank 0 -1 WITHSCORES
Return all members sorted by score ascending
SADD tags "python" "redis"
Add set members
SINTER set1 set2
Intersection of sets

Key Space 8

EXPIRE key 300
Set expiry in 300 seconds
TTL key
View remaining TTL (-1 forever, -2 does not exist)
TYPE key
Check data type of key
DEL key1 key2
Delete multiple keys
UNLINK key
Async delete large key, won't block main thread
RENAME old_key new_key
Rename key
RANDOMKEY
Return a random key
OBJECT ENCODING key
View internal encoding (ziplist/hashtable/intset)

Persistence & Memory 7

BGSAVE
Background async RDB snapshot, non-blocking
LASTSAVE
View Unix timestamp of last successful RDB save
BGREWRITEAOF
Background async AOF rewrite, compact file size
INFO memory
View memory details, check used_memory_human and mem_fragmentation_ratio
MEMORY USAGE key
Check memory usage of a single key in bytes
CONFIG GET maxmemory
View max memory limit
CONFIG GET maxmemory-policy
View eviction policy (noeviction/allkeys-lru etc.)

Slowlog & Monitor 6

SLOWLOG GET 10
View last 10 slow queries
SLOWLOG RESET
Clear slow query log
CONFIG GET slowlog-log-slower-than
View slow query threshold (microseconds, 0=all, -1=disabled)
CLIENT LIST
List all connections, find idle connections and source IPs
CLIENT KILL ID <id>
Kill a specific connection
INFO clients
View client statistics, check connected_clients and blocked_clients

Cluster & Replication 5

CLUSTER INFO
View cluster status, cluster_state should be ok
CLUSTER NODES
View all node roles and connection status
CLUSTER KEYSLOT key
Check hash slot of a key (0-16383)
INFO replication
View master/slave role and sync status
ROLE
Quick check role (master/slave) and offset

Parameter matrix

参数EffectExample
-h指定主机redis-cli -h 127.0.0.1
-p指定端口(默认 6379)redis-cli -p 6380
-a指定密码(建议用 --user)redis-cli -a secret
--scan安全遍历大键空间,避免 KEYS 阻塞redis-cli --scan --pattern "session:*" | head
INFO memory查看内存使用与碎片率redis-cli INFO memory
EXPIRE给键设置过期时间EXPIRE token:1 3600
TTL查看键剩余存活时间TTL token:1
CONFIG SET运行时改配置(部分需重启)redis-cli CONFIG SET maxmemory 2gb
SAVE/BGSAVE同步/后台落盘 RDBredis-cli BGSAVE
FLUSHDB清空当前库(危险)redis-cli FLUSHDB

Common pitfalls

Symptom内存持续增长直至触发 maxmemory 被逐出或 OOM。

Cause键未设过期、大 key(如巨大 hash/list),或客户端缓存无限增长。

Fix为缓存键统一设 EXPIRE;用 redis-cli --bigkeys 找大 key 拆分;设合理 maxmemory-policy(如 allkeys-lru)。

SymptomKEYS * 导致 Redis 卡死、超时雪崩。

CauseKEYS 生产环境遍历全量键,阻塞单线程。

Fix改用 SCAN/--scan 增量遍历;线上严禁 KEYS *,可用 rename-command 禁用。

Symptom缓存集中过期,瞬间大量请求穿透到数据库。

Cause大量键同一时刻过期(缓存雪崩),或热点 key 失效(击穿)。

Fix过期时间加随机抖动避免同时失效;热点 key 用互斥锁/逻辑过期重建;数据库侧加限流。

Symptom重启后数据全丢。

Cause只开 RDB 且间隔长,或 AOF 未开启且崩溃发生在两次快照之间。

Fix按重要程度开启 AOF(appendonly yes)并选合适 fsync 策略;关键数据双持久化。

Symptom连接数打满,新连接被拒。

Cause客户端连接未复用、连接泄漏,或 maxclients 过小。

Fix用连接池复用;redis-cli CLIENT LIST 查来源;调大 maxclients;排查未关闭连接的代码。

Symptom误执行 FLUSHDB/FLUSHALL 清空数据。

Cause在生产执行了清理命令,且无持久化或副本已同步清空。

Fix用 rename-command 重命名危险命令;依赖 AOF/RDB 恢复;从副本或备份重建。

Troubleshooting

  1. 1查看内存与碎片率

    redis-cli INFO memory

    关注 used_memory_human 与 mem_fragmentation_ratio,>1.5 说明碎片偏高。

  2. 2找出大 key 与类型分布

    redis-cli --bigkeys

    定位需要拆分的大 hash/list/set,避免单 key 阻塞。

  3. 3安全遍历键空间

    redis-cli --scan --pattern "session:*" | wc -l

    替代 KEYS,避免阻塞单线程。

  4. 4查看当前连接来源

    redis-cli CLIENT LIST

    定位连接泄漏的客户端 IP 与空闲连接。

Tips

  • Never use KEYS * in production — use SCAN instead. KEYS blocks the main thread and causes stuttering.
  • Use UNLINK instead of DEL for large keys (lists/hashes/sets) — DEL blocks the main thread.
  • mem_fragmentation_ratio > 1.5 indicates high fragmentation — consider restarting or enabling activedefrag.

FAQ

What is the difference between Redis and Memcached, and when should I use Redis?

Redis supports multiple data structures (strings, hashes, lists, sets, sorted sets) with built-in persistence, while Memcached is simple key-value and pure memory. Choose Redis when you need complex data operations, persistence, leaderboards, message queues, or session storage.

Why should I avoid the KEYS * command in production?

KEYS * traverses the entire keyspace and blocks the Redis main thread; with large datasets it causes stalls and timeouts. Use SCAN instead, which iterates keys incrementally without blocking.

Can Redis lose data? How do I ensure persistence?

Redis offers RDB (point-in-time snapshots) and AOF (append-only log) persistence. RDB restores fast but may lose data after the last snapshot; AOF is safer but larger. Production usually enables both to balance performance and safety.

Official References

Each command links to its official documentation below, so you can verify the latest usage and read deeper.

Maintained by LaoHand

Publicly updated on Jul 21, 2026, continuously proofread against official docs.

Contact Us

Wrong command or description? Send us corrections, business inquiries or product feedback by email.

Contact Us