Skip to main content
InterviewHubPRO
HomeTracksSection 18: Redis & Caching (50 Qs)
Section 18 of 6450 Questions (1 Per Page)

Redis In-Memory Data Store & Distributed Caching Master Interview Bank

Redis single-threaded event loop, core data structures, memory eviction policies, RDB and AOF persistence, Redis Cluster, Sentinel, and Redlock.

Curriculum Roadmap & Learning Path

3 Stages
Tip: Click any stage card above to instantly filter the question bank to that topic.3 Connected Milestones
50 of 50 Qs

Part 1: Basic & Foundational Concepts (Junior / Entry-Level)

10 Questions
1
Senior#redis#Basic

What is Redis and why is it so fast?

Redis (Remote Dictionary Server) is an open-source, in-memory key-value data structure store used as a database, cache, message broker, and streaming engine: In-Memory Storage: All primary data resides in RAM • Single-Threaded Event Loop: Uses non-blocking I/O multiplexing (epoll/kqueue).

2
JuniorCode#redis#Basic

What are the core Redis Data Structures and their primary use cases?

String: Basic text or binary blob up to 512 MB (caching JSON, session tokens, atomic integer counters with INCR) • Hash: Key-value map representing an object (e.g. user profile attributes: name, email, age) • List: Linked list of strings ordered by insertion (job queues, activity feeds with LPUSH/RPOP).

3
Junior#redis#Basic

How does TTL (Time to Live) and Key Expiration work in Redis?

You can set an expiration timeout on any key using EXPIRE key seconds or SET key value EX seconds: When the timer expires, the key becomes inaccessible to clients • Eviction Mechanisms • Passive (Lazy) Expiration: When a client tries to read a key, Redis checks if it has expired.

4
Most AskedJunior#System Design

What are the common Caching Patterns: Cache-Aside vs Write-Through vs Write-Behind?

Cache-Aside (Lazy Loading - Most Common) • Application checks Redis • If miss -> read from PostgreSQL/MySQL, store in Redis with TTL, return data • Write-Through: Application writes data to the cache, and the cache synchronously writes to the database before acknowledging success.

5
Junior#redis#Basic

What are the differences between `INCR`, `DECR`, and string commands?

Redis provides atomic operations that execute without race conditions: INCR counter: Atomically increments an integer string by 1 • INCRBY counter 5: Increments by an arbitrary step • SETNX key value ("Set if Not eXists"): Only sets the key if it does not already exist.

6
Junior#redis#Basic

What is the Redis serialization protocol (RESP)?

RESP (REdis Serialization Protocol) is the human-readable, high-speed binary-safe text protocol Redis uses over TCP: Simple Strings start with + (e.g. +OK\r\n) • Errors start with - (e.g. -ERR unknown command\r\n) • Integers start with : (e.g. :1000\r\n).

7
JuniorCode#Pipes#CI/CD & DevOps

What is Pipeline (Pipelining) in Redis?

Pipelining allows a client to send multiple commands to the Redis server in a single TCP batch without waiting for the response of each command individually: Eliminates Round-Trip Time (RTT) network latency • Increases throughput from ~10,000 ops/sec up to 500,000+ ops/sec on a single core!.

8
Junior#redis#Basic

Why is `KEYS *` dangerous in production and what should you use instead?

KEYS * runs a linear O(N) scan across all keys in the database: Because Redis is single-threaded, a database with 10 million keys will freeze completely for seconds or minutes, blocking all other web requests.

9
Most AskedJunior#System Design

What is the difference between Redis and Memcached?

Memcached: Pure multithreaded key-value cache • Redis: Rich data structures, disk persistence (RDB/AOF), master-replica replication, automatic failover (Sentinel), horizontal clustering.

10
Most AskedJuniorCode#redis#Basic

How do you implement a simple Rate Limiter using Redis Sorted Sets (Sliding Window)?

Sliding window rate limiters prevent boundary spikes: Use a Sorted Set where both the member and score are the current Unix epoch timestamp in milliseconds.

Part 2: Core Architecture & Implementation (Mid-Level)

10 Questions
11
Most AskedSenior#Event Loop#System Design

How does the single-threaded Event Loop work in Redis?

Redis's core request-processing loop runs on a single main execution thread: Built around I/O multiplexing primitives (epoll on Linux, kqueue on macOS) • The operating system notifies the event loop when a socket has incoming data to read or is ready to write.

12
Senior#System Design

What are the Redis Memory Eviction Policies (maxmemory-policy)?

When memory usage reaches maxmemory, Redis evicts keys according to the configured policy: noeviction (Default): Returns out-of-memory errors on new writes (OOM command not allowed) • allkeys-lru: Evicts least recently used keys across all keys (best for general web caches).

13
Most AskedSeniorCode#System Design

What is Cache Penetration, Cache Breakdown, and Cache Avalanche?

The 3 classic high-scale caching failure scenarios: Cache Penetration: Queries request keys that do not exist in both cache and DB (e.g. malicious requests for id = -999) • Fix: Cache null objects with short TTL (SET id:-999 null EX 60), or use a Bloom Filter.

14
Senior#System Design

What are Redis Persistence Mechanisms: RDB vs. AOF?

RDB (Redis Database Snapshot): Point-in-time snapshot of the entire dataset saved to a binary dump file (dump.rdb) • Uses bgsave which invokes Linux fork() (Copy-On-Write) • AOF (Append Only File): Logs every write command sequentially • Higher durability.

15
Senior#System Design

How does AOF Rewrite (BGREWRITEAOF) prevent infinite log file growth?

If a key is updated 10,000 times (INCR counter), the AOF file contains 10,000 lines: AOF Rewrite: Redis forks a child process to inspect the current state of memory and writes the minimum necessary commands to recreate the • Swaps the new compact AOF file atomically.

16
SeniorCode#State Management#System Design

What is the difference between Redis Transactions (MULTI/EXEC) and Lua Scripts?

MULTI / EXEC / WATCH • MULTI queues commands; EXEC runs them sequentially • WATCH provides optimistic locking (aborts if a key was modified before EXEC) • Limitation: Cannot use conditional results from one command inside the next command in the same transaction!.

17
Senior#System Design

What is Pub/Sub in Redis and what is its main limitation?

Redis Pub/Sub provides simple message broadcasting (PUBLISH, SUBSCRIBE, PSUBSCRIBE): Limitation (At-Most-Once / Fire-and-Forget): Redis does not buffer or store messages • Use Redis Streams if message persistence, acknowledgments, and consumer groups are required.

18
Senior#System Design#Apache Kafka

How do Redis Streams work with Consumer Groups?

Redis Streams (XADD, XREADGROUP, XACK) provide Kafka-like persistent message streaming: Message IDs: Millisecond timestamp + sequence number (1710500000000-0) • Consumer Groups: Multiple consumers share a stream; messages are distributed among consumers for parallel processing.

19
Senior#System Design

What is Redis Sentinel and how does it provide High Availability?

Sentinel is a distributed monitoring and failover management system: Runs as independent daemon processes alongside Redis master and replica nodes • Continuously pings master and replicas (PING) • Quorum Consensus: If a majority of Sentinels agree that Master is unreachable (sdown -> odown), Sentinel elects a new master via Raft.

20
Senior#System Design

How does Master-Replica Replication work in Redis?

Replication is asynchronous: Initial Sync (Full Resync): Master runs bgsave to create an RDB snapshot and sends it over the network to the Replica • The replica loads the RDB file into memory • Master buffers new writes in the Replication Backlog Buffer and streams them to the replica continuously.

Part 3: Advanced Internals, Scale & Production Patterns (Senior / Lead)

30 Questions
21
SeniorCode#redis#Advanced Internals

How does Redis Cluster partition data across 16,384 Hash Slots?

Redis Cluster provides transparent, distributed horizontal sharding with zero single point of failure: The keyspace is divided into 16,384 Hash Slots (0 to 16,383) • Slot Calculation • The 16,384 slots are divided among master nodes (e.g. Node 1 owns 0-5460, Node 2 owns 5461-10922, Node 3 owns 10923-16383).

22
Senior#redis#Advanced Internals

What are Hash Tags in Redis Cluster and why are they necessary for multi-key commands?

In Redis Cluster, multi-key commands (MGET, MSET, transactions) fail if the keys live on different cluster nodes: Hash Tags {...}: Force Redis to hash only the text inside curly braces • user:{101}:profile and user:{101}:orders will hash strictly on {101}.

23
SeniorCode#System Design

What is the Redlock Algorithm and how does Distributed Locking work?

Single-instance Redis locks (SET key uuid NX PX 30000) fail if the master crashes before replicating the lock to the replica (split-brain lock acquisition): Redlock (Martin Kleppmann / Salvatore Sanfilippo) • Acquire lock across N independent Redis master nodes (e.g. 5 nodes).

24
Most AskedSenior#System Design

What is a Bloom Filter in Redis (RedisBloom) and how does it eliminate Cache Penetration?

A Bloom Filter is a space-efficient probabilistic data structure used to test set membership: Returns: "Definitely NOT in the set" or "Might be in the set" (never false negatives, small configurable false positive rate) • Architecture: When a user queries id = 999, the app queries the Bloom Filter in memory first.

25
Senior#redis#Advanced Internals

How do Redis Skiplists work in Sorted Sets (ZSET)?

A Sorted Set is implemented internally using a Hash Table (O(1) score lookup by member) paired with a Skip List: Skip List: A probabilistic hierarchy of linked lists where higher levels act as "express lanes" skipping multiple nodes • Provides O(\log N) average time complexity for insertions, deletions, and range queries (ZRANGEBYSCORE).

26
Senior#redis#Advanced Internals

What causes Fork Latency and Copy-On-Write (COW) Memory Spikes during RDB/AOF saves?

When executing BGSAVE or BGREWRITEAOF, Redis calls fork() to spawn a child process: Linux duplicates page tables • Copy-On-Write (COW): Memory pages are shared between parent and child until written to • Ensure servers have at least 2x memory allocated or disable Transparent Huge Pages (THP).

27
Senior#redis#Advanced Internals

Why must Transparent Huge Pages (THP) be disabled for Redis?

Linux Transparent Huge Pages (THP) allocates memory in 2 MB chunks instead of standard 4 KB pages: During Copy-On-Write, writing a single 10-byte string forces the OS to duplicate an entire 2 MB memory page! • Causes severe memory bloat, high allocation latency, and random connection timeouts.

28
Most AskedSenior#CLI#Forms

What is Client-Side Caching (Tracking / Invalidation) in Redis 6?

Caches hot data directly in application process memory (Node.js/Go RAM) for zero-latency in-process lookups: The Invalidation Challenge: How does the app know when Redis data changed? • Redis 6 Tracking: The client instructs Redis to track keys it has read.

29
Senior#redis#Advanced Internals

How do you troubleshoot Redis Latency and High CPU?

Check the Slowlog: SLOWLOG GET 20 (identifies commands exceeding slowlog-log-slower-than) • Run redis-cli --latency and redis-cli --intrinsic-latency to differentiate network vs engine latency • Check CPU profile with INFO commandstats (detects heavy commands like KEYS, SMEMBERS, or large HGETALL).

30
Senior#redis#Advanced Internals

How does Redis handle Big Keys and Hot Keys?

Big Key: A single key containing millions of items (e.g. a List with 5 million entries) • Fix: Detect with redis-cli --bigkeys • Hot Key: A single key receiving 100,000 QPS, exhausting a single node's network interface.

31
Most AskedSenior#redis#Advanced Internals

What is Active Defragmentation in Redis?

Frequent allocations and deallocations in RAM cause memory fragmentation (high RSS memory while actual data is small): Traditional restart reclaims memory but incurs downtime • Active Defragmentation (activedefrag yes): Runs concurrently inside the event loop, allocating new contiguous memory blocks, copying data over.

32
Senior#redis#Advanced Internals

What is Redis Lua Script Timeout and `SCRIPT KILL`?

Because Lua scripts run atomically, an infinite loop freezes Redis completely: Configured by lua-time-limit (default 5,000ms) • When a script exceeds the threshold, Redis accepts administrative commands and responds with -BUSY • You can execute SCRIPT KILL to abort a read-only script.

33
Senior#redis#Advanced Internals

How does Redis achieve Cross-DC Replication (Active-Active)?

Standard Redis replication is strictly master-replica within a single datacenter: For active-active multi-region deployments, enterprise systems use CRDTs (Conflict-Free Replicated Data Types) (e.g. Redis Enterprise Active-Active).

34
Senior#redis#Advanced Internals

What is the difference between `EXPIRE` and `PEXPIRE`?

EXPIRE key seconds: Sets TTL in whole seconds • PEXPIRE key milliseconds: Sets TTL with millisecond precision • Internally, Redis always converts all expiration timestamps to Unix epoch in milliseconds for consistency across replication and restarts.

35
Senior#redis#Advanced Internals

When should you NOT use Redis?

Primary storage for datasets significantly larger than physical RAM: RAM costs 5-10/GB vs $0.02/GB on SSDs (use DynamoDB, Cassandra, or PostgreSQL) • Complex relational joins and ad-hoc aggregations: Redis lacks relational querying capabilities.

36
Most AskedSenior#Event Loop

Redis Single-Threaded Event Loop vs Multi-Threaded I/O (Redis 6.0+).

Core Engine is Single-Threaded: All command execution (updating strings, sets, hashes) runs on a single main thread, using non-blocking I/O • Multi-Threaded I/O (Redis 6.0+): Reading network requests and writing socket responses is offloaded to worker threads, while command execution.

37
Senior#redis#Advanced Internals

Redis Data Structures: Use Cases for ZSET, HyperLogLog, and Bitmaps.

Sorted Set (ZSET): Stores unique members with an associated floating-point score (backed by a SkipList and Hash) • HyperLogLog (PFADD, PFCOUNT): Probabilistic data structure that estimates unique items (cardinality) with a standard error of 0.81\%, using a • Bitmaps (SETBIT, BITCOUNT): Manipulates individual bits within strings.

38
Most AskedSenior#System Design

Caching Strategies: Cache-Aside vs Write-Through vs Write-Behind.

Cache-Aside (Lazy Loading): Application reads from Redis • Write-Through: Application writes data to Redis; the cache synchronous layer writes to the database immediately before confirming • Write-Behind (Write-Back): Application writes to Redis immediately; an asynchronous background worker flushes batched writes to the DB.

39
Most AskedSenior#System Design

Cache Stampede (Thundering Herd) Mitigation: Probabilistic Early Expiration.

A Cache Stampede occurs when a hot cache key expires (e.g. homepage top products), causing thousands of concurrent requests to hit the backend database simultaneously: Solution 1: Distributed Mutex Lock: The first thread acquires a lock to recompute the cache while others wait or return stale data.

40
Most AskedSenior#System Design

Cache Penetration & Bloom Filters.

Cache Penetration occurs when queries request non-existent keys (e.g. id = -9999 sent by an attacker). Since the key is neither in Redis nor the DB, every request bypasses the cache and hammers the database: Mitigation 1 (Null Caching): Cache the non-existent result with a short TTL (SET user:-9999 "NULL" EX 60).

41
Senior#redis#Advanced Internals

Redis Memory Eviction Policies: LRU vs LFU.

When memory reaches maxmemory, Redis evicts keys according to its configured policy: noeviction (Default): Returns errors on write operations when memory is full • allkeys-lru: Evicts the Least Recently Used keys across all keys (best for general caching).

42
Senior#redis#Advanced Internals

Redis Persistence: RDB vs AOF vs Hybrid.

RDB (Snapshotting): Point-in-time binary snapshot of memory dumped to disk via BGSAVE (fork() copy-on-write) • AOF (Append Only File): Logs every write command sequentially (appendfsync everysec) • Hybrid Persistence (Default in Redis 5+): RDB snapshot preamble + AOF incremental log tail for fast restarts and high durability.

43
Senior#System Design

Distributed Locks in Redis: Single-Node vs Redlock.

Single-Node Lock: SET resourcekey randomtoken NX PX 10000 (Acquires lock if Not eXists with 10s auto-expiry) • Redlock Algorithm: For multi-node independent Redis clusters.

44
SeniorCode#State Management#Databases & SQL

Atomic Operations: Redis Transactions (`MULTI`/`EXEC`) vs Lua Scripts (`EVAL`).

MULTI / EXEC: Queues commands and runs them sequentially • Lua Scripts (EVAL): Executed atomically in the Redis main thread.

45
Senior#Apache Kafka#Microservices

Redis Streams vs Kafka vs Pub/Sub.

Pub/Sub: Fire-and-forget; messages are lost if the subscriber is disconnected • Redis Streams (XADD, XREADGROUP): Persistent append-only log with consumer groups, message acknowledgments (XACK), and Pending Entries List.

46
Senior#System Design

High Availability with Redis Sentinel.

Redis Sentinel is a distributed monitoring and failover system for Master-Replica topologies: Monitoring: Sentinels continuously ping Master and Replica nodes • Quorum Election: If Master is unreachable, Sentinels agree via quorum (ODOWN), promote a Replica to Master, and notify clients via Pub/Sub to.

47
Senior#redis#Advanced Internals

Redis Cluster: 16,384 Hash Slots and Hash Tags.

Redis Cluster shards data across multiple nodes without a centralized proxy: 16,384 Hash Slots: Keys are mapped to slots using CRC16(key) % 16384 • Hash Tags ({user_id}): Only the string inside {} is hashed.

48
Most AskedSenior#redis#Advanced Internals

Rate Limiting with Sliding Window Log (ZSET).

Fixed-window rate limiters suffer from 2x traffic spikes at window boundaries. Sliding Window Log uses a Redis Sorted Set: Store timestamp as both member and score: ZADD rate:user1 • Remove timestamps older than window: ZREMRANGEBYSCORE rate:user1 0 ( - 60) • Count remaining requests: ZCARD rate:user1.

49
Senior#redis#Advanced Internals

Bigkey and Hotkey Detection in Production.

Bigkey: A single key containing megabytes of data (e.g. a Set with 1M items) • Hotkey: A single key receiving 50,000+ QPS, saturating a single CPU core • Mitigation: Enable Client-Side Caching (Tracking) via RESP3 to cache hot keys in application RAM.

50
Senior#redis#Advanced Internals

Enterprise Redis: Active-Active Multi-Region CRDTs.

Running Redis across globally distributed datacenters (US, EU, APAC) with sub-millisecond local reads and writes uses Conflict-Free Replicated Data Types (CRDTs): Nodes in different regions accept concurrent writes locally.