Databases 23 min read

Master Redis Interview Questions: Performance, Persistence, High Availability & More

This comprehensive guide covers why Redis is fast, its underlying data structures, single‑threaded and epoll models, cache eviction policies, persistence mechanisms, high‑availability architecture, performance bottlenecks, distributed locking, cache avalanche/penetration strategies, data skew handling, and bitmap applications, providing essential knowledge for interview preparation.

Su San Talks Tech
Su San Talks Tech
Su San Talks Tech
Master Redis Interview Questions: Performance, Persistence, High Availability & More

1 Redis Why Fast

1.1 Data Stored In Memory

Redis stores data in memory, so read/write operations only access RAM without disk I/O.

1.2 Underlying Data Structures

Data is kept as key:value pairs in a hash table with O(1) time complexity.

Redis defines rich value structures such as dynamic strings, doubly linked lists, ziplist, hash, skiplist, and integer arrays, choosing the most efficient one based on the value's characteristics.

1.3 Single‑Threaded Model

Redis uses a single‑threaded model for network I/O and data read/write, binding to a CPU to avoid context‑switch overhead. Note: Redis 6.0 introduces a multithreaded network model, but read/write remains single‑threaded.

Redis multithreaded network model:

1.4 I/O Multiplexing

Redis adopts the epoll network model. The kernel continuously monitors new socket connections and established socket read/write events, placing them into an event queue that the single thread processes, avoiding blocking waits.

These events are bound to callback functions that invoke Redis handlers.

2 Redis Underlying Data Structures

Redis has five data types: strings, lists, sets, sorted sets, and hashes.

Its six internal structures are dynamic strings, doubly linked lists, ziplist, hash tables, skiplist, and integer arrays.

2.1 String Type

Implemented with dynamic strings.

2.2 List

If both conditions are met, a ziplist is used; otherwise a doubly linked list.

Element size < 64 bytes

Number of elements < 512

Ziplist is a contiguous memory block; its lookup complexity is O(n).

2.3 Set

If elements are all integers and count ≤ 512, an ordered integer array is used; otherwise a hash table.

2.4 Sorted Set

If both conditions are met, a ziplist is used; otherwise a skiplist.

Element size < 64 bytes

Number of elements < 128

Skiplist provides O(log N) insert/delete/search and uses extra index nodes.

2.5 Hash

If each entry’s key/value is < 64 bytes and total entries < 512, a ziplist is used; otherwise a hash table.

3 Redis Cache Eviction Policies

Redis provides eight eviction strategies (illustrated below). The volatile‑lfu and allkeys‑lfu policies were added in version 4.0.

lru : evicts least recently used keys; can mistakenly evict hot data if many cold keys are accessed recently.

lfu : evicts keys with the lowest access frequency; ties are broken by older access time.

4 Redis Persistence

Redis supports two persistence methods: Append‑Only File (AOF) and RDB snapshots.

4.1 AOF Log

AOF records every received command; on restart Redis replays the log. AOF offers three sync strategies.

For non‑critical data loss scenarios, everysec is recommended, causing only ~1 s data loss.

4.2 RDB Snapshot

RDB captures the entire dataset at a point in time.

4.3 Hybrid Persistence (Redis 4.0+)

From Redis 4.0, AOF can embed an RDB snapshot at the beginning of the AOF file, enabling faster recovery.

4.4 Master‑Slave Replication

The master generates an RDB snapshot for the slave, then streams subsequent commands via the replication buffer.

4.5 AOF Rewrite

AOF rewrite compacts multiple commands for the same key into a single entry.

4.6 Blocking Points

Both AOF rewrite and RDB snapshot fork a child process; the fork copies the page table, blocking the main thread proportionally to memory size. Copy‑on‑write also incurs blocking when large pages are used.

When using large 2 MB pages, even a tiny key modification may require copying an entire page.

5 Redis High Availability

Typical “one master, two slaves, three sentinels” architecture is shown below.

When the master fails, sentinels coordinate a failover through four steps: detecting master down, electing a new master, electing a sentinel leader, and switching the master.

5.1 Detect Master Down

Sentinels exchange “Y”/“N” votes; a majority (n/2 + 1) must agree.

5.2 Elect New Master

Sentinels discard unstable slaves (based on down‑after‑milliseconds), consider slave‑priority, and prefer slaves whose replication offset is closest to the master’s.

5.3 Elect Sentinel Leader

The first sentinel that confirms master down becomes the leader after obtaining a quorum of votes.

5.4 Master Switch

The leader notifies other sentinels, slaves, and clients of the new master address.

6 Why Redis Becomes Slow

Performance degradation stems from two categories: main‑thread blocking and OS limits.

6.1 Main‑Thread Blocking

6.1.1 AOF Rewrite & RDB Snapshot

Both operations fork a child process; the fork copies the page table, which can be CPU‑intensive for large instances.

6.1.2 Large Memory Pages

Redis uses 2 MB pages by default; modifying a small key still requires copying an entire page, increasing latency.

6.1.3 High‑Complexity Commands

Commands like SORT on sets/lists have O(N + M·log M) complexity.

6.1.4 Big‑Key Operations

Large values cause costly allocation and deletion. Redis 4.0 introduced lazyfree (e.g., UNLINK) for asynchronous deletion; Redis 6.0 adds lazyfree‑lazy‑user‑del to make DEL async.

6.1.5 Full Sync of Slaves

During full sync, the slave clears memory and loads the RDB file, blocking reads.

6.1.6 AOF Sync to Disk

appendfsync

strategies (always, everysec, no) affect latency; “always” blocks on every write.

6.1.7 Memory Reaching maxmemory

Eviction and lazyfree still involve blocking operations.

6.2 OS Limits

6.2.1 Swap Usage

Swapping due to insufficient RAM dramatically slows Redis.

6.2.2 Network Saturation

High NIC load or competing traffic reduces throughput.

6.2.3 Thread Context Switch

Even with a single thread, moving between CPU cores can lose cache locality; binding Redis to a specific CPU mitigates this.

6.2.4 Disk Performance

Slow disks hurt AOF sync; SSDs are preferred.

7 Designing Leaderboard with Redis

Use the zset type to store scores; increment with ZINCRBY and retrieve top entries with ZRANGE (or ZREVRANGE).

8 Implementing Distributed Locks

8.1 Single‑Node Lock

Typical implementation uses SETNX (or SET … NX EX with expiration) to acquire a lock. SETNX KEY_NAME VALUE To avoid deadlocks, set an expiration:

SET key value [EX seconds] [PX milliseconds] NX

8.2 Redis Redlock

Redlock acquires locks on multiple Redis instances; a majority (e.g., 2 of 3) must succeed for the lock to be considered acquired.

9 Cache Avalanche, Stampede, Penetration

9.1 Cache Avalanche

Massive simultaneous expiration floods the DB. Mitigations: add random jitter to TTLs, rate‑limit, or degrade service.

9.2 Cache Stampede

Hot key expires, causing a surge of DB reads. Solution: keep hot keys without expiration.

9.3 Cache Penetration

Requests for nonexistent keys hit DB repeatedly. Solutions: cache empty values or use a Bloom filter before DB queries.

10 Data Skew

When a hot key receives extremely high QPS (e.g., 1 million), it can overload a single Redis instance. Mitigations: client‑side caching or sharding the hot key with random prefixes across multiple instances.

11 Bitmap Usage

11.1 Bitmap Introduction

Bitmaps store bits in a string, enabling compact representation of large integer sets. For 10 billion integers, a bitmap requires (max‑min + 1) bits.

11.2 Use Cases

11.2.1 Employee Attendance

Create a daily bitmap where each employee’s bit indicates presence; BITCOUNT gives daily attendance, and BITOP AND across 30 days yields fully present employees.

BITOP AND srckey1 srckey2 ... srckey30

11.2.2 Daily Active Users

Assign each user ID a bit in a bitmap; set the bit on login and use BITCOUNT to count daily active users.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

databasehigh availabilityrediscaching
Su San Talks Tech
Written by

Su San Talks Tech

Su San, former staff at several leading tech companies, is a top creator on Juejin and a premium creator on CSDN, and runs the free coding practice site www.susan.net.cn.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.