skip to content

Redis

3 roadmaps206 questionsupdated

You will learn Redis end to end: its data structures, caching mechanics, persistence, messaging, clustering, atomicity tools, memory management, and single-threaded internals. Redis shows up in nearly every backend and system-design interview because it is the default answer for caching, rate limiting, sessions, and leaderboards.

on this pageshow

guide

overview

~1 min

Redis is an in-memory data structure server: a single thread applies client commands to keys whose values are strings, hashes, lists, sets, sorted sets or streams. It shows up in backend and system-design interviews because it is the usual answer for caching, rate limiting, sessions, locks, leaderboards and lightweight queues, and every one of those answers hides a follow-up about memory, durability or atomicity. A strong Redis answer names the command or setting, says what happens when the process crashes or runs out of memory, and says what the choice cost. The hub splits by concern. [Core data structures](/topics/db-redis-data-structures) is the vocabulary: which type fits a problem, and what it costs in time and bytes. [Caching with Redis](/topics/db-redis-caching) covers its most common job, and [eviction and expiration](/topics/db-redis-eviction-expiration) covers what happens at the memory ceiling and when keys actually disappear. [Persistence: RDB and AOF](/topics/db-redis-persistence) and [replication and cluster](/topics/db-redis-replication-cluster) explain what survives a failure and how data spreads across machines. [Transactions and scripting](/topics/db-redis-transactions-scripting) is about atomic multi-step work, [pub/sub and streams](/topics/db-redis-pubsub-streams) about the two messaging models, and [internals](/topics/db-redis-internals) about the event loop, the protocol and the latency tooling beneath all of it. Junior rounds stay close to types and commands: which structure models a leaderboard, what a TTL does, why `KEYS` is dangerous. Senior rounds become incident stories: a snapshot that nearly doubles memory, a hot key pinning one shard, stale reads after failover, a "transaction" that half-applied. Start with the data structures and the single-threaded execution model, then expiry and eviction, because every caching question assumes both. Persistence and replication come next; cluster, scripting and streams build on all of them.

primer

### One thread runs the commands Redis executes commands one after another on its main thread. That is why each command is atomic without locks, and also why one expensive command, such as a scan of the whole keyspace, deleting a huge collection or a long script, delays every other client. Newer versions add threads for socket I/O and background freeing, but command execution stays serial. ### Memory is the budget Every value lives in RAM. Two settings decide what happens at the ceiling: the memory limit, and the policy that picks what to evict, or to refuse writes instead. Expiry is not a timer on each key; expired keys are cleaned up lazily and by sampling, so memory and key counts lag behind TTLs. Interviewers want you to connect the eviction policy to the workload: a pure cache and a store of record need opposite answers. ### Choose the structure, not only the key Redis types are server-side data structures with their own operations: counters, membership tests, blocking pops, rank queries, consumer groups. Picking the right one moves logic into one atomic command. Small collections are stored in compact encodings that switch to general structures past size thresholds, which is why memory per key can change sharply as a collection grows. ### Durability is opt-in and asynchronous An acknowledged write exists in the primary's memory. Whether it survives a crash depends on the persistence mode (snapshots, an append-only log, or both), on the fsync policy, and on whether a replica received it before the primary died. Snapshots and log rewrites fork the process, and copy-on-write makes a busy fork expensive. Good answers state the loss window in seconds for a given configuration. ### Atomicity comes in grades - **A single command** is always atomic. - **MULTI/EXEC** runs a queued batch without interleaving, but does not roll back a command that fails at runtime. - **WATCH** adds optimistic concurrency: the batch aborts if a watched key changed. - **Lua scripts and Functions** run logic that reads and writes atomically, at the price of blocking the server while they run. Pipelining sits outside this list: it saves network round trips and promises only ordering on one connection. ### The key decides the shard In Redis Cluster every key maps to one hash slot, and each slot to one primary. That single rule explains why multi-key commands need their keys in one slot, why hash tags exist, and why adding nodes does nothing for a single hot key. ### Two ways to deliver messages Pub/sub pushes to whoever is subscribed right now and keeps nothing. Streams are a stored, append-only log with IDs, consumer groups and acknowledgements. Most messaging questions ask you to pick between them, or to say when neither is enough.

TTL
Time to live: the remaining lifetime of a key with an expiry set. Some writes keep it and others clear it, depending on the command.
Sorted set
A collection of unique members, each carrying a numeric score, kept in score order so rank and range queries stay cheap.
Encoding
The internal representation Redis picks for a value. Small collections use compact encodings and convert to general-purpose structures once they pass configured size limits.
maxmemory
The configured memory ceiling for the dataset. When usage reaches it, the eviction policy decides whether keys are removed or writes are refused.
Eviction policy
The maxmemory-policy setting: which keys may be removed at the ceiling (all keys or only those with a TTL) and how the victim is chosen.
RDB snapshot
A compact point-in-time dump of the whole dataset, written by a forked child process. Fast to load, but loses writes made after it.
Append-only file (AOF)
A log of write commands that is replayed on restart. Its fsync policy sets how many recent writes a crash can lose.
Copy-on-write
The kernel mechanism a forked child uses to share the parent's memory. Pages the parent modifies during the fork are duplicated, so memory can grow.
Replica
A Redis instance that copies a primary's data and applies its write stream asynchronously. It can serve reads that lag the primary.
Hash slot
One of 16384 buckets a cluster divides the keyspace into. Each key hashes to one slot, and each slot belongs to one primary.
Hash tag
The part of a key inside curly braces that alone is hashed, letting related keys land in the same slot on purpose.
MULTI/EXEC
The commands that open and run a queued transaction. The queue executes without interleaving, but runtime errors in one command do not undo the others.
Stream
An append-only log of field-value entries with increasing IDs, readable by range, by blocking tail, or through consumer groups.
Consumer group
A named reader of a stream that splits entries among its consumers and tracks which delivered entries are still awaiting acknowledgement.
RESP
The Redis Serialization Protocol: typed, length-prefixed frames used between clients and servers. RESP3 adds richer types and server push.

Follow one command through the server. A client library encodes it in RESP and sends it over a long-lived connection. The event loop reads it, and the main thread looks up the key in the in-memory keyspace, checks whether it has already expired, and runs the operation against whatever structure the value holds. Once a write runs, it is also appended to the AOF buffer if persistence is on and to the replication stream for connected replicas; the reply waits for neither to reach disk or a replica. In a cluster the client has already hashed the key to a slot and picked the node that owns it; a redirect tells it the slot now lives elsewhere. The other sections hang off that path: - **Caching** is application code built from these commands, plus the choices that stop expiry turning into a load spike on the database. - **Eviction** runs when a write pushes memory past the ceiling, and background expiry samples keys with a TTL on a timer. - **Persistence and full resynchronisation** both fork a child process to dump the dataset as the parent goes on answering clients. - **Transactions and scripts** occupy the main thread for their whole duration, which is where atomicity and latency meet. - **Streams** are a data structure like any other, so they are persisted, replicated and sharded like one. Several of these dials live in one configuration, and they interact: ```bash redis-cli CONFIG SET maxmemory 6gb # leave host RAM for fork copy-on-write redis-cli CONFIG SET maxmemory-policy allkeys-lfu redis-cli CONFIG SET appendonly yes redis-cli CONFIG SET appendfsync everysec # bounded loss window, modest cost redis-cli CONFIG SET lazyfree-lazy-eviction yes # free evicted values off the main thread ``` A memory limit set close to physical RAM leaves no room for the copy-on-write growth of the next snapshot or log rewrite, and an eviction policy that ignores keys without a TTL can leave a cache refusing writes while it is full of keys it may not delete.

  1. Core Data Structures →

    The types and their costs are the vocabulary every other section uses; most junior questions start here.

  2. Event Loop & Threading →

    Single-threaded execution explains atomicity, blocking commands and latency spikes before you meet them elsewhere.

  3. Eviction & Expiration →

    How keys expire and what happens at the memory ceiling, which every caching answer assumes.

  4. Caching with Redis →

    The most common interview use of Redis: cache-aside, TTL choice, stampedes and hot keys.

  5. Persistence: RDB & AOF →

    What a crash can lose under each persistence setting, and what forking a large process costs.

  6. Replication & Cluster →

    Scaling past one node: asynchronous replicas, hash slots, cross-slot limits and failover.

  • Calling Redis single-threaded and stopping there: command execution is serial, but I/O and background freeing can use other threads, and one slow command still blocks everyone.

  • Running KEYS or deleting a huge collection with DEL on a production instance; see SCAN vs KEYS for the incremental alternative.

  • Treating an OK reply as durable: the write is in the primary's memory, and persistence and replication both happen after the reply.

  • Describing MULTI/EXEC as a relational transaction: there is no rollback, and a command that fails at runtime leaves the others applied.

  • Leaving the default eviction policy on a cache, or choosing a volatile-* policy when few keys carry a TTL, and then being surprised by OOM errors on writes.

  • Using pub/sub where messages must not be lost; subscribers that are disconnected simply miss them, which is what Streams exist to fix.

  • Proposing more cluster nodes as the cure for a hot key: one key lives in one slot on one primary, so the load has to be split or cached elsewhere.

  • Reading from replicas without saying the reads can be stale, including after a failover that promoted a replica missing recent writes.

This guide assumes Redis 7.2 or later, including the 8.x line. Several interview questions still turn on when a feature arrived, because older versions stay in production for years: - **4.0** added `UNLINK` and lazy freeing, LFU eviction policies, and the option of an RDB preamble inside the AOF. - **5.0** introduced Streams and consumer groups. - **6.0** added ACLs, the RESP3 protocol with client-side caching, threaded socket I/O, and the `KEEPTTL` option of `SET`. - **7.0** added Redis Functions, sharded pub/sub for clusters, and an AOF split into a base file plus incremental files. - **7.4** added per-field expiry on hashes, and was the first release under source-available licences rather than BSD. - **8.0** folded features previously shipped as separate modules, such as JSON and search, into the main distribution, and added AGPLv3 as a licence option. When an answer depends on one of these, such as whether a hash field can expire or how the AOF is laid out on disk, say which version you are describing.

Interviewers expect you to place Redis, not only to use it. As a cache it is most often weighed against Memcached, which is a simpler multithreaded key-value cache with no rich data types, persistence or replication; Redis wins when the structure of the data matters, Memcached when plain strings and vertical CPU scaling are enough. Valkey is a fork of Redis created after the 2024 licence change, maintained under the Linux Foundation and largely compatible at the command level; several managed cloud offerings now run it. For messaging, Redis streams and pub/sub compete with Apache Kafka and RabbitMQ. Redis fits small, latency-sensitive workloads on infrastructure the team already runs; a dedicated broker fits long retention, high throughput or guarantees that must survive multi-node failures. [Streams vs Pub/Sub vs Message Log](/topics/db-redis-streams-vs-pubsub) covers that comparison. Client libraries such as Jedis, Lettuce, redis-py and ioredis differ in how they handle pipelining, cluster redirects and pooling. High availability without sharding usually means Redis Sentinel; sharding means Redis Cluster or a proxy in front of independent instances.

explore

report an issue with this guide →

questions

206 · 8 sections

Running OBJECT ENCODING on a small Redis hash returns "listpack", and on a large one it returns "hashtable". What is that command reporting, and why does Redis keep more than one internal representation for the same data type?

level: juniorimportance: must knowfreq 50%
basics
~20 s

OBJECT ENCODING reports the internal memory layout Redis chose for that value. Small collections use a compact, cache-friendly flat array (listpack/intset) that saves a lot of memory; once they grow past configured thresholds Redis switches to a real hash table or skiplist for O(1)/O(log n) access.

open as a page

How would you store a user profile in a Redis hash, and which commands read a single attribute, several attributes, and the whole object? What happens to the key when you delete its last field?

level: juniorimportance: must knowfreq 68%
basics
~20 s

HSET user:42 name Ada email [email protected] writes fields; HGET reads one, HMGET reads several in one call, HGETALL returns every field and value. HDEL removes fields, and when the last field goes the key itself is deleted — Redis has no empty hashes.

open as a page

Describe the Redis List type: which commands you use to add and remove elements, how you read a range out of it, and how the cost of those operations differs between the ends of the list and the middle.

level: juniorimportance: must knowfreq 70%
basics
~20 s

An ordered sequence of strings with fast ends. LPUSH/RPUSH add at head/tail, LPOP/RPOP remove there, all O(1). LRANGE reads a slice; LINDEX/LSET/LINSERT/LREM touch the middle and are O(N) because Redis walks the list. Duplicates are allowed, order is insertion order, and an emptied list key is deleted.

open as a page

What is a Redis Set, and which commands do you use to add a member, remove one, test membership and get the element count?

level: juniorimportance: must knowfreq 72%
basics
~20 s

A Set is an unordered collection of unique strings. SADD adds (duplicates are silently ignored), SREM removes, SISMEMBER tests membership, SCARD returns the size, SMEMBERS returns everything. Add, remove, membership test and count are all O(1).

open as a page

What is a Redis Sorted Set, how is the ordering of its elements defined, and which commands do you use to add an element, read its score, read its rank and read a range?

level: juniorimportance: must knowfreq 74%
basics
~20 s

A Sorted Set holds unique string members, each with a floating-point score, kept ordered by score ascending and by member bytes when scores tie. ZADD adds or updates, ZSCORE reads a score, ZRANK gives the 0-based position, ZRANGE reads a slice, ZCARD counts.

open as a page

Walk through the read path of a cache-aside (lazy-loading) cache built on Redis: which commands run on a hit, which run on a miss, and what exactly gets written back?

level: juniorimportance: must knowfreq 75%
basics
~20 s

Read with GET. Hit: return the cached value. Miss (nil): load from the system of record, serialize it, write it back with a single SET key value EX <ttl>, and return it. Readers fill the cache lazily; a miss is normal, not an error.

open as a page

A record that your service caches in Redis is updated by the write path. Should the write path delete the cache key, overwrite it with a fresh TTL, or overwrite it while keeping the key's remaining time-to-live? Explain how each choice changes the worst-case staleness a reader can see.

level: juniorimportance: must knowfreq 58%
basics
~20 s

Deleting is the safest default: the next reader reloads from the database. Overwriting with a fresh TTL restarts the clock, so a hot key's expiry never fires and a wrong value can live forever. Overwriting while keeping the remaining TTL keeps a hard age bound.

open as a page

When your application updates a record that is also cached in Redis, do you delete the cached entry or overwrite it with the new value — and in which order relative to the database write?

level: middleimportance: must knowfreq 64%
basics
~20 s

Delete the cached key rather than overwriting it, and delete only after the database transaction commits. Deletion is idempotent, so racing writers cannot leave a wrong value stuck until the TTL expires. The cost is one extra miss.

open as a page

In a Redis-backed cache, what is a "hot key", and why can a single popular key become a bottleneck even though a Redis node handles hundreds of thousands of operations per second?

level: middleimportance: must knowfreq 55%
basics
~20 s

A hot key is one key taking a hugely disproportionate share of traffic. Because a key's name determines exactly one shard, and that shard executes commands on one thread, the load cannot be spread by adding nodes — one key saturates one CPU core and one network link.

open as a page

What is a cache stampede (thundering herd) in a Redis-backed cache, and what exactly does the request flow look like in the moment a popular cached entry expires?

level: middleimportance: must knowfreq 60%
basics
~20 s

When a popular key expires, every concurrent request gets nil from GET and all of them recompute the same value against the database at once. The number of duplicate recomputes is roughly request rate times recompute latency, and the resulting slowdown makes the window longer.

open as a page

What does the Redis append-only file (AOF) actually record, and what does turning on 'appendonly yes' give you that keeping only periodic point-in-time snapshots does not?

level: juniorimportance: must knowfreq 60%
basics
~20 s

The AOF is a log of every write command that changed the dataset, appended after the command runs; recovery replays the commands. A snapshot only stores state as of the moment it was taken, so a crash loses everything since it — the AOF narrows that loss to a second or less.

open as a page

Redis offers both a `SAVE` and a `BGSAVE` command for writing a snapshot to disk. What is the difference between them, and why is one of them effectively forbidden on a production server?

level: juniorimportance: must knowfreq 55%
basics
~20 s

SAVE writes the snapshot on the main thread, so the server answers no commands until it finishes — unusable in production. BGSAVE forks a child that writes the snapshot while the parent keeps serving; only the brief fork itself pauses the server.

open as a page

Redis exposes three values for the appendfsync setting: always, everysec and no. What does each one do, and how much data does each risk losing when the process or the machine crashes?

level: middleimportance: must knowfreq 66%
basics
~20 s

always fsyncs before replying, so an acknowledged write survives a crash, at a big throughput cost. everysec (the default) fsyncs once per second in a background thread, risking about a second of writes. no never fsyncs — the OS flushes when it likes, so a machine crash can lose tens of seconds.

open as a page

Redis can be configured to append every write command to an append-only file (AOF). What does the BGREWRITEAOF command do, and why does an append-only log need rewriting at all?

level: middleimportance: must knowfreq 58%
basics
~20 s

The AOF records every write, so it grows with write volume and repeats history. BGREWRITEAOF forks a child that writes a new minimal file reproducing the current in-memory dataset, then atomically swaps it in: smaller file, faster restart.

open as a page

Redis has a configuration directive called `aof-use-rdb-preamble`. What does enabling it change about the append-only file Redis writes and reads, and what do you gain from it?

level: middleimportance: must knowfreq 45%
basics
~20 s

With it on, a rewritten append-only file starts with the whole dataset in compact binary snapshot format, then appends later write commands as normal text. One file, snapshot body plus command tail. You gain much faster loading and a smaller file; durability is unchanged.

open as a page

Redis offers both XRANGE and XREAD for getting entries out of a stream. When would you reach for each?

level: juniorimportance: must knowfreq 50%
basics
~20 s

XRANGE is a history query: give it a start and end ID and it returns that slice in order, always immediately. XREAD is a consumer: you give it the last ID you saw and it returns only newer entries, and with BLOCK it waits for entries that have not arrived yet.

open as a page

In Redis, what delivery guarantee does a message sent with the PUBLISH command carry, and what happens to messages published while a subscriber's connection is down?

level: middleimportance: must knowfreq 62%
basics
~20 s

Fire-and-forget, at-most-once. PUBLISH hands the message only to clients subscribed at that instant and stores nothing. A subscriber that is disconnected, still reconnecting, or killed for a full output buffer misses those messages permanently: no replay, no offsets, no acknowledgement.

open as a page

When you append to a Redis Stream with XADD and pass * as the ID, what ID does Redis generate, and how is that identifier structured?

level: middleimportance: must knowfreq 55%
basics
~20 s

Redis generates an ID of the form milliseconds-sequence, e.g. 1699999999999-0. The first part is the server's Unix time in milliseconds, the second a counter that increments for additional entries within the same millisecond. IDs are strictly increasing, so XADD rejects any ID not greater than the stream's last one.

open as a page

Several worker processes need to share the entries of one Redis Stream so that each entry is initially handed to only one worker. How do you set that up with XGROUP CREATE and XREADGROUP, and what does the special ID `>` mean in XREADGROUP?

level: middleimportance: must knowfreq 55%
basics
~20 s

Create the group once: XGROUP CREATE key group $ (use 0 to replay history, MKSTREAM if the stream may not exist). Each worker reads with XREADGROUP GROUP group consumer-name STREAMS key >. The > means entries never yet delivered to anyone in this group, so Redis gives each new entry to one consumer only.

open as a page

After a worker receives an entry from a Redis Stream via XREADGROUP, what state does the server keep about that entry until XACK is called, and how do you inspect it?

level: middleimportance: must knowfreq 50%
basics
~20 s

The entry goes into the group's Pending Entries List (PEL): entry ID, owning consumer, last delivery time and delivery count. XACK key group id removes it from the PEL. Inspect with XPENDING (summary) or XPENDING key group IDLE ms start end count (per-entry detail).

open as a page

In Redis Cluster, how does the system decide which node stores a given key? Walk through the computation from the key string to the node that serves it.

level: juniorimportance: must knowfreq 62%
basics
~20 s

Redis Cluster computes CRC16 of the key modulo 16384, giving a hash slot. Each of the 16384 slots is owned by exactly one master node, so the slot decides the node. Keys are never hashed against node addresses.

open as a page

What does the Redis REPLICAOF command do to the instance it is run on, what can that instance still serve, and how do you detach it again?

level: juniorimportance: must knowfreq 50%
basics
~20 s

REPLICAOF host port makes the instance a replica: it discards its own dataset, copies the primary's, and then applies the primary's write stream. It serves reads but rejects writes (replica-read-only is on by default). REPLICAOF NO ONE detaches it into an independent primary, keeping the data it has.

open as a page

In Redis Cluster, how do the nodes decide that a primary is actually down rather than just slow, and what does the `cluster-node-timeout` setting control in that process?

level: middleimportance: must knowfreq 55%
basics
~20 s

Nodes ping each other over the cluster bus and gossip what they see. A node unreachable for longer than cluster-node-timeout is flagged PFAIL (possibly failed); once a majority of primaries report PFAIL for it, one marks it FAIL and broadcasts that, which triggers replica election.

open as a page

What does wrapping part of a Redis key in curly braces, as in user:{1000}:profile, do to where the key is placed in a Redis Cluster, and when would you deliberately use that?

level: middleimportance: must knowfreq 55%
basics
~20 s

Curly braces form a hash tag: Redis hashes only the substring inside the first {...} instead of the whole key. Keys sharing a tag share a slot and therefore a node, which is how you co-locate keys that must be read or written together.

open as a page

An MGET over three keys that worked against a single Redis instance now fails with "CROSSSLOT Keys in request don't hash to the same slot" after a move to Redis Cluster. Explain the rule being enforced and the realistic ways to make that read work.

level: middleimportance: must knowfreq 58%
basics
~20 s

In cluster mode every key of a single command must live in one hash slot, because one node executes it locally with no cross-node coordination. Fix it by hash-tagging the keys into one slot, by issuing separate GETs pipelined per node, or by restructuring the data into one key.

open as a page

A service writes 10,000 keys to Redis by issuing 10,000 separate SET commands in a loop, and the loop takes seconds even though Redis reports each command as sub-millisecond. Explain what Redis pipelining is and how it changes this picture.

level: juniorimportance: must knowfreq 62%
basics
~20 s

The cost is 10,000 network round trips, not Redis work. Pipelining means writing many commands to the socket without waiting for each reply, then reading the replies in order. Same server work, far fewer round trips, often 5-50x faster.

open as a page

When you run a Lua script on Redis with EVAL, you pass a key count followed by keys and then other arguments, which the script sees as KEYS and ARGV. Why does Redis insist that key names be declared separately instead of just hardcoding them in the script body?

level: juniorimportance: must knowfreq 52%
basics
~20 s

Redis needs to know which keys a script touches before running it, so it can route the command to the right cluster node, enforce ACL key permissions and cross-slot rules. Keys go in KEYS via the numkeys count; everything else goes in ARGV.

open as a page

Walk through what Redis does with the commands a client sends between MULTI and EXEC, what EXEC returns, and what DISCARD is for.

level: juniorimportance: must knowfreq 55%
basics
~20 s

MULTI puts the connection in transaction mode; each following command is only queued and answers +QUEUED, not executed. EXEC runs the whole queue in order with no other client's commands interleaved, returning an array of replies, one per queued command. DISCARD throws the queue away and leaves transaction mode.

open as a page

While one Redis client is sending a batch of commands in a single pipeline, can another client's commands execute in between them? State precisely what guarantees pipelining does and does not give.

level: middleimportance: must knowfreq 52%
basics
~20 s

Yes, other clients can run in between. A pipeline only guarantees that your commands execute in the order you sent them on that connection, and that replies come back in that order. It gives no atomicity, no isolation, and no all-or-nothing behaviour on failure.

open as a page

Redis 7.0 introduced Redis Functions alongside the older EVAL/EVALSHA Lua scripting. What is a Redis Function library, and how does it differ from a script executed with EVAL?

level: middleimportance: must knowfreq 45%
basics
~20 s

A Function library is named Lua code loaded once with FUNCTION LOAD and stored in the dataset itself — persisted to RDB/AOF, replicated, surviving restart. You invoke it by name with FCALL. EVAL scripts are anonymous, cached only, and identified by SHA1.

open as a page

A Redis key was written with a 60-second time-to-live and 60 seconds have passed. Is the key removed from memory at that exact moment? What can a client still observe about it afterwards?

level: juniorimportance: must knowfreq 58%
basics
~20 s

No. Redis frees an expired key only when a command touches it (lazy delete) or when a background sampling cycle picks it. Reads never return an expired value, but the memory can stay allocated for a while.

open as a page

What do the Redis commands `TTL` and `PTTL` return for a key that exists but has no expiry, versus a key that does not exist at all — and how do you remove an expiry without deleting the key?

level: juniorimportance: must knowfreq 58%
basics
~20 s

TTL returns the remaining seconds, -1 if the key exists with no expiry, and -2 if the key does not exist. PTTL is the same in milliseconds. PERSIST key removes the expiry and keeps the value, returning 1 if an expiry was removed, 0 otherwise.

open as a page

Redis's allkeys-lru eviction policy is documented as an *approximated* LRU. When Redis needs to free memory, how does it actually pick a victim key, and what does the maxmemory-samples setting control?

level: middleimportance: must knowfreq 52%
basics
~20 s

Redis keeps no global LRU list. When memory exceeds maxmemory it picks maxmemory-samples random keys (default 5), reads the last-access timestamp stored in each key's object header, and evicts the idlest. More samples means better accuracy and more CPU.

open as a page

Redis can publish an event whenever a key changes, but the feature ships disabled. How do you turn Redis keyspace notifications on, and what do the individual flag characters in the notify-keyspace-events configuration value mean?

level: middleimportance: must knowfreq 40%
basics
~20 s

Set notify-keyspace-events to a string of flags; empty means off. You must include K (keyspace channels) and/or E (keyevent channels) plus at least one event class such as g generic, $ string, l list, x expired, e evicted, or A for all classes. Example: Ex.

open as a page

Besides deleting a key when it is next accessed, Redis runs a background cycle over keys that carry a time-to-live. Walk through how that cycle decides how much work to do, and why its guarantee is probabilistic rather than exact.

level: middleimportance: must knowfreq 52%
basics
~20 s

It repeatedly samples about 20 random keys from the table of keys with a TTL, deletes the expired ones, and loops again if more than 25% of the sample was expired. Time-boxed per run, so it bounds stale keys statistically, not exactly.

open as a page

Redis is commonly described as "single-threaded". What exactly is single-threaded about a redis-server process, and what does that design buy and cost you?

level: juniorimportance: must knowfreq 78%
basics
~20 s

Command execution is single-threaded: one command at a time runs on the main event loop, so every command is atomic and no locks are needed. The cost is that one slow command stalls all clients, and one instance uses about one CPU core.

open as a page

In Redis, what actually happens when you run the KEYS command with a glob pattern against a production database with millions of keys, and what should you use instead?

level: juniorimportance: must knowfreq 70%
basics
~20 s

KEYS visits every key in the database in a single command, O(N), and Redis executes commands one at a time — so every other client waits until it finishes, potentially seconds. Use SCAN, which iterates the same keyspace in small cursor-based batches.

open as a page

Redis has a SLOWLOG facility. What exactly does it record, how do you configure and read it, and what part of a request's total time does it NOT include?

level: middleimportance: must knowfreq 60%
basics
~20 s

SLOWLOG stores the last N commands whose execution exceeded slowlog-log-slower-than microseconds. Read with SLOWLOG GET/LEN, clear with SLOWLOG RESET. It times only command execution inside the server — not network transfer, not time spent waiting in the queue behind other commands.

open as a page

Redis clients talk to the server using the REdis Serialization Protocol (RESP). Describe how a command and its reply are framed on the wire, and name the basic RESP2 data types with their prefix bytes.

level: middleimportance: must knowfreq 45%
basics
~20 s

A client sends every command as a RESP array of bulk strings; the server replies with one typed frame. RESP2 has five types identified by a first byte: + simple string, - error, : integer, $ bulk string (length-prefixed, binary safe), * array. Every frame ends with CRLF.

open as a page