Skip to content

Redis Cheat Sheet

Core commands for strings, hashes, sets, and expiry.

The Redis commands you reach for most, grouped by data type. Redis is a key–value store where the value can be a string, list, hash, set, or sorted set — picking the right type is most of using Redis well.

The expiry section matters for caching: `SET key val EX 60` writes a value that self-deletes after 60 seconds, which is the pattern behind most cache entries and short-lived tokens.

Strings

SET key valueSet a string value.
GET keyRead a value.
SET key value EX 60Set with a 60-second expiry.
SETNX key valueSet only if the key does not exist (lock-like).
INCR key · INCRBY key 5Atomically increment a counter.
MSET k1 v1 k2 v2Set multiple keys at once.

Hashes

Store an object as fields under one key.

HSET key field valueSet a field on a hash.
HGET key fieldRead one field.
HGETALL keyRead all field/value pairs.
HDEL key fieldDelete a field.
HINCRBY key field 1Increment a numeric field.

Lists & sets

LPUSH key v · RPUSH key vPush to the head / tail of a list.
LRANGE key 0 -1Read a range (0 to -1 = all).
LPOP key · BRPOP key 5Pop; BRPOP blocks up to 5s (queue).
SADD key m · SMEMBERS keyAdd to a set; list members.
ZADD key 1 m · ZRANGE key 0 -1Sorted set: add with score, read ordered.

Keys & expiry

EXPIRE key 60 · TTL keySet expiry; check remaining seconds.
PERSIST keyRemove an expiry (make it permanent).
DEL key · EXISTS keyDelete a key; test existence.
SCAN 0 MATCH prefix:*Iterate keys safely (never use KEYS in prod).
TYPE keyShow a key’s data type.

Server & pub/sub

redis-cli -h host -p 6379Connect to a Redis server.
INFO · DBSIZEServer stats; number of keys.
FLUSHDB · FLUSHALLWipe current DB / all DBs (careful!).
SUBSCRIBE ch · PUBLISH ch msgPub/sub messaging.
MONITORStream every command in real time (debug only).

Frequently asked questions

Why should I avoid the KEYS command in production Redis?

`KEYS pattern` scans the entire keyspace in one blocking call, which can stall the server on large datasets since Redis is single-threaded. Use `SCAN`, which iterates in small batches via a cursor and does not block other clients.

How do I make a Redis key expire automatically?

Set a TTL when writing — `SET key value EX 60` — or add one later with `EXPIRE key 60`. Check the remaining time with `TTL key`, and remove the expiry with `PERSIST key`. This is the mechanism behind cache entries and short-lived sessions.