Redis Cheat Sheet: Data Types, Expiry, SCAN, Transactions and Pub/Sub
Checked against Redis Redis Open Source 8.12.0 (released 22 Nov 2026), redis.io docs; docs only on 28 November 2026. Each section links to the official docs it was checked against.
This sheet is for application developers using Redis as a cache, counter store or lightweight queue. It follows the redis.io command docs and the Redis Open Source 8.12.0 release notes from 22 November 2026. redis-server isn't installed here, so every row is untested and outputs shown come from the official docs.
When to use what
Pick the data type by how you read the data, not how you write it. A string is right for a cached blob or a counter (INCR is atomic). A hash fits an object whose fields you update one at a time. A list is a queue or a capped "latest N" feed. A set answers "is X a member" in constant time, and a sorted set is the answer whenever you need ranking or a time window: leaderboards, rate limits, scheduled jobs. Streams are for event logs that consumers must not miss. Our post on Redis data structures in practice walks through each with examples.
For messaging, pub/sub is fire and forget: a subscriber that is offline when you publish never sees the message. If losing a message matters, use a stream with a consumer group. Use SCAN for anything that walks keys in production; KEYS blocks the server while it runs. The Redis command builder helps assemble the longer commands such as SET with its options, and if you're still deciding whether Redis is the right cache, read choosing a cache. The Redis MCP server lets an AI assistant query a dev instance.
SET user:42:name "Ada"Store a string; overwrites any value and drops any previous TTL
SET session:abc "…" EX 3600Store a value that expires in an hour
SET lock:report token123 NX EX 30Set only if the key doesn't exist, with a 30 s expiry; the simple lock pattern
SET counter 5 KEEPTTLOverwrite the value but keep the existing expiry
SET cfg new IFEQ oldWrite only if the current value equals old (Redis 8.4+)
GET user:42:nameRead a string value; nil if the key doesn't exist
INCR page:viewsAtomically add 1 and return the new value; does not reset the TTL
Hash commands are documented at https://redis.io/docs/latest/develop/data-types/hashes/.
LPUSH feed:42 item:9Add to the head of a list, creating it if needed
LTRIM feed:42 0 99Keep only the first 100 items, the capped list pattern after LPUSH
LRANGE feed:42 0 -1Read the whole list; -1 means the last element
HSET user:42 name Ada plan proSet one or more fields on a hash
HGET user:42 planRead a single field
HINCRBY user:42 logins 1Increment an integer field, starting from 0 if missing
HGETALL user:42Read every field and value; avoid on very large hashes
Streams: https://redis.io/docs/latest/develop/data-types/streams/.
ZADD racer_scores 10 "Norem" 12 "Castilla"Add members with scores to a sorted set
ZRANGE racer_scores 0 -1 REV WITHSCORESRead the whole set from highest to lowest score with scores
ZRANGE racer_scores -inf 10 BYSCORERead members with a score up to 10
ZINCRBY racer_scores 50 "Henshaw"Add to a member's score, for leaderboards
ZRANK racer_scores "Norem"Zero-based rank from lowest score; ZREVRANK counts from the top
XADD race:france * rider Castilla speed 30.2Append an event to a stream with an auto-generated ID
XREADGROUP GROUP mygroup c1 COUNT 10 BLOCK 300 STREAMS race:france >Read new entries for one consumer in a group
XACK race:france mygroup 1692632086370-0Acknowledge an entry so it leaves the pending list
The TTL is cleared by commands that delete or overwrite the value (DEL, SET, GETSET, *STORE) and kept by commands that change it in place (INCR, LPUSH, HSET). RENAME carries the TTL to the new name.
EXPIRE mykey 10Delete the key in 10 seconds; returns 1 if set, 0 if not
EXPIRE mykey 10 NXSet an expiry only if the key has none (7.0+); XX, GT and LT are the other conditions
TTL mykeySeconds left; -1 means no expiry, -2 means the key doesn't exist
PTTL mykeySame as TTL in milliseconds
PERSIST mykeyRemove the expiry so the key lives until deleted
A full iteration starts at cursor 0 and ends when the server returns 0. It may return a key twice, and MATCH filters after fetching, so some calls return nothing.
SCAN 0 MATCH user:* COUNT 100Walk keys matching a glob in batches; repeat with the returned cursor
SCAN 0 TYPE hashOnly return keys of a given type (6.0+)
HSCAN user:42 0Iterate fields of one large hash; SSCAN and ZSCAN do the same for sets
KEYS user:*Returns every match in one call but can block the server for seconds on big databases
Pub/sub: https://redis.io/docs/latest/develop/pubsub/. Delivery is at most once; Pub/Sub ignores database numbers.
MULTI … EXECQueue commands and run them in order with no other client in between
DISCARDThrow away the queued commands and leave the transaction
WATCH balance:42Abort the next EXEC (it returns null) if this key changes first; optimistic locking
SUBSCRIBE ordersListen on a channel; the connection then only accepts subscribe commands in RESP2
PSUBSCRIBE news.*Listen on every channel matching a glob pattern
PUBLISH orders "order:991 paid"Send a message to whoever is subscribed right now
SPUBLISH orders "…"Sharded pub/sub in a cluster (7.0+), kept within the shard
save 60 1000redis.conf: write an RDB snapshot every 60 s if at least 1000 keys changed
appendonly yesTurn on the append-only file so every write is logged and replayed on restart
appendfsync everysecDefault fsync policy: lose at most about one second of writes; always and no are the others
BGSAVEFork and write an RDB snapshot in the background
BGREWRITEAOFCompact the AOF to the shortest set of commands for the current data
redis-cli config set appendonly yesSwitch a live RDB server to AOF safely, then persist it in redis.conf
Worked example: Why a key lost its expiry
A cache entry that was meant to expire stayed forever. This sequence, from the EXPIRE docs, shows the cause:
> SET mykey "Hello"
OK
> EXPIRE mykey 10
(integer) 1
> TTL mykey
(integer) 10
> SET mykey "Hello World"
OK
> TTL mykey
(integer) -1
> EXPIRE mykey 10 XX
(integer) 0
> EXPIRE mykey 10 NX
(integer) 1
The second SET replaced the value and threw the TTL away, so TTL returned -1: the key exists but has no expiry. EXPIRE ... XX then did nothing (it only updates keys that already have an expiry) and returned 0, while NX applied because there was none. In application code the usual fix is to write the value and its expiry together, SET mykey "Hello World" EX 10, or add KEEPTTL when you want to keep the original deadline. If you only bump a counter with INCR, the TTL survives, which is why rate-limit counters don't need re-expiring on every hit.
Common mistakes
Running
KEYS *on a production instance to find keys.Use
SCANwithMATCHandCOUNT, which iterates without blocking the server.Calling
SETon a cached key and assuming the old TTL still applies.Pass
EX,PXorKEEPTTLon everySETthat should keep an expiry.Expecting
MULTI/EXECto roll back when one command fails at run time.Redis has no rollback; validate inputs first or use a Lua script, and check each reply in the EXEC array.
Using pub/sub for jobs that must not be lost.
Use a stream with
XADDand a consumer group; pub/sub drops messages when no subscriber is connected.Releasing a
SET NXlock with a plainDEL, deleting a lock another client now holds.Store a random token and delete only if it matches, with a script or
DELEXwith a condition on 8.4+.Running with only RDB snapshots for data you can't lose.
Enable AOF with
appendfsync everysecas well; the docs suggest both when you need strong durability.
Related cheat sheets
Sources
- https://redis.io/docs/latest/develop/data-types/
- https://redis.io/docs/latest/commands/set/
- https://redis.io/docs/latest/commands/expire/
- https://redis.io/docs/latest/commands/ttl/
- https://redis.io/docs/latest/commands/scan/
- https://redis.io/docs/latest/develop/using-commands/transactions/
- https://redis.io/docs/latest/develop/pubsub/
- https://redis.io/docs/latest/operate/oss_and_stack/management/persistence/
- https://github.com/redis/redis/releases
How we research: where our facts come from, how often we re-check them, and why no one can pay for a review or a verdict.