Skip to content

Menu

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

Try it: redis-command-builderFrom the docs, not run by us
SET session:abc "…" EX 3600

Store a value that expires in an hour

From the docs, not run by us
SET lock:report token123 NX EX 30

Set only if the key doesn't exist, with a 30 s expiry; the simple lock pattern

From the docs, not run by us
SET counter 5 KEEPTTL

Overwrite the value but keep the existing expiry

From the docs, not run by us
SET cfg new IFEQ old

Write only if the current value equals old (Redis 8.4+)

From the docs, not run by us
GET user:42:name

Read a string value; nil if the key doesn't exist

From the docs, not run by us
INCR page:views

Atomically add 1 and return the new value; does not reset the TTL

From the docs, not run by us

Hash commands are documented at https://redis.io/docs/latest/develop/data-types/hashes/.

LPUSH feed:42 item:9

Add to the head of a list, creating it if needed

From the docs, not run by us
LTRIM feed:42 0 99

Keep only the first 100 items, the capped list pattern after LPUSH

From the docs, not run by us
LRANGE feed:42 0 -1

Read the whole list; -1 means the last element

From the docs, not run by us
HSET user:42 name Ada plan pro

Set one or more fields on a hash

From the docs, not run by us
HGET user:42 plan

Read a single field

From the docs, not run by us
HINCRBY user:42 logins 1

Increment an integer field, starting from 0 if missing

From the docs, not run by us
HGETALL user:42

Read every field and value; avoid on very large hashes

From the docs, not run by us

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

From the docs, not run by us
ZRANGE racer_scores 0 -1 REV WITHSCORES

Read the whole set from highest to lowest score with scores

From the docs, not run by us
ZRANGE racer_scores -inf 10 BYSCORE

Read members with a score up to 10

From the docs, not run by us
ZINCRBY racer_scores 50 "Henshaw"

Add to a member's score, for leaderboards

From the docs, not run by us
ZRANK racer_scores "Norem"

Zero-based rank from lowest score; ZREVRANK counts from the top

From the docs, not run by us
XADD race:france * rider Castilla speed 30.2

Append an event to a stream with an auto-generated ID

From the docs, not run by us
XREADGROUP GROUP mygroup c1 COUNT 10 BLOCK 300 STREAMS race:france >

Read new entries for one consumer in a group

From the docs, not run by us
XACK race:france mygroup 1692632086370-0

Acknowledge an entry so it leaves the pending list

From the docs, not run by us

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 10

Delete the key in 10 seconds; returns 1 if set, 0 if not

From the docs, not run by us
EXPIRE mykey 10 NX

Set an expiry only if the key has none (7.0+); XX, GT and LT are the other conditions

From the docs, not run by us
TTL mykey

Seconds left; -1 means no expiry, -2 means the key doesn't exist

From the docs, not run by us
PTTL mykey

Same as TTL in milliseconds

From the docs, not run by us
PERSIST mykey

Remove the expiry so the key lives until deleted

From the docs, not run by us

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 100

Walk keys matching a glob in batches; repeat with the returned cursor

From the docs, not run by us
SCAN 0 TYPE hash

Only return keys of a given type (6.0+)

From the docs, not run by us
HSCAN user:42 0

Iterate fields of one large hash; SSCAN and ZSCAN do the same for sets

From the docs, not run by us
KEYS user:*

Returns every match in one call but can block the server for seconds on big databases

From the docs, not run by us

Pub/sub: https://redis.io/docs/latest/develop/pubsub/. Delivery is at most once; Pub/Sub ignores database numbers.

MULTI … EXEC

Queue commands and run them in order with no other client in between

From the docs, not run by us
DISCARD

Throw away the queued commands and leave the transaction

From the docs, not run by us
WATCH balance:42

Abort the next EXEC (it returns null) if this key changes first; optimistic locking

From the docs, not run by us
SUBSCRIBE orders

Listen on a channel; the connection then only accepts subscribe commands in RESP2

From the docs, not run by us
PSUBSCRIBE news.*

Listen on every channel matching a glob pattern

From the docs, not run by us
PUBLISH orders "order:991 paid"

Send a message to whoever is subscribed right now

From the docs, not run by us
SPUBLISH orders "…"

Sharded pub/sub in a cluster (7.0+), kept within the shard

From the docs, not run by us
save 60 1000

redis.conf: write an RDB snapshot every 60 s if at least 1000 keys changed

From the docs, not run by us
appendonly yes

Turn on the append-only file so every write is logged and replayed on restart

From the docs, not run by us
appendfsync everysec

Default fsync policy: lose at most about one second of writes; always and no are the others

From the docs, not run by us
BGSAVE

Fork and write an RDB snapshot in the background

From the docs, not run by us
BGREWRITEAOF

Compact the AOF to the shortest set of commands for the current data

From the docs, not run by us
redis-cli config set appendonly yes

Switch a live RDB server to AOF safely, then persist it in redis.conf

From the docs, not run by us

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 SCAN with MATCH and COUNT, which iterates without blocking the server.

  • Calling SET on a cached key and assuming the old TTL still applies.

    Pass EX, PX or KEEPTTL on every SET that should keep an expiry.

  • Expecting MULTI/EXEC to 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 XADD and a consumer group; pub/sub drops messages when no subscriber is connected.

  • Releasing a SET NX lock with a plain DEL, deleting a lock another client now holds.

    Store a random token and delete only if it matches, with a script or DELEX with a condition on 8.4+.

  • Running with only RDB snapshots for data you can't lose.

    Enable AOF with appendfsync everysec as well; the docs suggest both when you need strong durability.