Top 20 Cloud Caching, Redis & Memcached Interview Questions & Answers
Distributed in-memory caching is the single most effective architectural lever for scaling read-heavy cloud applications from thousands to millions of requests per second while protecting relational databases from saturation. In Cloud Infrastructure, Site Reliability Engineering (SRE), and System Design interviews, candidates are expected to compare Redis and Memcached at the threading and memory-allocator level, select the right caching write strategy, and mitigate production failure modes like cache stampedes, cache penetration, and hot-key hotspots.
Redis vs. Memcached: Architectural Comparison
Reviewing this side-by-side matrix ensures you can immediately contrast internal threading models, persistence, data structures, and scaling topologies:
| Architectural Dimension | Redis (Valkey / Redis 7+) | Memcached |
|---|---|---|
| Threading & Execution Model | Single-threaded main event loop (epoll/kqueue) for command execution + multi-threaded network I/O | Multi-threaded architecture (libevent) scaling linearly across CPU cores for simple key-value ops |
| Supported Data Structures | Rich native structures: Strings, Hashes, Lists, Sets, Sorted Sets (ZSET), Streams, Bitmaps, HyperLogLog | Opaque key-value byte blobs only (<= 1 MB default slab limit per item) |
| Memory Allocation | jemalloc dynamic allocator (minimizes fragmentation; supports active defragmentation) | Slab Allocator (pre-allocated memory pages split into fixed-size chunks; susceptible to slab calcification) |
| Persistence & Durability | RDB point-in-time snapshots + AOF (Append-Only File) write-ahead log | Purely volatile in-memory store (zero disk persistence) |
| High Availability & Clustering | Built-in Master-Replica replication, Redis Sentinel, and Redis Cluster (16,384 hash slots) | Shared-nothing nodes; clustering and consistent hashing handled entirely on the client side |
| Lua Scripting & Transactions | Atomic server-side Lua scripts (EVAL), Redis Functions, and MULTI/EXEC | Atomic Compare-And-Swap (CAS), INCR/DECR only |
| Best Production Fit | Rate limiters, leaderboards, distributed locks, session stores, pub/sub streams, durable caches | Ultra-high-throughput stateless HTML/object caching where simplicity and multi-core CPU scaling matter |
TEXT
+-----------------------------------------------------------------------------------+
| DISTRIBUTED CACHING PATTERNS: READ & WRITE TOPOLOGIES |
+-----------------------------------------------------------------------------------+
| |
| 1. CACHE-ASIDE (LAZY LOADING) - Most Common in Cloud Microservices |
| [App Service] --(1. GET user:42)--> [Redis / Memcached] |
| | | (Cache Miss) |
| +--(2. SELECT * FROM users)---> [Primary DB] |
| +--(3. SET user:42 EX 300)----> [Redis / Memcached] |
| |
| 2. WRITE-THROUGH - Strong Cache/DB Consistency, Higher Write Latency |
| [App Service] --(1. Write synchronously)--> [Cache] --(2. Sync Write)--> [DB] |
| |
| 3. WRITE-BEHIND (WRITE-BACK) - Ultra-Fast Writes, Risk of Data Loss on Crash |
| [App Service] --(1. Ack immediately)--> [Cache] ~~(2. Async Batch)~~~~> [DB] |
+-----------------------------------------------------------------------------------+
Part 1: Redis vs. Memcached Internals (Questions 1–7)
1. Why is Redis fast despite using a single-threaded main command loop?
- Answer: Redis is almost never CPU-bound; it is memory- and network-I/O-bound. Keeping command execution on a single thread eliminates lock contention, mutex overhead, and CPU context switching across data structures like Sorted Sets and Hashes. Combined with non-blocking multiplexed I/O (
epoll/kqueue), $O(1)$ hash-table lookups, and multi-threaded socket read/write I/O threads (introduced in Redis 6+), a single Redis core routinely handles 100,000+ operations per second at sub-millisecond latency.
2. When would you choose Memcached over Redis in a cloud architecture?
- Answer: Choose Memcached when you only need a pure, volatile key-value cache storing small, uniform objects (e.g., rendered HTML fragments or session blobs) and want vertical multi-core scaling on a single large instance without managing multiple Redis shards. Memcached's multi-threaded worker pool utilizes 16+ CPU cores on a single node seamlessly, whereas a single Redis process executes commands on one CPU core.
3. How does Memcached's Slab Allocator work, and what is "slab calcification"?
- Answer: To avoid
malloc/freememory fragmentation, Memcached divides memory into $1\text{ MB}$ pages and partitions each page into fixed-size chunks belonging to specific slab classes (e.g., $96\text{ B}$, $120\text{ B}$, $240\text{ B}$, growing by a factor of $1.25\times$). Slab calcification occurs when a workload initially fills memory with small objects (allocating most pages to the $128\text{ B}$ slab class) and later shifts to storing larger objects ($4\text{ KB}$)—causing premature evictions in the $4\text{ KB}$ class while free chunks sit idle in the $128\text{ B}$ class. Modern Memcached mitigates this via background slab page reassignment (slab_automove).
4. Compare Redis RDB snapshots and AOF (Append-Only File) persistence.
- Answer: RDB (Redis Database): Forks a child process (
copy-on-write) at configured intervals to serialize a compact binary point-in-time snapshot to disk. Fast restarts and minimal runtime overhead, but loses writes occurring since the last snapshot if the node crashes. AOF (Append-Only File): Logs every write mutation command (SET,HSET,ZADD) sequentially to disk. Configured withappendfsync everysec, it bounds maximum data loss to 1 second while avoiding per-commandfsyncstalls. Production Redis deployments typically enable hybrid RDB+AOF persistence (aof-use-rdb-preamble yes) for fast restarts and minimal data loss.
5. Why can KEYS * cause a production outage in Redis, and what should you use instead?
- Answer:
KEYS *performs a blocking $O(N)$ full scan of the entire keyspace inside Redis's single-threaded command loop. On a cache holding 50 million keys,KEYS *freezes all client reads and writes for several seconds—triggering cascading microservice timeouts and Sentinel failovers. Always useSCAN, which uses a stateless cursor to iterate incrementally in small batches (COUNT 100) without blocking the event loop.
6. How does Redis implement Sorted Sets (ZSET) internally to achieve $O(\log N)$ performance?
- Answer: A Redis
ZSETuses a dual data structure under the hood: A Hash Table mappingmember -> scorefor $O(1)$ score lookups (ZSCORE). A Skip List ordering(score, member)pairs across multi-level probabilistic forward pointers for $O(\log N)$ range queries (ZRANGE,ZREVRANK) without requiring complex tree rebalancing rotations.
7. What is Redis Pipelining, and how does it improve throughput?
- Answer: Normally, a client sends one command and waits for the server's reply before sending the next—paying one full network Round-Trip Time (RTT) per command. Pipelining batches dozens or hundreds of commands into a single TCP write buffer and reads all responses together, eliminating per-command RTT latency and boosting throughput by $5\times$ to $10\times$ over cloud VPC networks.
Part 2: Caching Strategies & Consistency Patterns (Questions 8–13)
8. Compare Cache-Aside (Lazy Loading), Read-Through, Write-Through, and Write-Behind caching.
- Answer: Cache-Aside (Lazy Loading): Application checks cache first; on a miss, queries the database and populates the cache. Only requested data is cached, but initial requests suffer a cache miss penalty and stale data can persist until TTL expiration. Read-Through: The cache provider itself (or sidecar proxy) transparently fetches missing keys from the database on a miss, simplifying application code. Write-Through: Application writes synchronously to the cache, which synchronously commits to the database before returning. Ensures strong consistency, at the cost of higher write latency. Write-Behind (Write-Back): Application writes to the cache and receives an immediate ACK; the cache flushes batched updates asynchronously to the database. Delivers extreme write throughput, but risks data loss if the cache node crashes before flushing.
9. Why can concurrent Cache-Aside updates cause stale data races, and how do you prevent them?
- Answer: Suppose Request A (read) experiences a cache miss and reads old value
v1from the DB. Before Request A writesv1into Redis, Request B (write) updates the DB tov2and invalidates (DEL) the cache key. Request A then finishes and writes stalev1into Redis, pinning stale data until the TTL expires. Mitigation: Always set bounded TTLs as a safety net, use versioned keys / monotonic timestamps (SETvia Lua script only ifnew_version > cached_version), or stream database Change Data Capture (CDC) events via Debezium/Kafka to update Redis deterministically in order.
10. Should you invalidate (DEL) or overwrite (SET) a cache entry when updating the database?
- Answer: Invalidate (
DEL) is safer and more efficient in most systems. If a cached object aggregates data from multiple tables or expensive joins, recomputing it on every write wastes CPU when the record may never be read again before the next update. Furthermore, concurrent writes overwriting (SET) the cache without optimistic versioning easily race out of order, whereasDELforces the next reader to load the latest committed state cleanly.
11. Explain Redis Eviction Policies (allkeys-lru, volatile-lru, allkeys-lfu, noeviction).
- Answer: When Redis reaches
maxmemory:noeviction: Returns anOOMerror on new write commands (default; mandatory when using Redis as a primary state store or message queue).allkeys-lru: Evicts the Least Recently Used keys across the entire keyspace (ideal for general-purpose caches).volatile-lru: Evicts LRU keys only among keys that have an explicitEXPIRETTL set, preserving permanent configuration keys.allkeys-lfu: Evicts the Least Frequently Used keys using a Morris probabilistic counter—superior to LRU when a batch job scans cold items once, preventing one-off scans from flushing genuinely hot items.
12. How do you implement a safe Distributed Lock in Redis without deadlocks or lock-stealing?
- Answer: Never use
SETNXfollowed byEXPIRE(non-atomic: a crash between commands creates a permanent deadlock). Instead: Acquire atomically with a unique random owner token (UUID):SET lock:order:99 <uuid_token> NX PX 10000Release only if the token still matches using an atomic Lua script so a slow worker whose lock expired cannot accidentally delete another worker's newly acquired lock:
LUA
-- Atomic Redis Lock Release (release_lock.lua)
if redis.call("GET", KEYS[1]) == ARGV[1] then
return redis.call("DEL", KEYS[1])
else
return 0
end
13. How does a Sliding-Window Rate Limiter work in Redis using Sorted Sets (ZSET)?
- Answer: Store each request timestamp (in milliseconds) as both the score and unique member in a
ZSETkeyed byratelimit:{user_id}. Inside an atomic Lua script:ZREMRANGEBYSCOREremoves entries older thannow - window_ms.ZCARDcounts active requests in the current window. If count< limit,ZADDinserts the current timestamp andPEXPIRErefreshes the key TTL.
Part 3: Production Failure Modes & Distributed Scaling (Questions 14–20)
14. What is a Cache Stampede (Thundering Herd), and how do you prevent it?
- Answer: A Cache Stampede happens when an ultra-popular key (e.g., homepage config or flash-sale product) expires, causing thousands of concurrent app servers to miss the cache simultaneously and slam the primary database with identical expensive queries. Mitigations: Distributed Mutex / Singleflight Coalescing: Only one worker acquires a short-lived lock (
SET mutex:key 1 NX PX 3000) to recompute the value from the DB while concurrent callers wait briefly or return stale data. Probabilistic Early Expiration (PER / XFetch): Workers asynchronously refresh keys slightly before their hard TTL expires based on recomputation cost and random jitter.
15. What is Cache Penetration, and how do Bloom Filters defend against it?
- Answer: Cache Penetration occurs when attackers or buggy clients repeatedly query keys that do not exist in either the cache or the database (e.g.,
GET /users/-99999or random non-existent UUIDs). Because misses are never cached, 100% of malicious traffic bypasses Redis and hammers the database. Mitigations: Cache Null / Negative Results: Store a sentinel value ("NULL") in Redis with a short TTL (30–60s) for non-existent IDs. Bloom Filter Gatekeeper: Maintain a compact in-memory Bloom Filter containing all valid IDs before the cache layer—immediately rejecting guaranteed non-existent IDs in $O(k)$ time with zero DB queries.
16. What is a Cache Avalanche, and how does TTL Jitter prevent it?
- Answer: A Cache Avalanche occurs when thousands of cached keys are loaded at the same time with an identical TTL (e.g.,
EXPIRE 3600during a batch warm-up) and expire simultaneously—or when an entire cache cluster restarts—causing a sudden spike of database traffic that triggers cascading outages. Mitigation: Add random TTL Jitter to every write (ttl = base_ttl + random.randint(0, 300)) so expirations spread smoothly over time, and deploy multi-AZ replica nodes with circuit breakers.
17. How do you solve the "Hot Key" problem in a sharded Redis Cluster?
- Answer: Even in a 10-shard Redis Cluster, a single viral key (e.g., celebrity profile or live election counter) hashes to one specific shard, saturating that single node's CPU and network NIC while the other 9 shards sit idle. Mitigations: In-Process L1 Local Cache: Cache ultra-hot keys inside each application container's local RAM for a very short TTL (
1–5 seconds), absorbing 99% of reads before hitting Redis. Key Salting / Read Replicas: Append a random suffix (hot_key:{0..9}) across multiple shards for read distribution, or route reads across dedicated Redis read replicas.
18. How does Redis Cluster partition data across nodes without a central proxy?
- Answer: Redis Cluster divides the keyspace into
16,384hash slots usingCRC16(key) mod 16384. Each primary shard owns a contiguous range of hash slots. Smart cluster-aware clients cache the slot-to-node topology map locally and route commands directly to the owning shard in 1 network hop (updating their routing table whenever a node responds with a-MOVEDredirect).
19. What are Redis Hash Tags ({...}), and when are they required in Redis Cluster?
- Answer: Multi-key commands (
MGET,SUNION,RENAME, or multi-key Lua scripts) fail in Redis Cluster withCROSSSLOT Keys in request don't hash to the same slotif the keys map to different shards. Wrapping a substring in curly braces—such asuser:{1042}:profileanduser:{1042}:orders—forces Redis Cluster to computeCRC16only on1042, guaranteeing both keys reside on the exact same shard.
20. Walk through a multi-layer caching architecture for a global, high-traffic cloud API.
- Answer: Edge CDN Layer (Cloudflare / CloudFront): Caches public, cacheable HTTP responses (
Cache-Control: public, s-maxage=60, stale-while-revalidate=30) closest to end users. L1 In-Process Application Cache (Caffeine /cachetools): Stores top $1\%$ ultra-hot configuration and metadata keys inside microservice RAM (1–5sTTL) to eliminate network hops and hot-key shard bottlenecks. L2 Distributed Shared Cache (Multi-AZ Redis Cluster): Stores user sessions, rate-limit counters, and shared entity objects withallkeys-lfueviction, TTL jitter, and singleflight stampede locks. Persistence Layer (Primary DB + Read Replicas + CDC): Streams committed row updates via CDC to invalidate or refresh L2 Redis keys deterministically.