Redis essentials: 50 cards on data types, caching and persistence
Redis basics: strings, lists, sets, sorted sets, hashes and streams, TTLs, RDB and AOF persistence, pub/sub, caching patterns, eviction and MULTI/EXEC.
Practice now
Study without an account
Scheduled with the default Askesis timings. Progress is saved in this browser.
All 50 cards
- 1What is Redis?An in-memory data structure server: keys map to strings, lists, sets, hashes, sorted sets, streams and more. Common uses are caching, sessions, queues, rate limits and leaderboards
- 2How does Redis execute commands?One at a time on a single main thread, so every command is atomic and never interleaves with another client’s commandRedis 6+ can use I/O threads for networking, and some work, like freeing big values, runs in background threads.
- 3Why can one slow command hurt every client?Nothing else runs while the main thread is busy. Avoid
KEYS *,SMEMBERSorHGETALLon huge keys, and long Lua scripts, in production - 4
KEYSvsSCANKEYSreturns every match in one blocking O(N) call;SCANwalks the keyspace in small steps with a cursor. Repeat with the returned cursor until it is0; keys may appear more than onceredisSCAN 0 MATCH user:* COUNT 100 - 5
DELvsUNLINKBoth remove keys.DELfrees the memory right away (by default), which is slow for huge values;UNLINKremoves the key at once and frees memory in a background thread - 6What can a Redis string hold?Any binary-safe value up to 512 MB: text, numbers, serialized JSON or raw bytes;
SETandGETare O(1) - 7What do the two
INCRcalls return?redisSET views 10 INCR views INCR missing11and1:INCRis atomic and treats a missing key as 0. It errors if the value isn’t an integer - 8What does
SET lock:job:42 worker-1 NX EX 30do?Sets the key only if it doesn’t exist (NX), expiring after 30 seconds (EX); it returns nil if the key already exists. The basis of a simple lock - 9What is a Redis list?An ordered sequence of strings with O(1) push and pop at both ends:
LPUSH,RPUSH,LPOP,RPOP - 10What does
LRANGE mylist 0 -1return?Every element of the list: negative indexes count from the end, so-1is the last element - 11Build a simple job queue with a listProducers
LPUSH jobs …; workers callBRPOP jobs 0, which blocks until an item arrives (a timeout of 0 waits forever)A popped job is lost if the worker crashes; streams with consumer groups, orLMOVEto a processing list, add reliability. - 12Keep only the 100 most recent items in a listredis
LPUSH recent:42 "item" LTRIM recent:42 0 99 - 13What is a Redis set?An unordered collection of unique strings:
SADD,SREMandSISMEMBERare O(1), andSINTER,SUNIONandSDIFFcombine sets - 14What is a sorted set?Unique members, each with a floating-point score, kept ordered by score (ties ordered lexicographically); adding and ranking are O(log N)Typical uses: leaderboards, priority queues and time-based indexes.
- 15Build a leaderboard and read the top 10redis
ZADD scores 1500 alice 1200 bob ZINCRBY scores 50 bob ZRANGE scores 0 9 REV WITHSCORESREVneeds Redis 6.2+; older code usesZREVRANGE. - 16Store and update a user object in a hashredis
HSET user:42 name Ada email [email protected] HGET user:42 name HINCRBY user:42 logins 1HGETALLreturns every field;HSETtakes several field–value pairs (HMSETis deprecated). - 17Why use a hash instead of a JSON string?You can read or change one field (
HGET,HINCRBY) without fetching and rewriting the whole objectSince Redis 7.4, individual hash fields can even expire (HEXPIRE). - 18What is a Redis stream?An append-only log of entries, each with an ID and field–value pairs; consumers read ranges, block for new entries, or share work through consumer groups
- 19What does
XADD orders * id 42 total 9.99do?Appends an entry to theordersstream;*makes Redis generate an ID like1718000000000-0(milliseconds, then a sequence number) - 20How do stream consumer groups work?Each entry goes to one consumer in the group and stays pending until acknowledged with
XACK, so messages from a crashed consumer can be claimed and retried (XAUTOCLAIM)redisXGROUP CREATE orders workers $ MKSTREAM XREADGROUP GROUP workers w1 COUNT 10 STREAMS orders > XACK orders workers 1718000000000-0 - 21Streams vs pub/subStreams store messages, so consumers can replay history, acknowledge work and catch up after downtime; pub/sub delivers only to clients connected at that moment
- 22What is a HyperLogLog for?Counting unique items approximately (
PFADD,PFCOUNT) with about 0.81% standard error, using at most 12 KB per keyExample: unique visitors per day without storing every visitor ID. - 23Give a key a time to liveredis
EXPIRE session:abc 1800 SET session:abc "data" EX 1800The first adds a 30-minute TTL to an existing key; the second sets the value and TTL together.PEXPIREtakes milliseconds,EXPIREATa Unix timestamp, andPERSISTremoves the expiry. - 24What do
-1and-2fromTTLmean?-1: the key exists but has no expiry.-2: the key doesn’t exist. OtherwiseTTLreturns the remaining seconds - 25Does overwriting a key with
SETkeep its TTL?No.SETclears the expiry unless you addKEEPTTL(Redis 6.0+); commands that modify the value in place, likeINCR,LPUSHorHSET, keep it - 26How do expired keys get removed?Passively, when a client accesses an expired key, and actively, by a background cycle that samples keys with a TTL; expired keys can linger in memory briefly
- 27What is RDB persistence?Point-in-time snapshots of the dataset written to a compact file on a schedule or with
BGSAVE; restarts are fast, but writes since the last snapshot are lost on a crash - 28What is AOF persistence?An append-only file logging every write, replayed on restart. With the default
appendfsync everysecyou lose at most about a second of writes;alwaysis safest and slowest - 29Why does Redis rewrite the AOF?The log keeps growing with every write; a rewrite (automatic, or
BGREWRITEAOF) replaces it with the minimal set of commands that recreates the current data - 30With both RDB and AOF enabled, which one loads on restart?The AOF, because it is usually the more complete record of recent writesUsing both is common: AOF for durability, RDB files for backups.
- 31Why can
BGSAVEneed a lot of extra memory?It forks a child that shares memory copy-on-write; every page the parent modifies during the save gets copied, up to double the memory under heavy writes - 32Publish and subscribe to messagesredis
SUBSCRIBE news PSUBSCRIBE news.* PUBLISH news "hello"PSUBSCRIBEmatches channels by pattern;PUBLISHreturns how many subscribers received the message. - 33What delivery guarantee does pub/sub give?At most once: messages aren’t stored, so a subscriber that is disconnected or slow to reconnect simply misses them
- 34Why does a subscribed connection reject
GET?With the RESP2 protocol, a connection in subscribe mode can only run (un)subscribe commands,PING,RESETandQUIT; use a separate connection for other commandsRESP3 connections can mix both. - 35How does the cache-aside pattern work?Read from the cache; on a miss, load from the database and store it with a TTL. On writes, update the database and delete the cache keyjs
// node-redis let user = await redis.get(`user:${id}`) if (!user) { user = JSON.stringify(await db.users.find(id)) await redis.set(`user:${id}`, user, { EX: 300 }) } - 36On a write, why delete the cached value instead of updating it?Two concurrent writers can update the cache in the opposite order from the database, leaving stale data; deleting lets the next read load the fresh value
- 37Write-through vs write-behind cachingWrite-through writes to the cache and the database together on every write; write-behind writes to the cache and persists to the database later, which is faster but can lose data
- 38What is a cache stampede?A popular key expires and many requests miss at once, all hitting the database. Fix it with a lock so one request rebuilds the value, early refresh, or random TTL jitter
- 39Conventional Redis key namingColon-separated namespaces from general to specific, like
user:42:profileorsession:abc123 - 40What is the default
maxmemory-policy?noeviction: oncemaxmemoryis reached, commands that add data fail with an out-of-memory error while reads keep workingFor a pure cache, switch to an eviction policy likeallkeys-lruorallkeys-lfu. - 41
allkeys-lruvsvolatile-lruallkeys-lrucan evict any key;volatile-lruonly evicts keys that have a TTL, and acts likenoevictionif none do - 42LRU vs LFU evictionLRU evicts the least recently used keys; LFU (Redis 4.0+) evicts the least frequently used, which better protects keys that are steadily popular
- 43Is Redis’s LRU eviction exact?No. It samples a few keys (
maxmemory-samples, default 5) and evicts the best candidate among them, which approximates LRU cheaply - 44What do
MULTIandEXECdo?Commands afterMULTIare queued;EXECruns them in order as one block, with no other client’s command in betweenredisMULTI INCR orders:count LPUSH orders:recent 42 EXEC - 45Does a Redis transaction roll back if a command fails?No. If a command fails while running (say, a wrong type), the rest still execute. Only errors detected while queuing, like bad syntax, abort the whole transaction
- 46What does
WATCHadd to a transaction?Optimistic locking: if a watched key changes beforeEXEC, the transaction is aborted andEXECreturns nil, so the client retriesredisWATCH balance:42 GET balance:42 MULTI SET balance:42 90 EXEC - 47Why use a Lua script (
EVAL) instead ofMULTI?A script runs atomically on the server and can branch on values it reads, like deleting a lock only if you still own it, whichMULTIcan’t expressredisEVAL "if redis.call('GET', KEYS[1]) == ARGV[1] then return redis.call('DEL', KEYS[1]) end return 0" 1 lock:job:42 worker-1 - 48Pipelining vs transactionsPipelining sends many commands without waiting for each reply, saving round trips, but other clients’ commands can interleave;
MULTI/EXECis atomic - 49How does Redis Cluster split data, and what breaks?Keys are spread over 16,384 hash slots across nodes; multi-key commands fail unless all keys are in the same slotHash tags force a slot:
{user:42}:cartand{user:42}:profilehash onlyuser:42. - 50Allow 100 requests per minute per IPredis
INCR rate:203.0.113.7:202610151230 EXPIRE rate:203.0.113.7:202610151230 60 NXReject whenINCRreturns more than 100.EXPIRE … NX(Redis 7.0+) sets the expiry only on the first hit of the window.
Frequently asked questions
Does this deck apply to Valkey?
Yes. Valkey is a fork of Redis 7.2.4, so the commands and concepts here work the same; only features added to Redis later, like hash field expiry in 7.4, may differ.
Is Redis open source?
Redis moved to source-available licenses with version 7.4 in 2024, and Redis 8 added the AGPLv3 as an open-source option. Valkey remains BSD-licensed.
Can Redis be my primary database?
It can for data that fits in memory, with AOF persistence and replication, but most teams use it next to a database as a cache, queue or session store.
More in Databases
SQL
Learn SQL that holds up in production: joins, grouping, NULL semantics, indexes, transactions, window functions and CTEs.
50 cardsPostgreSQL
PostgreSQL know-how: data types, B-tree and GIN indexes, EXPLAIN, isolation levels, MVCC and VACUUM, JSONB, CTEs, window functions, constraints and roles.
50 cardsMongoDB
MongoDB basics: documents and BSON, CRUD in mongosh, query operators, indexes, the aggregation pipeline, embedding vs referencing, replica sets and sharding.
50 cards