LearnThatStack Ace your next interview

Redis

Commands for Redis 7.2+ in redis-cli Checked Oct 2026 103 commands

The model

  • Redis keeps every key in RAM. Each key holds one data structure, such as a string, hash, list, set, sorted set or stream.
  • One main thread runs commands one at a time, so each is atomic. A slow one blocks every client.
  • RDB snapshots and the append-only file (AOF) save data to disk. A crash loses the writes since the last save.
  • Replicas copy the master asynchronously. Sentinel promotes one when the master fails. Redis Cluster also shards the keys.
  • At maxmemory, the eviction policy deletes keys, or the default noeviction rejects writes.
Clientsmany connectionsMain threadevent loopMemoryevery keyDisk & replicasAOF and RDB filesWRITESET k v queuedrun in microsecondsOK not on disk yetwrite copy laterSLOWKEYS * blocks everyone
One thread runs commands in memory, one at a time, so a slow one blocks everyone. The OK doesn't wait for disk or replicas, so a crash can lose the write.

What Redis is

an in-memory store, its speed, and its licenses

Redis or a relational database

Compare it with a relational databaseIt's far faster, but the data must fit in RAM. It has no joins and no rollback.
Name the common usesCaching, sessions, counters, rate limits, leaderboards and queues.
Use it beside a SQL databaseRedis caches the most-read data. The database stays the source of truth.

TrapDon't say Redis loses its data on restart. RDB snapshots and the AOF reload it.

Licenses, Valkey and Redis 8

Say what changed in Redis 7.4In March 2024, it left BSD for RSALv2 and SSPLv1, source-available licenses.
Say what Valkey isA BSD-licensed fork of Redis 7.2.4, a Linux Foundation project.
Say what Redis 8 changed (2025)It added AGPLv3, an OSI-approved open source license, as a third choice.
Store JSON or search text (8.0+)JSON.SET user:1 $ '{"name":"Ann"}'FT.SEARCH idx "action"Before Redis 8, you loaded these as modules.

TrapRunning Redis for your own company is allowed under every license. The limits are on offering it to others as a managed service.

Data types & commands

pick the structure that fits, then its commands

Pick a data type

Store a value or a counterSET page:title "Home"INCR page:viewsA string, up to 512MB.
Store an object's fields under one keyHSET user:1 name AnnA hash.
Keep items in the order you add themLPUSH feed post:9A list.
Keep unique members, with no orderSADD tags redisA set.
Store a yes-or-no flag per userSETBIT active 42 1BITCOUNT activeA bitmap.
Count unique visitors in at most 12 KBPFADD visitors u1PFCOUNT visitorsHyperLogLog. The count is an estimate, with a 0.81% standard error.
Find places within 5 km of a pointGEOSEARCH shops FROMLONLAT 13.4 38.1 BYRADIUS 5 kmA geospatial index.

TrapGEOADD takes longitude first, then latitude. Swap them and every distance is wrong.

Sorted sets and leaderboards

head50head3050head10304050
find 40Go right while the next score is at most 40, otherwise go down. Dark boxes are the path.
Show the top 10 with their scoresZRANGE board 0 9 REV WITHSCORES
Add 50 points to a playerZINCRBY board 50 ana
Get a player's rank from the topZREVRANK board anaZRANK counts from the lowest score. Both count from 0.
Say how Redis stores a sorted setOBJECT ENCODING boardSmall ones as a listpack. Large ones as a skip list plus a hash table.

TipThe hash table answers ZSCORE in O(1). The skip list makes inserts and ranks O(log N).

TrapMembers with equal scores sort byte by byte, and REV reverses that order too.

Keys, expiry & SCAN

expire, find and delete keys without blocking

Expire keys with a TTL

Set a value that expires in an hourSET session:42 data EX 3600
Add a TTL, check it, or remove itEXPIRE cart:42 600TTL cart:42PERSIST cart:42TTL returns -1 for no TTL, and -2 for no key.
Expire one field of a hash (7.4+)HEXPIRE user:1 60 FIELDS 1 token
Say how Redis deletes expired keysOn read, and in a sweep 10 times a second. Clients never see an expired key.

TrapA plain SET clears the TTL. Add KEEPTTL to keep it. INCR and HSET keep it anyway.

Find and delete keys

List keys that match a patternKEYS user:*It's O(N) in one call, so it blocks every client. Avoid it in production.
Walk the keys a batch at a timeSCAN 0 MATCH user:* COUNT 100Repeat with the cursor it returns until that is 0. It may return a key twice.
Walk one big hash, set or sorted setHSCAN user:1 0SSCAN tags 0ZSCAN board 0
Delete a keyDEL cart:42It frees the memory on the main thread, so a huge value blocks everyone.
Empty one database, or every databaseFLUSHDBFLUSHALL

TrapNothing undoes FLUSHALL. Only a backup, or an AOF copy cut back to before it, brings the data back.

Memory & eviction

cap memory, choose what to evict, and shrink keys

Cap memory and evict keys

Cap the memory Redis may useCONFIG SET maxmemory 2gbAt the cap, the default noeviction rejects writes. Reads still work.
Evict the least recently used keys, for a cachemaxmemory-policy allkeys-lruallkeys-lfu evicts the least frequently used instead.
Evict only keys that have a TTLmaxmemory-policy volatile-lruUse it when cache keys share Redis with permanent ones.

TipLRU and LFU are approximate. Redis samples 5 keys and evicts the best one.

TrapRedis may not return freed memory to the operating system. Size the server for peak use.

Shrink memory use

Measure one key's memoryMEMORY USAGE user:1
Store an object as one hash, not a key per fieldHSET user:1 name Ann age 30Every key costs extra memory, and Redis stores small hashes compactly.
Keep hashes of up to 512 fields compacthash-max-listpack-entries 512The compact encoding is a listpack. Higher limits save memory but slow lookups.

TrapA temporary key with no TTL stays in memory until eviction removes it.

Big keys and hot keys

Find the biggest keysredis-cli --bigkeysredis-cli --memkeysBoth scan, so they don't block.
Split a big hashHash each field into one of N bucket keys.
Find the hottest keysredis-cli --hotkeysIt needs an LFU eviction policy.
Spread the load of a hot keyCache it in the app, or read it from replicas. Split a hot counter into sub-keys.

TrapExpiring or evicting a big key blocks too, unless lazyfree-lazy-expire and lazyfree-lazy-eviction are on.

Persistence & backups

save data to disk, and get it back

RDB, AOF and backups

Take a snapshot every 900 seconds if a key changedsave 900 1RDB. A crash loses every write since the last snapshot.
Take a snapshot nowBGSAVEA forked child writes it. SAVE blocks every client instead.
Log every write, synced once a secondappendonly yesappendfsync everysecAOF. A crash loses about one second of writes.
Sync every write to diskappendfsync alwaysEvery write waits for the disk.
Turn persistence off for a pure cacheCONFIG SET save ""CONFIG SET appendonly noAfter a restart, Redis is empty.
Copy a live server's snapshot to this machineredis-cli --rdb /backup/dump.rdbCopying a running server's RDB file is safe too.
Restore from an RDB fileStop Redis, copy the file in, and start it with AOF off. With AOF on, Redis loads the AOF instead.

TipWith both on, Redis loads the AOF at startup, because it's more complete.

TrapDon't let a master with persistence off restart by itself. It comes back empty, and its replicas copy the empty data.

MULTI, Lua & pipelining

batch commands, or run them as one step

Transactions and pipelines

Run commands as one isolated stepMULTIEXECRedis queues them, then runs them in order with nothing in between.
Abort if a key changes before EXECWATCH balanceOptimistic locking. EXEC returns null if it changed, so retry.
Say what happens when a command failsA syntax error cancels it all. A runtime error fails only that command.
Send many commands, then read all the repliesPipelining. One round trip per batch, not per command, but it isn't atomic.
Choose a pipeline, MULTI or LuaA pipeline saves round trips. MULTI adds isolation, and Lua adds logic.

TipA command can't use an earlier one's result. Use a Lua script for that.

TrapThere is no rollback. Commands that succeeded stay applied when another one fails.

Lua scripts and functions

Run a script atomicallyEVAL "return redis.call('GET', KEYS[1])" 1 kPass key names in KEYS, so it works in Redis Cluster.
Cache a script, then run it by its SHA1SCRIPT LOAD "<script>"EVALSHA <sha1> 1 kA restart clears the cache. Reload the script after a NOSCRIPT error.
Call a named functionFCALL myfn 1 kFunctions came in 7.0 to replace EVAL. Redis saves them with the data.

TrapA running script blocks every client. Keep scripts short.

Pub/Sub, queues & Streams

broadcast messages, and hand out jobs

Pub/Sub

Listen on channels, or on a patternSUBSCRIBE news sportsPSUBSCRIBE news:*
Send a message to everyone subscribed nowPUBLISH news "hello"It returns how many subscribers got it.
Keep a channel inside one shard (7.0+)SSUBSCRIBE ordersSPUBLISH orders hiIn a cluster, plain PUBLISH goes to every node.
Choose Pub/Sub or a StreamUse Pub/Sub when a lost message does no harm, and a Stream when none may be lost.

TrapDelivery is at most once. An offline or crashed subscriber misses those messages for good.

Job queues with lists

Push a job, and block until a worker takes itLPUSH jobs job:1BRPOP jobs 0If the worker crashes, the job is lost.
Take a job so a crash can't lose itBLMOVE jobs doing RIGHT LEFT 0It moves the job to a processing list. Remove it with LREM when done.
Take the most urgent job firstZADD tasks 10 urgent:1BZPOPMAX tasks 0A sorted set scored by priority.

TipA reliable queue can run a job twice. Make handlers idempotent, so a second run has the same result.

Streams and consumer groups

Append an entry with an automatic IDXADD orders * id 7 total 99The ID is a millisecond time plus a sequence number.
Replay entries by ID rangeXRANGE orders - +
Create a consumer group that reads from the startXGROUP CREATE orders g1 0 MKSTREAMWith $ instead of 0, it reads only new entries.
Read new entries as one worker, then acknowledge themXREADGROUP GROUP g1 w1 STREAMS orders >XACK orders g1 <id>Each entry goes to one worker and stays pending until acknowledged.
Take over entries a dead worker left pendingXAUTOCLAIM orders g1 w2 60000 0Here it claims entries idle for 60 seconds or more.

TipEntries stay in memory until you trim them with XTRIM or MAXLEN.

TrapRecovery isn't automatic. Pending entries wait until their worker rereads them or another worker claims them.

Replicas, Sentinel & Cluster

copy data, fail over, and shard

Replication

Make this server a replicaREPLICAOF 10.0.0.1 6379It deletes this server's data and copies the master's.
Promote a replica by handREPLICAOF NO ONEThen point the other replicas at it.
Say how a replica catches upAfter a short break, PSYNC sends only what it missed. Otherwise the master sends a full snapshot.
Refuse writes when no replica keeps upmin-replicas-to-write 1min-replicas-max-lag 10It limits what a network split can lose.

TrapReplication is asynchronous. A master can acknowledge a write and fail before any replica has it. WAIT narrows that window.

Sentinel

Choose Sentinel or ClusterSentinel fails over one master with replicas. Cluster also shards the data.
Watch a master, with a quorum of 2sentinel monitor mymaster 10.0.0.1 6379 2The quorum is how many Sentinels must agree the master is down.
Ask Sentinel for the current masterSENTINEL get-master-addr-by-name mymasterClients must ask, unless a script moves a virtual IP to the new master.
Fail over for planned maintenanceSENTINEL FAILOVER mymaster

TrapThe quorum only marks the master down. A failover needs a majority of all Sentinels, so run at least three.

Redis Cluster

Find which hash slot a key is inCLUSTER KEYSLOT user:42The slot is CRC16 of the key, mod 16,384. Each master owns a range of slots.
Keep related keys in one slotMGET {user:42}:cart {user:42}:ordersA hash tag. Redis hashes only the part in braces.
Say what MOVED and ASK meanMOVED means the slot lives on another node now. ASK redirects one request mid-move.
Move slots to another noderedis-cli --cluster reshard 10.0.0.1:6379Redis never reshards by itself. Moving a big key blocks both nodes.
Fail over to a replica without losing writesCLUSTER FAILOVERRun it on the replica. It waits until it has caught up.

TrapMulti-key commands, transactions and scripts need all their keys in one slot. Otherwise they fail with CROSSSLOT.

Caching, locks & rate limits

the designs interviewers ask you to build

Caching strategies

Cache reads with cache-asideRead Redis first. On a miss, read the database and cache the result with a TTL.
Keep the cache fresh on every writeWrite-through. Update the database, then the cache. Writes get slower.
Make writes as fast as possibleWrite-behind. Update the cache and queue the database write. A crash before that write loses it.
Stop a cache stampede on a hot keyMany requests miss it at once. Let one rebuild it under a short lock, or refresh it early.

TipAdd random jitter to TTLs, so many keys don't expire together.

TrapWithout a TTL, a key whose invalidation goes missing stays stale forever. Put a TTL on every cached key.

Invalidate cached data

Clear an entry when its data changesDEL user:42Delete it rather than update it.
Skip deletes with versioned keysPut a version number in the key and raise it on change. Old entries expire.
Have Redis tell each client what changedCLIENT TRACKING ONClient-side caching. Redis sends an invalidation for each key the client read.

TrapDelete after the database commit, never before. An earlier delete lets a reader cache the old value again.

Distributed locks

Take a lock that expires in 30 secondsSET lock:order:7 <token> NX PX 30000NX sets it only if it's free. The token is a random value unique to you.
Release it only if you still hold it (8.4+)DELEX lock:order:7 IFEQ <token>Before 8.4, compare and delete in one Lua script.
Lock across 5 independent mastersRedlock. You hold it if at least 3 grant it in time.
Stop a holder that paused too long from writingFencing tokens. Each grant gets a higher number, and storage rejects older ones.

TrapA replica doesn't make a lock safe. The master can fail before the key reaches it, and a second client gets the same lock.

Rate limiting

windowsminute 1minute 2fixedslidingtime

With a limit of 3 a minute, the fixed window lets 6 requests through in 50 seconds. The sliding window rejects the last 3, drawn hollow.

Allow 100 requests per client each minuteINCR rl:42:1405EXPIRE rl:42:1405 60Fixed window. Set the expiry when INCR returns 1.
Count requests in the last 60 seconds exactlySliding window log. A sorted set holds one entry per request, scored by time.
Allow short bursts at a steady average rateToken bucket. A hash stores the tokens and the last refill time.

TrapSeparate INCR and EXPIRE calls aren't atomic. A crash between them leaves a counter that never expires.

Model data around your queries

Query users by an age rangeZADD idx:age 30 user:123ZRANGE idx:age 25 35 BYSCOREA sorted set scored by age is an index you keep by hand.
Find mutual friendsSINTER friends:1 friends:2

TrapA hand-made index drifts when a write path forgets it. Update the data and the index in one MULTI or script.

Monitoring & security

find what's slow, and lock Redis down

Find what's slow

List the slowest recent commandsSLOWLOG GET 10
Log commands slower than 10 msslowlog-log-slower-than 10000The unit is microseconds.
Record latency spikes over 100 mslatency-monitor-threshold 100LATENCY LATESTThe latency monitor is off until you set this. The unit is milliseconds.
Read the hit rate and memory statsINFO statsINFO memoryThe hit rate comes from keyspace_hits and keyspace_misses.
Watch every command liveMONITORIt can halve throughput, so run it only briefly.

TrapDisable transparent huge pages on Linux. They slow the fork behind every RDB save and AOF rewrite.

Lock Redis down

Listen only on private interfacesbind 127.0.0.1 10.0.0.5With no password and no bind, protected mode refuses remote clients.
Set a password for the default userrequirepass <password>
Create a user limited to some keys and commandsACL SETUSER app on >pw ~cache:* +@read -@dangerous
Encrypt every connection with TLStls-port 6380port 0port 0 closes the plain-text port.

TipBlock FLUSHALL and CONFIG with -@dangerous, not the deprecated rename-command.

TrapA new ACL user starts disabled. Without on in its rule, every login fails.

Found this useful? Pass it on.
Pro · $10/mo

This sheet stays free. With Pro, you can:

  • Every answer on this sheet. Read the full answer to all 33 questions it links, not just the 3 free ones.
  • My sheet. The cards you star and the ones you miss in Quiz me, from every sheet, on one page to quiz and print.
  • PDFs. Download this sheet and My sheet, laid out for A4, with every question a link to its answer.
  • The rest of Pro. Every answer in the question library, and 1,000 AI credits a month.