Databases 45 min read

Redis Interview Questions and Core Concepts: Data Types, Performance, Persistence, High Availability, and Common Use Cases

This article provides a comprehensive overview of Redis, covering its definition, basic and special data structures, performance optimizations, expiration and eviction policies, common application scenarios, persistence mechanisms, high‑availability architectures, distributed lock implementations, transaction handling, and related algorithms such as Redlock and Bloom filters.

Full-Stack Internet Architecture
Full-Stack Internet Architecture
Full-Stack Internet Architecture
Redis Interview Questions and Core Concepts: Data Types, Performance, Persistence, High Availability, and Common Use Cases

Redis (Remote Dictionary Server) is an open‑source, in‑memory key‑value store written in ANSI C that supports persistence, networking, and multiple language APIs. It is widely used for caching, distributed locks, and various data‑structure‑based features.

Basic Data Types

Redis provides five primary data types: String, Hash, List, Set, and Sorted Set (zset), plus three special types: Geospatial, HyperLogLog, and Bitmap.

String

Strings are binary‑safe and can store up to 512 MB. Example commands:

set key value
get key

Internal encodings include int, embstr, and raw. Redis uses SDS (Simple Dynamic String) instead of C's char[] for efficient length retrieval.

struct sdshdr{
  unsigned int len;   // length of buffer
  unsigned int free; // unused space
  char buf[];        // data
}

Hash

Hashes store a map of fields to values. Example commands:

hset key field value
hget key field

Internal encodings are ziplist and hashtable.

List

Lists hold ordered strings. Example commands:

lpush key value [value ...]
lrange key start end

Encodings: ziplist or linkedlist. Common use cases include message queues and article lists.

Set

Sets store unique strings. Example commands:

sadd key element [element ...]
smembers key

Encodings: intset and hashtable.

Sorted Set (zset)

Sorted sets store unique strings with scores. Example commands:

zadd key score member [score member ...]
zrank key member

Encodings: ziplist and skiplist.

Special Data Types

Geospatial – location indexing.

HyperLogLog – cardinality estimation.

Bitmap – bit‑level operations for massive boolean data.

Why Redis Is Fast

Redis achieves high performance through in‑memory storage, efficient data structures (SDS, hash tables, skiplists), O(1) operations, and an event‑driven single‑threaded I/O model with epoll for multiplexing. Since Redis 6.0 it also uses optional worker threads for network I/O.

Thread Model

Redis primarily runs a single thread for command execution, avoiding context switches, while optional I/O threads handle socket reads/writes.

Cache Issues

Cache Penetration

When a request queries a non‑existent key, it bypasses the cache and hits the database each time. Mitigations include request validation, caching null values, and using Bloom filters.

Cache Avalanche

Massive simultaneous expiration can overload the database. Staggered TTLs and high‑availability clusters help prevent this.

Cache Breakdown (Hot Key)

A hot key expiring at a peak moment can cause a surge of DB requests. Solutions include mutex locks, “never expire” patterns, or proactive refreshes.

Expiration and Eviction Strategies

Redis supports three expiration strategies: active (timers), lazy (on‑access), and periodic (random sampling). When memory is insufficient, eight eviction policies are available, such as volatile‑lru, allkeys‑lru, volatile‑lfu, allkeys‑lfu, volatile‑random, allkeys‑random, volatile‑ttl, and noeviction.

Common Use Cases

Cache layer for hot data.

Leaderboards using sorted sets.

Counters for real‑time metrics.

Shared session storage.

Distributed locks (setnx, set ex px nx, Redisson watchdog).

Social features (likes, followers).

Simple message queues via lists or pub/sub.

Bit operations for massive boolean flags.

Persistence Mechanisms

RDB

Snapshotting the dataset to a dump.rdb file at configured intervals. Advantages: fast backup, low runtime overhead. Disadvantages: not real‑time, version compatibility issues.

AOF

Append‑only log of every write command, offering higher durability at the cost of larger files and slower recovery.

High Availability

Master‑Slave Replication

Data is replicated from a master to one or more slaves using full and incremental sync. The replicationFeedSlaves() function propagates writes to slaves.

Sentinel

Sentinel monitors masters and slaves, performs automatic failover, and notifies clients. It uses subjective and objective down detection with voting.

Cluster

Redis Cluster shards data across 16384 hash slots, uses the Gossip protocol for node communication, and provides automatic failover within each shard.

Distributed Locks

Common implementations:

if (jedis.setnx(key, lock_value) == 1) {
    expire(key, 100);
    try { /* business */ } finally { jedis.del(key); }
}

Improved version with expiration stored in the value:

long expires = System.currentTimeMillis() + expireTime;
String expiresStr = String.valueOf(expires);
if (jedis.setnx(key, expiresStr) == 1) return true;
String current = jedis.get(key);
if (current != null && Long.parseLong(current) < System.currentTimeMillis()) {
    String old = jedis.getSet(key, expiresStr);
    if (old != null && old.equals(current)) return true;
}
return false;

Atomic set with NX and EX options:

if (jedis.set(key, lock_value, "NX", "EX", 100) == 1) {
    try { /* business */ } finally { jedis.del(key); }
}

Safer version using a unique request ID and Lua for atomic check‑and‑delete:

if (jedis.set(key, uniqId, "NX", "EX", 100) == 1) {
    try { /* business */ } finally {
        if (uniqId.equals(jedis.get(key))) jedis.del(key);
    }
}
if redis.call('get', KEYS[1]) == ARGV[1] then
    return redis.call('del', KEYS[1])
else
    return 0
end

Redlock Algorithm

Redlock obtains locks on a majority of independent Redis masters (e.g., 5) with a short timeout, measures acquisition time, and considers the lock successful only if at least N/2+1 masters grant it within the lock’s TTL.

Transactions

Redis transactions use MULTI/EXEC/WATCH to ensure atomic execution of a command queue. Commands are queued after MULTI and executed together with EXEC, or discarded with DISCARD.

Hash Collisions

Redis resolves hash collisions using chaining and performs incremental rehashing with a secondary hash table to keep lookup O(1).

RDB Generation

save blocks the server; bgsave forks a child process to write the snapshot while the parent continues serving clients.

Protocol

Redis uses the RESP (Redis Serialization Protocol) for fast, simple, and human‑readable communication.

Bloom Filter

Bloom filters provide space‑efficient probabilistic membership testing to mitigate cache penetration, using multiple hash functions and a bit array.

References

Redis high‑availability solutions – https://www.jianshu.com/p/5de2ab291696

Redis cluster deep dive – https://www.cnblogs.com/leeSmall/p/8414687.html

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.

Cachehigh availabilityredisdistributed-lockData Structures
Full-Stack Internet Architecture
Written by

Full-Stack Internet Architecture

Introducing full-stack Internet architecture technologies centered on Java

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.