Redis Caching: Use Cases, Best Practices, Common Pitfalls, and Monitoring
The article explains how Redis caching boosts high‑concurrency applications by outlining common use cases such as counters, session storage, rate limiting, leaderboards and distributed locks, then details best‑practice guidelines, typical pitfalls like TTL overwrites and cache stampedes, and essential monitoring techniques for performance and reliability.
In high‑concurrency internet applications, caching is a key component of the architecture. This article introduces typical cache scenarios, practical case analyses, Redis usage guidelines, and common Redis monitoring techniques.
Cache Comparison : Local caches such as HashMap, ConcurrentHashMap, Ehcache, Memcache, Guava Cache, and middleware caches like Redis and Tair are compared (illustrated with a diagram).
Redis Use Cases :
Counting : Fast counters for video views, live stream viewers, etc.
Session Centralization : Storing user sessions in Redis to avoid JVM memory overflow and consistency issues.
Rate Limiting : Using INCRBY for atomic increments, e.g., limiting verification code requests to 5 per minute.
Leaderboards : Leveraging SortedSet for ranking hot data such as streamer earnings.
Distributed Locks : Implementing locks with SETNX to prevent cache stampede.
Case Analyses :
Expiration Overwrite : Re‑setting a key with SET removes its TTL, which can lead to memory exhaustion.
Jedis 2.9.0 Bug : The pexpireAt call mistakenly invokes pexpire, causing excessively long expirations. The problematic code is shown below:
@Override
public Long pexpireAt(final byte[] key, final long millisecondsTimestamp) {
return new JedisClusterCommand<Long>(connectionHandler, maxAttempts) {
@Override
public Long execute(Jedis connection) {
return connection.pexpire(key, millisecondsTimestamp); // should be pexpireAt
}
}.runBinary(key);
}Cache Stampede : When many requests hit an expired key, they all fall back to the DB, overwhelming it. Solutions include using a distributed lock or proactive cache refresh via asynchronous tasks.
Standalone Redis DB Selection : Switching databases (e.g., SELECT 0 vs SELECT 1) adds CPU overhead. Keeping the connection on DB 0 avoids extra SELECT commands and improves performance.
O(N) Commands : Commands like SMEMBERS, HGETALL, LRANGE, and ZREVRANGE have linear complexity and can cause CPU spikes when the underlying collection grows.
Hot Keys : Frequently accessed keys can overload a single Redis node. Identification methods include business intuition, client‑side statistics, and proxy‑layer monitoring. Mitigation strategies: cluster expansion, key sharding, and local (L1) caching.
Redis Standards :
Do not use databases other than 0 in standalone deployments.
Key naming: use business‑prefixed, colon‑separated keys (e.g., live:rank:user:weekly:1:202003), keep length < 30 characters, and avoid special characters.
Value size: keep under 10 KB; limit collection element counts to ~1000.
Prefer O(1) commands; be cautious with O(N) commands.
Use pipelines for batch operations to reduce RTT.
Disable dangerous commands in production: MONITOR, KEYS, FLUSHALL, FLUSHDB, SAVE, BGREWRITEAOF, and avoid client‑side CONFIG changes.
Redis Monitoring :
Slow Queries : Use SLOWLOG GET or tools like CacheCloud to identify slow commands.
CPU Usage : Since Redis is single‑threaded, monitor the bound CPU core; usage >20% may indicate heavy persistence work.
Cluster Load Balancing : Check per‑shard request rates with redis-cli --stat; alert when requests exceed 120 k per second.
Big Keys : Scan with redis-cli --bigkeys or redis-memory-for-key; keys >10 KB warrant optimization.
Memory Usage : Track
used_memory_human<!--; excessive growth requires capacity planning.</li-->Conclusion : By evaluating business characteristics, sizing Redis memory appropriately, choosing suitable data structures, and adhering to the guidelines above, Redis can provide high‑performance caching that reliably supports demanding workloads.
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.
vivo Internet Technology
Sharing practical vivo Internet technology insights and salon events, plus the latest industry news and hot conferences.
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.
