Skip to content
Tutorials Center
My learning

Topics

Lesson 42 of 42 ยท Practice and Review

Redis Cheat Sheet

A one-page Redis cheat sheet: commands by data type, expiry, transactions, persistence, replication, cluster, config, ACL and safety reminders in compact tables.

This page packs the whole course into compact tables: the commands you use every day, grouped by data type, followed by expiry, transactions, persistence, replication, configuration and a list of safety reminders. Use it while you write code, while you work through the practice exercises, or right before an interview.

Everything here is real Redis syntax and is read-only: Redis cannot run on this site. Two small JavaScript stand-ins at the end (a searchable command table and a "which type?" chooser) let you try the ideas. Commands are case-insensitive; this page writes them in capitals. O(...) is the time cost, where N is the size of the collection. Features added recently name the version that introduced them.

Not sure what a command does or what its arguments are? Run COMMAND DOCS name in redis-cli, or type the command and read the hint. The server always knows its own version best.

Connect and inspect

Command What it does
redis-cli -h host -p 6379 Open an interactive session (add --tls for TLS).
PING Health check; replies PONG.
SELECT n Switch to logical database n (default 0; Cluster has only 0).
DBSIZE Number of keys in the current database.
INFO [section] Server statistics: memory, stats, replication, persistence, clients, keyspace.
CONFIG GET pattern / CONFIG SET name value Read or change settings at run time.
CLIENT LIST Connected clients.
SLOWLOG GET 10 The ten latest slow commands.
MONITOR Stream every command (debugging only: it slows the server).
COMMAND DOCS name Built-in documentation of a command.

See Installing Redis and Using redis-cli.

Keys and expiry

Command What it does
EXISTS key... Count of keys that exist.
TYPE key string, list, hash, set, zset, stream, or none.
DEL key... / UNLINK key... Delete (UNLINK frees memory in the background: use it for big values).
RENAME old new Rename a key (overwrites new).
EXPIRE key s / PEXPIRE key ms Set a time to live; EXPIREAT / PEXPIREAT take a Unix timestamp.
TTL key / PTTL key Time left: -1 means no expiry, -2 means no such key.
PERSIST key Remove the expiry.
SCAN cursor MATCH pat COUNT n Iterate keys safely; repeat until the cursor returns 0; expect duplicates.
OBJECT ENCODING key Internal encoding (listpack, hashtable, skiplist, ...).
MEMORY USAGE key Bytes used by a key.
COPY src dst Copy a key.

A plain SET removes a key's TTL (use KEEPTTL to keep it). Commands that edit a value in place, such as INCR and LPUSH, keep the TTL. See Keys, Expiry and TTL.

Strings and counters

Command What it does
SET key v [NX|XX] [EX s|PX ms|KEEPTTL] [GET] Write; NX only if absent, XX only if present, GET returns the old value.
GET key / GETDEL key / GETEX key EX s Read; read and delete; read and change the expiry.
MSET k v k v / MGET k k Several keys in one round trip.
INCR / DECR / INCRBY key n / DECRBY key n Atomic integer counters (create the key at 0).
INCRBYFLOAT key x Atomic float add.
APPEND key s / STRLEN key Append; length in bytes.
GETRANGE key a b / SETRANGE key off s Read or overwrite part of a string.

A string holds up to 512 MB and is binary safe. See Strings and Counters.

Lists

Command What it does
LPUSH key v... / RPUSH key v... Push at the head or tail, O(1) per value.
LPOP key [n] / RPOP key [n] Pop from the head or tail.
BLPOP key... timeout / BRPOP Blocking pop (0 waits forever).
LRANGE key a b Read a slice; 0 -1 is everything, O(S+N).
LINDEX key i / LSET key i v Read or set by index, O(N).
LLEN key Length, O(1).
LTRIM key a b Keep only the slice; with LPUSH it makes a capped list.
LINSERT / LREM key count v Insert before or after a value; remove matches.
LMOVE src dst LEFT|RIGHT LEFT|RIGHT Atomically move an item between lists (reliable queues).

Hashes

Command What it does
HSET key f v [f v...] Set fields; replies with the number of new fields.
HGET key f / HMGET key f... / HGETALL key Read one, several or all fields (HGETALL is O(N)).
HDEL key f... / HEXISTS key f / HLEN key Delete, test, count.
HINCRBY key f n / HINCRBYFLOAT Atomic field counters.
HKEYS / HVALS / HSCAN List names, list values, iterate big hashes.
HSETNX key f v Set a field only if it is absent.
HEXPIRE key s FIELDS n f... Per-field expiry (Redis 7.4 and later).

Sets

Command What it does
SADD key m... / SREM key m... Add or remove members.
SISMEMBER key m / SMISMEMBER key m... Membership test, O(1).
SMEMBERS key / SCARD key / SSCAN List (O(N)), count, iterate.
SINTER / SUNION / SDIFF key... Intersection, union, difference; ...STORE dst saves the result.
SINTERCARD n key... Size of the intersection without building it.
SPOP key [n] / SRANDMEMBER key [n] Remove or only read random members.
SMOVE src dst m Move a member.

See Sets.

Sorted sets

Command What it does
ZADD key [NX|XX] [GT|LT] score member... Add or update; replies with how many members were new.
ZINCRBY key n m Add n to a member's score.
ZSCORE key m / ZRANK key m / ZREVRANK key m Score; rank from the lowest; rank from the highest (0-based).
ZRANGE key a b [REV] [WITHSCORES] Read by rank; add BYSCORE or BYLEX for ranges, LIMIT off n to page.
ZCARD key / ZCOUNT key min max Size; members in a score range.
ZREM key m... / ZREMRANGEBYRANK / ZREMRANGEBYSCORE Delete members.
ZPOPMIN key [n] / ZPOPMAX / BZPOPMIN Pop the lowest or highest, optionally blocking.
ZUNIONSTORE / ZINTERSTORE dst n key... [WEIGHTS ...] Combine boards into a new key.

Ties in score are ordered by member name. See Sorted Sets.

Streams

Command What it does
XADD key [MAXLEN ~ n] * f v... Append an entry (* generates the ID).
XLEN key / XRANGE key - + Count; read a range of entries.
XREAD [COUNT n] [BLOCK ms] STREAMS key id Read new entries ($ means only newer ones).
XGROUP CREATE key group id [MKSTREAM] Create a consumer group.
XREADGROUP GROUP g consumer ... STREAMS key > Read entries not yet delivered to the group.
XACK key group id... Confirm processing.
XPENDING key group / XAUTOCLAIM Inspect and take over unacknowledged entries.
XTRIM key MAXLEN ~ n / XDEL key id Cap or delete entries.

See Streams.

Bitmaps, HyperLogLog and geo

Command What it does
SETBIT key offset 0|1 / GETBIT key offset Set or read one bit.
BITCOUNT key / BITPOS key bit / BITOP AND|OR|XOR|NOT dst key... Count, find, combine bitmaps.
BITFIELD key ... Read and write small integers packed in a string.
PFADD key item... / PFCOUNT key... / PFMERGE dst key... Approximate distinct counts (about 0.81 percent error, 12 KB per key).
GEOADD key lon lat member Add a place (stored in a sorted set).
GEODIST key a b [km|m] / GEOPOS key m Distance; coordinates.
GEOSEARCH key FROMLONLAT lon lat BYRADIUS r km ASC Nearby search (replaces GEORADIUS).

Transactions, scripts and messaging

Command What it does
MULTI / EXEC / DISCARD Queue commands, run them uninterrupted, or drop the queue. No rollback.
WATCH key... / UNWATCH Optimistic locking: EXEC returns nil if a watched key changed.
EVAL script numkeys key... arg... Run Lua atomically; use KEYS[n] and ARGV[n].
SCRIPT LOAD / EVALSHA sha numkeys ... Cache a script and call it by hash.
FUNCTION LOAD / FCALL name numkeys ... Named server-side functions (Redis 7 and later).
PUBLISH ch msg / SUBSCRIBE ch... / PSUBSCRIBE pat... Fire-and-forget messaging (at-most-once).
SPUBLISH / SSUBSCRIBE Sharded Pub/Sub for clusters.

See Transactions, Pipelining and Pub/Sub and Lua Scripting and Functions.

Persistence

Setting or command Meaning
save 3600 1 300 100 60 10000 RDB snapshot rules: after N seconds if at least M keys changed.
BGSAVE / LASTSAVE Snapshot in a child process; time of the last success.
SAVE Blocking snapshot: avoid it on a live server.
appendonly yes Turn the append-only file on.
appendfsync always|everysec|no Flush policy; everysec is the default and loses up to about a second.
BGREWRITEAOF Compact the AOF in the background.
dir / dbfilename Where the files are written.

See Persistence: RDB and AOF.

Replication, Sentinel and Cluster

Command What it does
REPLICAOF host port / REPLICAOF NO ONE Become a replica; promote to primary.
ROLE / INFO replication Role, offsets and lag.
WAIT n ms Block until n replicas acknowledge the writes so far (does not make Redis strongly consistent).
SENTINEL get-master-addr-by-name name Ask Sentinel for the current primary.
CLUSTER INFO / CLUSTER NODES State and topology.
CLUSTER KEYSLOT key Slot of a key: CRC16(key) mod 16384 (only the is hashed when present).
redis-cli -c Follow MOVED and ASK redirects automatically.

See Replication, High Availability with Sentinel and Redis Cluster and Sharding.

Configuration, memory and security

Setting or command Meaning
maxmemory 2gb Memory limit for data.
maxmemory-policy noeviction (default), allkeys-lru, allkeys-lfu, allkeys-random, volatile-lru, volatile-lfu, volatile-random, volatile-ttl.
maxmemory-samples 5 Sample size of the approximate LRU/LFU.
hz 10 How often background tasks such as active expiry run.
io-threads n Optional threads for socket I/O (commands still run on one thread).
bind / protected-mode / port Which addresses listen. Never expose Redis to the internet.
requirepass / ACL SETUSER name on >pass ~key:* +get +set Authentication; per-user command and key permissions.
redis-benchmark -q -n 100000 Quick throughput test.
redis-cli --bigkeys Find the largest keys by sampling.

See Memory Limits and Eviction, Securing Redis and Performance and Latency.

Slow or risky commands

Avoid in production Use instead
KEYS * SCAN with COUNT.
FLUSHALL / FLUSHDB on a live server A restricted ACL; ASYNC if you truly must.
SMEMBERS, HGETALL, LRANGE 0 -1 on huge keys SSCAN, HSCAN, paged LRANGE.
DEL on a huge key UNLINK.
SAVE BGSAVE.
MONITOR left running Short sessions only.

Safety reminders

  • Treat Redis as memory first: set maxmemory and a policy that matches the job (cache or store).
  • Persistence is a choice. No setting makes Redis as durable as a database, and replication is asynchronous.
  • Give every cache key a TTL unless you really want it forever, and add jitter so keys do not expire together.
  • Use random tokens for locks and release them with a script that checks the token.
  • MULTI/EXEC does not roll back; check every reply.
  • Keep Redis on a private network, require authentication, restrict dangerous commands with ACLs and enable TLS when traffic leaves the host.
  • In Cluster, plan hash tags for keys that must be used together.

Try the stand-ins

Redis cannot run here, so these two examples are plain JavaScript. The first holds a few rows of the tables above and searches them. Edit the find(...) calls to look for something else.

JS Search a mini command table

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The second maps a need to a data type with a few keyword rules. It is deliberately simple: real modelling starts from your access patterns, as described in Choosing the Right Data Type.

JS Which data type fits?

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which command iterates the keyspace without blocking the server for long?

    SCAN returns a small batch plus a cursor, so you can walk a large database in many short calls. KEYS does the whole walk in one blocking command.
  2. 2. TTL returns -2 for a key. What does it mean?

    -1 means the key exists without an expiry, and -2 means there is no such key (for example it already expired).
  3. 3. You want the rank of a player counted from the highest score. Which command do you use?

    ZREVRANK counts from the highest score (0 is the leader). ZRANK counts from the lowest.
  4. 4. Which pair makes a capped list of the latest 100 items?

    LPUSH adds the newest item at the head and LTRIM key 0 99 drops everything beyond the first 100.

Summary

  • Choose the type by access pattern: strings for values and counters, lists for queues, hashes for records, sets for uniqueness, sorted sets for rankings, streams for logs.
  • Always think about expiry (EXPIRE, TTL), and remember that a plain SET clears a TTL.
  • Prefer SCAN over KEYS, UNLINK over DEL for big keys, and BGSAVE over SAVE.
  • Transactions queue and run uninterrupted with no rollback; WATCH and Lua cover read-then-write logic.
  • Persistence, replication and eviction are configuration choices with trade-offs; Cluster adds sharding by 16,384 hash slots.
  • Keep Redis private, authenticated and memory-limited.

You have reached the end of the Redis course. Revisit the Redis course overview any time to review a topic, and use the practice exercises and interview questions to keep your skills sharp.