PrepStack › Databases › Redis & Caching

Redis & Caching interview cheat sheet

Data structures, TTL & eviction, persistence, scaling, caching patterns and locks

Redis questions come in two layers. First, Redis itself: why it is fast, which data structure fits which problem, expiry and eviction, persistence, replication and Cluster. Second, caching as a design skill: cache-aside vs write-through, invalidation, stampedes, distributed locks and rate limiting. Read the 15-minute revision first, then use Quiz mode and answer out loud. The redis-cli examples are illustrative; the JS and Python snippets are runnable models of the same ideas.

15-minute revision

  1. Redis is an in-memory key-value data-structure server. It is fast because data lives in RAM, structures are compact, and commands run one at a time on one main thread over an event loop (epoll/kqueue). No locks are needed.
  2. Since Redis 6, optional I/O threads (io-threads) read and write sockets in parallel, but command execution stays single-threaded, so every command is atomic.
  3. Core types: string (counters, cache blobs), hash (objects), list (queues), set (unique members), sorted set (leaderboards, time indexes), plus bitmap, HyperLogLog, geo and stream.
  4. Redis 8 ships JSON, time series, probabilistic types (Bloom, Cuckoo, Top-K…), the Query Engine and the new vector set in core, previously Redis Stack modules.
  5. Expiry: SET k v EX 60 or EXPIRE. Keys are removed lazily (checked on access) and actively (a background cycle samples keys with a TTL). TTL returns -1 for no expiry and -2 for a missing key.
  6. maxmemory + maxmemory-policy. Default policy is noeviction (writes fail when full). For a pure cache use allkeys-lru or allkeys-lfu. volatile-* only evicts keys that have a TTL. LRU/LFU are approximated by sampling.
  7. Persistence: RDB = point-in-time snapshots via fork (compact, fast restart, may lose minutes). AOF = log of writes with appendfsync everysec (lose about 1 s). Use both for safety.
  8. Replication is asynchronous primary → replicas (full sync by RDB, then a command stream; PSYNC resumes from a backlog). WAIT reduces but does not remove the chance of losing acknowledged writes.
  9. Sentinel = HA for one primary (monitoring + automatic failover), no sharding. Cluster = sharding over 16384 hash slots (CRC16(key) mod 16384) plus failover. Use {hash tags} to keep related keys together.
  10. Pipelining saves round trips but is not atomic. MULTI/EXEC queues commands and runs them together without rollback; WATCH adds optimistic locking. Lua scripts / Functions run atomically with logic.
  11. Pub/Sub is fire-and-forget (offline subscribers miss messages). Streams are a persisted log with consumer groups, acknowledgements and replay.
  12. Caching patterns: cache-aside (app reads cache, on miss loads DB and fills cache) is the default. Others: read-through, write-through, write-behind and refresh-ahead.
  13. On update, write the DB then delete the cache key (don't update it). Always set a TTL as a safety net for missed invalidations.
  14. Stampede (hot key expires) → single-flight lock or early refresh. Penetration (keys that don't exist) → negative caching or a Bloom filter. Avalanche (many keys expire at once) → TTL jitter.
  15. Lock: SET lock:x <random> NX PX 30000; release with a Lua compare-and-delete. Redlock is debated: for correctness you need fencing tokens; locks with TTLs are safe for efficiency, not always for correctness.
  16. Redis 7.4 moved to source-available licences (RSALv2/SSPLv1), which led to the Linux Foundation fork Valkey (BSD, from 7.2.4). Redis 8 added AGPLv3 as an open-source option.

Foundations

What Redis is & why it is fast

An in-memory data-structure server that runs commands one at a time on an event loop, so each command is atomic and very fast.

  • Redis (REmote DIctionary Server) keeps the whole dataset in RAM and serves it over TCP using the simple RESP protocol (RESP3 since Redis 6).
  • Values are data structures, not just blobs. You send operations like INCR, LPUSH or ZADD, and the server does the work next to the data.
  • Single-threaded command execution: one main thread runs an event loop over epoll (Linux) or kqueue (macOS/BSD). It never waits on a slow socket, so one thread can serve many thousands of clients.
  • No locks or context switches are needed, and each command is atomic. The bottleneck is usually network or memory, not CPU.
  • Since Redis 6, io-threads lets extra threads do socket reads/writes and protocol parsing. Background threads also handle UNLINK, lazy freeing and fsync.
  • The flip side: one slow command (KEYS *, a huge SMEMBERS, a long Lua script) blocks every other client. Scale CPU with more shards, not more threads.

Interview questions

  • Why is Redis so fast even though it is single-threaded?
  • Is Redis really single-threaded?
  • What happens if one client runs a slow command?
  • When would you not use Redis as a primary database?

Core data structures & use cases

Pick the structure that matches the access pattern: strings for blobs and counters, hashes for objects, lists for queues, sets for uniqueness, sorted sets for ranking.

  • String: binary-safe, up to 512 MB. Cache JSON, counters (INCR, INCRBY), flags, and simple locks (SET NX).
  • Hash: a map of fields to values inside one key. Good for objects (HSET user:1 name Asha plan pro). Since Redis 7.4 you can set a TTL per field (HEXPIRE).
  • List: ordered, push/pop at both ends in O(1). Queues and recent-items feeds (LPUSH + LTRIM). BLPOP/BLMOVE block until an item arrives.
  • Set: unordered unique members with O(1) add/check. Tags, unique visitors, friends; SINTER/SUNION/SDIFF for set maths.
  • Sorted set (ZSET): unique members ordered by a float score. Leaderboards, priority queues, time-ordered indexes, sliding-window rate limits.
  • Small collections use a compact listpack (or intset for small integer sets) and switch to a hash table or skiplist when they grow past configured limits.

Interview questions

  • Which Redis data structure would you use for a leaderboard and why?
  • Hash vs a JSON string for storing an object?
  • How would you implement a queue in Redis?
  • How is a sorted set implemented?

Bitmaps, HyperLogLog, geo, streams & Redis 8 types

Specialised types answer specific questions cheaply: yes/no per ID, approximate unique counts, nearby places, event logs, JSON documents and vector similarity.

  • Bitmap: string operations on bits. SETBIT active:2026-12-02 <userId> 1, then BITCOUNT for daily actives and BITOP AND across days. 1 bit per user ID.
  • HyperLogLog: approximate distinct count using at most 12 KB per key with about 0.81% standard error. PFADD, PFCOUNT, PFMERGE. You cannot list the members.
  • Geo: longitude/latitude stored as a geohash score inside a sorted set. GEOADD, GEODIST, GEOSEARCH ... BYRADIUS.
  • Stream: append-only log with IDs like 1733140000000-0. XADD, XRANGE, consumer groups with XREADGROUP/XACK. (Covered in the messaging section.)
  • Redis 8 includes in core: JSON (JSON.SET/JSON.GET with paths), time series, probabilistic types (Bloom, Cuckoo, Count-Min, Top-K, t-digest), the Query Engine (FT.CREATE/FT.SEARCH incl. vector search) and vector sets (VADD/VSIM).
  • Before Redis 8 these lived in modules / Redis Stack (RedisJSON, RediSearch, RedisBloom, RedisTimeSeries).

Interview questions

  • How do you count unique visitors per page for millions of pages cheaply?
  • What is a Bloom filter and when does Redis use it?
  • What changed for data types in Redis 8?

Memory: TTL, eviction & persistence

Key expiry (TTL): lazy + active

A TTL marks when a key should die; Redis deletes it lazily when touched and actively with a background sampling cycle.

  • Set expiry with SET k v EX 60 / PX 60000, EXPIRE, PEXPIRE, EXPIREAT. Since Redis 7, EXPIRE takes NX | XX | GT | LT conditions.
  • TTL k returns seconds left, -1 if the key has no expiry, -2 if the key does not exist. PERSIST removes the TTL.
  • Overwriting a key with SET clears its TTL (unless KEEPTTL). Changing it in place (INCR, LPUSH, HSET) keeps the TTL.
  • Lazy (passive) expiry: when a command touches a key, Redis checks its expiry time and deletes it if it has passed.
  • Active expiry: about hz (default 10) times per second Redis samples keys from the set that has a TTL and deletes expired ones. If many in the sample were expired, it repeats, within a CPU-time budget.
  • Replicas do not expire keys on their own; the primary sends a DEL. A replica does hide logically expired keys from reads.

Interview questions

  • How does Redis delete expired keys?
  • What do TTL return values -1 and -2 mean?
  • Does SET on an existing key keep its TTL?
  • Can you expire a single field of a hash?

maxmemory & eviction policies

When memory hits maxmemory, Redis either rejects writes (noeviction) or evicts keys using LRU, LFU, random or shortest-TTL among all keys or only keys with a TTL.

  • maxmemory 2gb sets the limit; 0 means no limit (the 64-bit default). maxmemory-policy picks what happens at the limit; the default is noeviction.
  • allkeys-* policies consider every key; volatile-* policies only keys with a TTL. If no key has a TTL, volatile-* behaves like noeviction.
  • LRU evicts the least recently used; LFU (Redis 4+) evicts the least frequently used, with a decaying counter. LRM (Redis 8.6+) is like LRU but only writes count as use.
  • Both are approximated: Redis samples maxmemory-samples keys (default 5) and evicts the best candidate from a pool. Raising it to 10 is closer to true LRU at more CPU cost.
  • Eviction happens when a write command needs memory. Leave headroom for replication and AOF buffers, which are not counted against maxmemory.
  • Watch evicted_keys, expired_keys, keyspace_hits / keyspace_misses in INFO stats.

Interview questions

  • What is the difference between allkeys-lru and volatile-lru?
  • LRU vs LFU: when is LFU better?
  • Does Redis implement exact LRU?
  • What happens when Redis reaches maxmemory with noeviction?

Persistence: RDB vs AOF vs both

RDB takes compact point-in-time snapshots; AOF logs every write; combined they give fast restarts with at most about a second of loss.

  • RDB: BGSAVE forks a child that writes a binary snapshot (dump.rdb) while the parent keeps serving. Triggered by save <seconds> <changes> rules, BGSAVE, or replication.
  • AOF: every write command is appended to a log. appendfsync always (safest, slowest), everysec (default, lose up to about 1 s), or no (the OS decides, often around 30 s).
  • AOF grows, so Redis rewrites it in the background (BGREWRITEAOF, auto via auto-aof-rewrite-percentage). Since Redis 7 the AOF is multi-part: a base file, incremental files and a manifest.
  • With aof-use-rdb-preamble yes (default) the AOF base is in RDB format, so loading is fast and the tail is replayed as commands.
  • If both are enabled, Redis loads from the AOF on restart because it is more complete.
  • Pure cache? You can disable both (save "", appendonly no) and rebuild from the source of truth.

Interview questions

  • Difference between RDB and AOF?
  • What are the appendfsync options and their trade-offs?
  • How does BGSAVE not block Redis?
  • Is Redis with AOF always as durable as PostgreSQL?

Replication, HA & scaling

Replication

Replicas copy a primary asynchronously: a full RDB sync first, then a live stream of write commands, with partial resync after short disconnects.

  • Configure with REPLICAOF host port. Replicas are read-only by default and can serve reads to scale read traffic.
  • First sync: the primary makes an RDB (to disk or repl-diskless-sync straight to the socket), sends it, then streams buffered and new writes.
  • Each primary has a replication ID and offset. After a short disconnect a replica sends PSYNC <replid> <offset>; if the gap is still in the replication backlog (repl-backlog-size) only the missing part is sent.
  • Replication is asynchronous: the primary replies to the client before replicas confirm. WAIT numreplicas timeout blocks until N replicas acknowledged, reducing (not removing) loss on failover.
  • Reads from replicas can be stale (replication lag). Use the primary for read-your-own-writes.
  • Running a primary without persistence and with auto-restart is dangerous: it restarts empty and replicas sync the empty dataset.

Interview questions

  • Is Redis replication synchronous or asynchronous?
  • What is the difference between full and partial resynchronization?
  • Why could reading from a replica return old data?

Sentinel vs Cluster (16384 hash slots)

Sentinel gives automatic failover for one primary; Cluster shards keys over 16384 hash slots across many primaries and also fails over.

  • Sentinel: separate processes (run at least 3) watch the primary. When a quorum agrees it is down, one Sentinel is elected to promote a replica, and clients ask Sentinel for the current primary address.
  • Cluster: data is split into 16384 hash slots; slot = CRC16(key) mod 16384. Each primary owns a range of slots and has replicas. Nodes talk over a gossip cluster bus and fail over automatically.
  • Hash tags: only the part inside {…} is hashed, so user:{42}:cart and user:{42}:profile land in the same slot and can be used together.
  • Multi-key commands, transactions and Lua scripts work only when all keys are in the same slot; otherwise you get CROSSSLOT.
  • A client hitting the wrong node gets MOVED (slot moved permanently; update the slot map) or ASK (slot migrating; ask the other node once). Smart clients cache the slot map.
  • Cluster supports only database 0 and needs cluster-aware clients. Resharding moves slots live with redis-cli --cluster reshard.

Interview questions

  • Sentinel vs Cluster: which would you choose?
  • Why 16384 hash slots?
  • What are MOVED and ASK redirects?
  • How do you run a multi-key operation in Redis Cluster?
  • How does Sentinel decide to fail over?

Atomicity & messaging

Pipelining vs MULTI/EXEC vs WATCH

Pipelining cuts network round trips; MULTI/EXEC runs a batch without interleaving; WATCH makes it a check-and-set.

  • Pipelining: the client sends many commands without waiting for each reply, then reads all replies. One RTT instead of N. Not atomic; other clients' commands can run in between.
  • MULTI … EXEC: commands are queued and then executed in order with no other client in between. EXEC returns an array of results.
  • No rollback: if a command fails at runtime (wrong type), the others still run. A syntax error while queuing makes EXEC abort the whole transaction.
  • You cannot read a value inside MULTI and use it in a later command in the same transaction; replies arrive only at EXEC.
  • WATCH key: optimistic locking. If a watched key changes before EXEC, EXEC returns nil and nothing runs; the client retries.
  • Clients often send MULTI/EXEC through a pipeline to get both atomicity and one round trip.

Interview questions

  • Difference between pipelining and a transaction?
  • Does Redis support rollback?
  • How does WATCH work?
  • Why can't I use a GET result inside the same MULTI?

Lua scripts & Redis Functions

Scripts run server-side and atomically, so read-decide-write logic needs no locks or retries; Functions (Redis 7) are named, persisted scripts.

  • EVAL script numkeys key… arg… runs Lua on the server. The whole script is atomic: no other command runs until it finishes.
  • Pass every key through KEYS[] and values through ARGV[]. Cluster routing and ACLs depend on declared keys.
  • SCRIPT LOAD + EVALSHA <sha1> avoids resending the script; handle NOSCRIPT by falling back to EVAL.
  • Functions (Redis 7+): FUNCTION LOAD a library with redis.register_function, call with FCALL name numkeys …. They are persisted and replicated like data, unlike the script cache.
  • A long script blocks the server. After busy-reply-threshold (default 5 s) other clients get BUSY; SCRIPT KILL works only if the script has not written yet.
  • Scripts should be deterministic: same inputs → same writes, because effects are replicated.

Interview questions

  • Why use a Lua script instead of MULTI/EXEC?
  • EVAL vs Redis Functions?
  • What happens if a Lua script runs for too long?

Pub/Sub vs Streams

Pub/Sub pushes messages to whoever is listening right now; Streams store messages in a log so consumer groups can read, acknowledge and replay them.

  • Pub/Sub: PUBLISH channel msg, SUBSCRIBE / PSUBSCRIBE (patterns). At-most-once: nothing is stored; offline or slow subscribers miss messages.
  • Redis 7 added sharded pub/sub (SSUBSCRIBE, SPUBLISH) so messages in Cluster only go to the shard owning the channel's slot instead of every node.
  • Streams: XADD appends entries with time-based IDs. XRANGE/XREAD read by ID; MAXLEN/MINID trims.
  • Consumer groups: XGROUP CREATE, XREADGROUP gives each entry to one consumer; it stays in the Pending Entries List until XACK. XAUTOCLAIM reassigns stuck messages.
  • Streams give at-least-once delivery, so consumers must be idempotent.
  • Use Kafka or similar when you need long retention on disk, very high throughput or huge fan-out history; Streams are great for moderate, in-memory event flows.

Interview questions

  • Pub/Sub vs Streams?
  • How do consumer groups handle a crashed consumer?
  • Redis Streams vs Kafka?

Caching patterns & problems

Caching strategies

Cache-aside is the default; read-through, write-through, write-behind and refresh-ahead move work into a cache layer in exchange for complexity or risk.

  • Cache-aside (lazy loading): the app checks the cache; on a miss it reads the DB and stores the result with a TTL. Simple, and the cache only holds data that is actually read.
  • Read-through: the app always asks the cache; the cache layer itself loads from the DB on a miss (a library or proxy, not Redis alone).
  • Write-through: every write goes to the cache and the DB synchronously. Cache stays fresh, but writes are slower and may cache data nobody reads.
  • Write-behind (write-back): write to the cache now, flush to the DB asynchronously in batches. Fast writes, but data is lost if the cache dies before flushing.
  • Refresh-ahead: refresh popular keys before they expire, so users never see the miss latency.
  • Measure hit ratio (keyspace_hits / (hits + misses)). A cache with a low hit ratio adds latency and cost.

Interview questions

  • Explain cache-aside.
  • Write-through vs write-behind?
  • What is refresh-ahead and when is it worth it?
  • How do you decide the TTL?

Cache invalidation & consistency

Write the DB first, then delete the cache key; add TTLs, and use delayed double delete, CDC or client-side tracking when races matter.

  • Delete, don't update: updating the cache on write races with concurrent writers and can leave the older value cached. Deleting lets the next read load fresh data.
  • DB first, then delete: deleting first lets a concurrent reader refill the cache with the old DB value before your DB write commits.
  • A rare race remains (reader loads old value, writer updates + deletes, reader then writes stale value). Mitigate with short TTLs or a delayed double delete (delete again after a few hundred ms).
  • For reliability, drive invalidation from the DB's change log (CDC, e.g. Debezium → consumer → DEL) or an outbox, so a crash between DB write and delete is retried.
  • Multiple app instances with local caches: broadcast invalidations via Pub/Sub, or use Redis 6+ client-side caching (CLIENT TRACKING), where Redis tells clients which keys changed.
  • Versioned keys (product:42:v17) or generation counters avoid deletes entirely: bump the version, old entries expire.

Interview questions

  • Should you update or delete the cache on a write? Why?
  • Why update the DB before deleting the cache?
  • How do you keep cache and DB consistent across many services?
  • What is Redis client-side caching?

Stampede, penetration & avalanche

Hot key expiry floods the DB (stampede), missing keys bypass the cache (penetration), mass expiry or cache outage hits everything at once (avalanche).

  • Cache stampede / thundering herd / dogpile: a hot key expires and thousands of requests miss at once and all hit the DB.
  • Stampede fixes: single-flight / mutex (only one request rebuilds, using SET lock NX PX; others wait or serve stale), refresh-ahead or probabilistic early expiration (refresh slightly before TTL with rising probability), and stale-while-revalidate (keep a soft TTL and a hard TTL).
  • Cache penetration: requests for keys that don't exist (often an attack: random IDs) always miss and go to the DB.
  • Penetration fixes: negative caching (store a "null" marker with a short TTL), a Bloom filter of valid IDs in front, and input validation / rate limiting.
  • Cache avalanche: many keys expire at the same moment (bulk loaded with the same TTL) or the cache cluster goes down.
  • Avalanche fixes: TTL jitter, warming the cache before traffic, HA (replicas, Sentinel/Cluster), circuit breakers and request limiting in front of the DB, and a local in-process cache layer.

Interview questions

  • What is a cache stampede and how do you prevent it?
  • What is cache penetration?
  • What is a cache avalanche?
  • How does probabilistic early expiration work?

Patterns in practice

Distributed locks & the Redlock debate

SET key token NX PX ttl plus a compare-and-delete release is a good lock for efficiency; for correctness you also need fencing tokens, because TTL-based locks can expire under a paused holder.

  • Acquire: SET lock:res <unique-token> NX PX 30000. NX = only if absent, PX = auto-expire so a crashed holder doesn't block forever. One atomic command.
  • Release: a Lua compare-and-delete (GET == my token → DEL). A plain DEL could remove a lock that expired and was taken by someone else.
  • Long jobs: extend the TTL periodically while still holding it (a "watchdog", as Redisson does), again with a token check.
  • Redlock: acquire the same lock on a majority (e.g. 3 of 5) of independent Redis primaries within a time limit; valid time = TTL − elapsed − clock drift.
  • Kleppmann's critique: a GC pause, page fault or network delay can outlast the TTL, so two clients may both think they hold the lock; Redlock also assumes bounded clock drift. The fix is a fencing token (increasing number) checked by the storage.
  • Rule of thumb: for efficiency (avoid duplicate work) a single-instance Redis lock is fine. For correctness (money, inventory), use fencing tokens or a consensus system (ZooKeeper, etcd) or DB constraints.

Interview questions

  • How do you implement a distributed lock with Redis?
  • Why must lock release check the token?
  • What is Redlock and why is it controversial?
  • What is a fencing token?

Rate limiting with Redis

Redis counters with TTLs give fixed windows, sorted sets give exact sliding windows, and a Lua script gives atomic token buckets shared by every app server.

  • Redis is a natural fit: it is shared by all app instances, fast, atomic per command, and TTLs clean up old counters.
  • Fixed window: INCR rl:<user>:<minute> + EXPIRE on first hit. Cheap, but allows up to 2× bursts at window edges.
  • Sliding log: a sorted set of request timestamps per user. ZREMRANGEBYSCORE old ones, ZCARD to count, ZADD the new one. Exact, but memory grows with the limit.
  • Sliding window counter: weight the previous window's count by overlap. Close to exact with two counters.
  • Token bucket: store tokens and last_refill in a hash; refill based on elapsed time, take one token per request. Allows controlled bursts. Must be a Lua script for atomicity.
  • Return 429 Too Many Requests with Retry-After and RateLimit-* headers.

Interview questions

  • How would you build a rate limiter shared by 20 API servers?
  • What is the problem with a fixed-window limiter?
  • Why must the token bucket be a Lua script?

Leaderboards, sessions & counters

Sorted sets make live leaderboards trivial, hashes with TTL make shared sessions easy, and INCR gives atomic counters.

  • Leaderboard: ZINCRBY board <points> <player>, ZRANGE board 0 9 REV WITHSCORES for the top 10, ZREVRANK for a player's rank, ZSCORE for points.
  • Ties are ordered by member name (lexicographically), so encode a tie-breaker (like time) into the score if order matters.
  • Time-boxed boards: one key per period (board:2026-w49) with a TTL; ZUNIONSTORE to combine periods.
  • Sessions: HSET session:<id> user 42 role admin + EXPIRE session:<id> 1800. Refresh the TTL on each request for a sliding expiry. Shared by every app instance, so no sticky sessions.
  • Counters: INCR/INCRBY/HINCRBY are atomic, so concurrent page views or likes never lose updates.
  • Session IDs must be long random values; store only what you need, and delete the key on logout.

Interview questions

  • Design a real-time game leaderboard.
  • Why store sessions in Redis instead of server memory?
  • How do you count page views accurately under heavy concurrency?

Hot keys, big keys & production tuning

A hot key overloads one shard and a big key blocks the thread and skews memory; find them with redis-cli tools and fix them by splitting, replicating or caching locally.

  • Big key: a value that is very large (multi-MB string, collections with millions of members). Reading, deleting, migrating or expiring it blocks the main thread and spikes network.
  • Find big keys: redis-cli --bigkeys (largest per type), redis-cli --memkeys, MEMORY USAGE key. Delete them with UNLINK (background free) or incrementally with HSCAN + HDEL.
  • Fix big keys by splitting (shard a hash into user:42:part:0..N), paging, or storing blobs in object storage with only a pointer in Redis.
  • Hot key: one key receives a huge share of traffic. In Cluster it lives on one shard, so that node's CPU or network saturates while others idle.
  • Find hot keys: redis-cli --hotkeys (requires an LFU policy), MONITOR briefly (expensive), client-side metrics, or proxy stats.
  • Fix hot keys: a local in-process cache with a short TTL, read replicas, or key replication (feed:home:{1..N}, pick one at random for reads).

Interview questions

  • What is a hot key and how do you handle it?
  • What is a big key and why is it a problem?
  • DEL vs UNLINK?
  • Your Redis latency suddenly spiked. How do you investigate?

Ecosystem & choices

Redis vs Memcached

Memcached is a simple, multi-threaded string cache; Redis is a data-structure server with persistence, replication, scripting and messaging.

  • Memcached: key → opaque bytes, multi-threaded, slab allocator, LRU eviction, no persistence, no built-in replication. Default max item size is 1 MB.
  • Redis: rich data types, TTL per key (and per hash field), persistence, replication, Sentinel/Cluster, transactions, Lua, Pub/Sub and Streams.
  • Memcached scales across cores in one process; Redis scales by running more shards (or with I/O threads).
  • Choose Memcached for a very simple, large, volatile object cache where multi-threaded throughput per node matters. Choose Redis for almost everything else.
  • Both are in-memory and both are usually put beside a database, not instead of it.

Interview questions

  • Redis vs Memcached: when would you pick each?

Licensing, Valkey & Redis 8

Redis left BSD in 2024 (7.4: RSALv2/SSPLv1), the community forked Valkey from 7.2.4, and Redis 8 (2025) added AGPLv3 as an open-source option.

  • Up to 7.2, Redis was BSD-3-Clause licensed.
  • In March 2024, starting with Redis 7.4, Redis Ltd moved to a dual source-available licence: RSALv2 or SSPLv1. Neither is OSI-approved open source; the aim was to stop cloud providers selling Redis as a service without contributing.
  • Days later, the Linux Foundation launched Valkey, a BSD-licensed fork of Redis 7.2.4, backed by AWS, Google Cloud, Oracle and others. Managed services such as ElastiCache and Memorystore now offer Valkey.
  • In May 2025, Redis 8 added AGPLv3 as a third licence option (RSALv2 / SSPLv1 / AGPLv3), making it OSI open source again. Redis 8 also merged Stack features (JSON, search, time series, probabilistic) into core and added vector sets.
  • Valkey stays wire-compatible with Redis 7.2 clients and has added its own features (for example improved multi-threaded I/O in Valkey 8). Feature sets diverge from Redis 7.4/8 onward.
  • Other compatible options: KeyDB (multi-threaded fork), Dragonfly (new multi-threaded engine, Redis-protocol compatible).

Interview questions

  • What happened with the Redis licence and why does Valkey exist?
  • Is Valkey a drop-in replacement for Redis?