Mastering Redis: From Basics to Advanced Caching Strategies
This article provides a comprehensive overview of Redis, covering its core concepts, features, data types, caching patterns in Spring Boot, common cache pitfalls and solutions, performance reasons, eviction policies, persistence options, replication, and Sentinel high‑availability mechanisms.
1. Introduction to Redis
Redis is an open‑source, high‑performance, in‑memory key‑value store written in C. It can serve as a database, cache, or message broker and belongs to the NoSQL family.
2. Redis Features
Excellent performance with in‑memory storage, supporting up to 100,000 QPS.
Single‑threaded but process‑based, thread‑safe, using I/O multiplexing.
Can be used as a distributed lock.
Supports five data types.
Provides data persistence to disk.
Can act as a message broker with publish/subscribe.
3. Data Types
The following image illustrates the five data types and their typical use cases.
4. Caching in Spring Boot
Redis is most commonly used for caching. In Spring Boot there are two typical approaches:
Directly using RedisTemplate.
Integrating Redis via Spring Cache annotations.
Problems with Caching
(1) Data Consistency
In distributed environments cache and database can become inconsistent. If strong consistency is required, avoid caching. Common mitigation strategies include cache‑update after DB writes, retry mechanisms, and asynchronous updates.
(2) Cache Avalanche
When the cache node fails, all traffic falls back to the database, potentially overwhelming it. Solutions are divided into three phases:
Before incident: high‑availability setup (master‑slave + Sentinel, clustering) to prevent total failure.
During incident: use local Ehcache, rate limiting, and graceful degradation to reduce DB pressure.
After incident: enable Redis persistence to quickly recover data from disk.
The diagram below shows the post‑avalanche data flow.
After recovery, requests first check local Ehcache, then Redis, and finally the database, synchronizing the data back to both caches.
The rate‑limiting component can restrict the number of requests per second, allowing excess requests to be degraded or return default responses.
(3) Cache Penetration
When a key does not exist in both cache and DB, repeated requests can hammer the database. Mitigations include request validation, blacklisting invalid IDs, and using a Bloom filter to quickly reject non‑existent keys.
(4) Cache Breakdown
A hot key that expires can cause a sudden surge of DB requests. Solutions depend on data change frequency:
If data rarely changes, set the key to never expire.
If updates are infrequent, use distributed or local locks to allow only one request to rebuild the cache.
If updates are frequent, employ a background thread to proactively refresh or extend the TTL before expiration.
5. Why Redis Is Fast
Uses a hash‑map‑like structure with O(1) operations, all in memory.
Simple KV data model.
Single‑threaded design avoids lock contention and context switches.
Non‑blocking I/O with multiplexing.
6. Eviction Policies
volatile‑* policies evict only expired keys.
allkeys‑* policies consider all keys.
LRU – Least Recently Used.
LFU – Least Frequently Used.
All are triggered when Redis memory reaches the configured threshold.
7. Persistence
Redis offers two persistence mechanisms:
RDB : snapshotting the in‑memory data to a dump file at intervals.
AOF : appending every write command to a log file.
RDB provides fast backup and restore, while AOF offers higher durability at the cost of write performance. Both can be enabled simultaneously; on restart Redis prefers AOF for recovery.
8. Master‑Slave Replication
Slave executes SLAVEOF [masterIP] [masterPort] to record master info.
Slave discovers master via periodic tasks and establishes a socket connection.
Ping/Pong exchange verifies connectivity.
Master sends full data set to slave for initial synchronization.
After sync, master continuously streams write commands to slaves to keep data consistent.
9. Sentinel Mode
Plain replication has drawbacks such as manual failover, limited write capacity, and potential full‑sync pauses. Sentinel adds four capabilities:
Monitoring : continuously checks health of master and slaves.
Notification : alerts administrators or applications when a server fails.
Automatic Failover : promotes a slave to master and re‑points other slaves without human intervention.
Configuration Provider : clients query Sentinel nodes to obtain the current master address.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Architect's Guide
Dedicated to sharing programmer-architect skills—Java backend, system, microservice, and distributed architectures—to help you become a senior architect.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
