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.
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 passwordredis-cli --scan --pattern "user:*"redis-cli -r 5 -i 1 INFO memoryAUTH passwordSELECT 0DBSIZEData Structure 11
SET key value EX 300GET keyMSET k1 v1 k2 v2HSET user:1 name "tom" age 30HGETALL user:1LPUSH queue task1BRPOP queue 30ZADD rank 100 "user1" 200 "user2"ZRANGE rank 0 -1 WITHSCORESSADD tags "python" "redis"SINTER set1 set2Key Space 8
EXPIRE key 300TTL keyTYPE keyDEL key1 key2UNLINK keyRENAME old_key new_keyRANDOMKEYOBJECT ENCODING keyPersistence & Memory 7
BGSAVELASTSAVEBGREWRITEAOFINFO memoryMEMORY USAGE keyCONFIG GET maxmemoryCONFIG GET maxmemory-policySlowlog & Monitor 6
SLOWLOG GET 10SLOWLOG RESETCONFIG GET slowlog-log-slower-thanCLIENT LISTCLIENT KILL ID <id>INFO clientsCluster & Replication 5
CLUSTER INFOCLUSTER NODESCLUSTER KEYSLOT keyINFO replicationROLEParameter matrix
| Parameter | Effect | Example |
|---|---|---|
-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 | 同步/后台落盘 RDB | redis-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查看内存与碎片率
redis-cli INFO memory关注 used_memory_human 与 mem_fragmentation_ratio,>1.5 说明碎片偏高。
2找出大 key 与类型分布
redis-cli --bigkeys定位需要拆分的大 hash/list/set,避免单 key 阻塞。
3安全遍历键空间
redis-cli --scan --pattern "session:*" | wc -l替代 KEYS,避免阻塞单线程。
4查看当前连接来源
redis-cli CLIENT LIST定位连接泄漏的客户端 IP 与空闲连接。
Command Examples
Clear prefixed keys with SCAN instead of KEYS
redis-cli --scan --pattern "session:*" | xargs -r -n 500 redis-cli DELWhen you must clear session-style prefixed keys, KEYS blocks the whole instance while it walks the keyspace. SCAN returns a small cursor batch at a time; combined with --pattern it scans incrementally and stays unnoticeable on a live server.
SET with EX so the write and the TTL are one atomic step
SET user:1 "{\"name\":\"tom\"}" EX 300A SET followed by a separate EXPIRE is two commands: a crash in between leaves a key that never expires. Folding EX into SET is atomic. Whether that prevents a thundering herd depends on your code having a fallback branch when GET returns nil.
Reconciling cache against the database
redis-cli --scan --pattern "user:*"
redis-cli -h 127.0.0.1 -p 6379 GET user:1
redis-cli TTL user:1
redis-cli DBSIZEWhen a list page is missing a row, check DBSIZE and TTL first: many -1 values or mass expiry means the whole cache expired, whereas a few stragglers point at an overwrite. TTL -1 means "no expiry", which usually means one write path forgot to set it.
Diagnosing memory and slow queries
INFO memory
MEMORY USAGE user:1
CONFIG GET maxmemory
CONFIG GET maxmemory-policy
SLOWLOG GET 10
SLOWLOG RESETWhen memory climbs, start with mem_fragmentation_ratio and maxmemory-policy: with noeviction, writes are refused rather than evicting anything. Confirm the SLOWLOG threshold via slowlog-log-slower-than — at 0 the log is useless, at -1 it is disabled, and a 0 threshold would also slow the instance down.
Finding blocked connections and deleting large keys
INFO clients
CLIENT LIST
CLIENT KILL ID <id>
MEMORY USAGE bigkey
UNLINK bigkeyDEL on a large collection frees the memory synchronously and occupies the main thread the whole time; UNLINK unlinks the key first and reclaims in the background, so it returns immediately. Blocking commands such as BRPOP also show up in blocked_clients — check it first when client count explodes.
Common Pitfalls
- KEYS walks the entire keyspace and blocks the main thread; on a large instance a single KEYS * is enough to time out every write. Use redis-cli --scan --pattern and work in batches.
- Cache and database have no built-in consistency: crashing after SET, or two instances writing the same key, leaves them diverging with no alert. Paths that must stay consistent should delete the cache key after committing the database write, not populate the cache first.
- RENAME renames in place and silently overwrites an existing destination, copying no data and checking no conflict. Confirm the target key does not exist first, or one rename is one silent data loss.
- AOF defaults to appendfsync everysec, so a failure can lose roughly the last second of writes. Treating that as durability guarantees losing just-placed orders; shorten the fsync interval or accept the window explicitly.
- redis-cli -a password leaves the password in shell history and in the process list. Prefer ACL plus requirepass configuration, and make sure a one-shot -a in a script never lands in CI logs.
- With maxmemory-policy set to noeviction, a full memory limit rejects writes outright. It surfaces as broad application errors rather than slowness, which is easily misdiagnosed as a database or network fault — check CONFIG GET first.
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