Databases 21 min read

Mastering Redis: Core Uses, Data Types, Persistence, and Performance Tricks

This article explains Redis’s primary roles as a high‑speed cache, in‑memory database, and analytics engine, compares it with relational databases, details its data structures, single‑threaded performance, persistence options, expiration and eviction policies, distributed lock implementation, and strategies for cache penetration, breakdown, and avalanche.

Java Interview Crash Guide
Java Interview Crash Guide
Java Interview Crash Guide
Mastering Redis: Core Uses, Data Types, Persistence, and Performance Tricks

1. What can Redis be used for?

Redis is most commonly used as a cache, serving as the primary middleware for distributed caching.

It can act as a database to implement high‑performance features such as likes, follows, and ranking.

Redis serves as a lightweight analytics tool for counting metrics like PV/UV and user online days.

Other scenarios include implementing distributed locks and using Redis as a message queue.

2. How does Redis differ from traditional relational databases?

Redis is a key‑value NoSQL database whose values are built from various data structures and algorithms. All data resides in memory, giving it astonishing speed—read/write performance can reach 100,000 operations per second, far surpassing relational databases.

Relational databases store data in two‑dimensional tables on disk, enforce stricter schemas, and support complex relational queries. While they can hold massive amounts of data, their performance is much lower than Redis.

3. What data types does Redis provide?

Redis supports five core data types: string, hash, list, set, and sorted set.

Additional types such as Bitmap, HyperLogLog, and Geo are built on top of the core types.

Since Redis 5.0, a Streams type is available, offering a powerful, multicast‑capable, persistent message queue.

4. Why is Redis fast despite being single‑threaded?

Thread switching and locking are major performance killers; a single thread eliminates those costs.

Most operations are performed directly in memory, which is a key factor for high performance.

Redis uses I/O multiplexing to handle many client connections concurrently, achieving high throughput.

Diagram of Redis’s single‑threaded architecture:

5. How can Redis have multiple processes during persistence yet still be called single‑threaded?

Redis’s single‑threaded claim refers to its network I/O and key‑value read/write operations. Other functions such as persistence, asynchronous deletion, and cluster synchronization run in separate background threads or child processes.

6. Difference between SET and ZSET

SET: unordered, no duplicate elements, up to 2^32‑1 members; supports add/remove and set operations like intersection, union, and difference.

ZSET: ordered set that also forbids duplicates; each element has a score used for sorting; scores may be identical for different elements.

7. What is the WATCH command?

WATCH provides an optimistic lock mechanism. The client asks Redis to monitor one or more keys; if any of those keys change before the transaction is executed, Redis aborts the transaction and returns a null reply.

8. Common List operations

LPUSH / RPUSH – push elements to the left or right of the list.

LRANGE – return elements within a specified index range.

LINDEX – get the element at a specific index.

LPOP / RPOP – pop an element from the left or right.

BLPOP / BRPOP – block until an element becomes available if the list is empty.

9. Designing Redis expiration times

Do not set expiration for hot data, making it effectively permanent to avoid cache breakdown.

When setting expiration, add a random offset to prevent many keys from expiring simultaneously, which could cause a cache avalanche.

10. SETNX return value and using it for distributed locks

SETNX returns 1 if the key was set successfully, 0 if the key already exists.

Direct use of SETNX for locks is discouraged because setting the expiration is not atomic, leading to possible deadlocks. The improved SET command with the NX and EX options performs both actions atomically.

Lock acquisition examples:

setnx key value
setnx key value
expire key seconds
set key value nx ex seconds

Unlocking is simply deleting the lock key: del key Potential issue: if a lock expires before the owning process finishes, the process may unintentionally delete another process’s lock. To avoid this, include a unique identifier in the lock value and release the lock atomically via a Lua script:

# Acquire lock
set key random-value nx ex seconds
# Release lock (Lua script)
if redis.call("get",KEYS[1]) == ARGV[1] then
  return redis.call("del",KEYS[1])
else
  return 0
end

11. Redis persistence strategies

Redis supports three persistence methods: RDB, AOF, and hybrid RDB‑AOF.

RDB

RDB creates a compressed binary snapshot of the dataset. It can be triggered manually with SAVE or BGSAVE, or automatically based on configuration. BGSAVE forks a child process to write the snapshot, avoiding the blocking behavior of SAVE.

RDB advantages: compact file size and fast recovery. Disadvantages: fork operation is heavyweight and snapshots are not real‑time.

AOF

AOF logs every write command in a text protocol, enabling near‑real‑time persistence. Configuration options (appendonly yes, appendfilename "appendonly.aof") enable it.

Example AOF entry:

*3
$3
set
$5
hello
$5
world

AOF benefits: higher durability (loss limited to 1 second with everysec). Drawbacks: larger file size and slower recovery compared to RDB.

Hybrid RDB‑AOF

Since Redis 4.0, hybrid persistence writes an RDB snapshot at the start of an AOF rewrite, then appends subsequent commands in the AOF format. This combines fast recovery (RDB) with minimal data loss (AOF).

12. Why is Redis fast and how to recover after power loss?

Redis stores all data in memory, providing extremely low latency. Persistence (RDB, AOF, or hybrid) allows recovery after a crash; AOF/hybrid can limit data loss to about 1 second.

13. Redis cache eviction policies

When memory exceeds maxmemory, Redis applies the maxmemory‑policy. Options include:

noeviction – return an error.

volatile‑ttl – evict the key with the shortest remaining TTL among keys with expiration.

volatile‑random – evict a random key with expiration.

volatile‑lru – evict the least‑recently‑used key among those with expiration.

volatile‑lfu – evict the least‑frequently‑used key among those with expiration.

allkeys‑random – evict a random key from the entire dataset.

allkeys‑lru – evict the globally least‑recently‑used key.

allkeys‑lfu – evict the globally least‑frequently‑used key.

LRU removes the least recently accessed items; an approximate LRU samples N keys (default 5) and evicts the oldest. LFU, introduced in Redis 4.0, tracks access frequency and evicts keys with the lowest count.

14. Redis expiration strategies

Redis uses two mechanisms:

Lazy deletion – when a client accesses a key, Redis checks its TTL and deletes it if expired.

Periodic deletion – a background timer scans the expiration dictionary 10 times per second, randomly sampling 20 keys each round and deleting expired ones. If more than 25 % of the sampled keys are expired, the scan repeats.

15. Cache penetration, breakdown, and avalanche – differences and solutions

Cache penetration : Requests for non‑existent data bypass the cache and hit the database, causing overload. Solutions: cache empty objects or use a Bloom filter to filter out invalid requests.

Cache breakdown : A hot key expires, leading to a sudden surge of database traffic. Solutions: keep hot data permanently (or use logical expiration with a background refresh) or add a mutex lock to ensure only one thread rebuilds the cache.

Cache avalanche : Many keys expire simultaneously or a Redis node fails, overwhelming the database. Solutions: add random jitter to expiration times, implement degradation/fallback mechanisms, and deploy high‑availability Redis clusters (Sentinel or Cluster mode).

RedisDistributed LockIn-Memory Databaseeviction policy
Java Interview Crash Guide
Written by

Java Interview Crash Guide

Dedicated to sharing Java interview Q&A; follow and reply "java" to receive a free premium Java interview guide.

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.