10 Real-World Redis Use Cases Every Backend Engineer Should Know
This article explores ten practical Redis scenarios—from counting page visits and caching category trees to implementing distributed locks, leaderboards, rate limiting, bitmap statistics, cache acceleration, message queues, and global ID generation—providing code snippets and best‑practice tips for each use case.
Preface
Redis is a high‑performance key/value cache widely used in both production and interview settings. This article shares ten real‑world Redis scenarios that can help you solve common problems efficiently.
1. Count Page Visits
Websites often need to count homepage visits. Storing a single counter in a database and aggregating later is cumbersome. Define a Redis key, e.g., OFFICIAL_INDEX_VISIT_COUNT, and use the INCR command to increment it. For larger increments, use INCRBY with the desired step.
INCR OFFICIAL_INDEX_VISIT_COUNT INCRBY OFFICIAL_INDEX_VISIT_COUNT 52. Cache Category Tree
Many sites need a category tree. Instead of recursively querying the database on each request, cache the JSON representation in Redis under a key such as MALL_CATEGORY_TREE. The API can then fetch the tree directly from Redis, avoiding multiple database hits. Beware of large keys and consider optimization strategies.
3. Implement Distributed Lock
Redis‑based distributed locks are popular due to their performance. The following Java snippet acquires a lock using SET key value NX PX expireTime. However, this simple approach can release another client’s lock in certain edge cases, so be cautious of pitfalls.
try{
String result = jedis.set(lockKey, requestId, "NX", "PX", expireTime);
if ("OK".equals(result)) {
return true;
}
return false;
} finally {
unlock(lockKey);
}4. Build Leaderboard
Leaderboards can be stored with Redis Sorted Set. Use ZADD to add scores and ZRANGE (or ZREVRANGE) to retrieve rankings.
ZADD rank:score 100 "周星驰"
ZADD rank:score 90 "周杰伦"
ZADD rank:score 80 "周润发"
ZRANGE rank:score 0 -1 WITHSCORES 1) "周星驰" 100
2) "周杰伦" 90
3) "周润发" 805. Record User Login State
After a successful login, store the user’s session information in Redis with an expiration (e.g., 30 minutes). Subsequent requests check this key to verify the user is logged in.
jedis.set(userId, userInfo, 1800)6. Rate Limiting
Redis can enforce fine‑grained rate limits, such as allowing an IP address only 10 requests per minute, 50 per ten minutes, or 100 per day. Store a counter per IP (or user ID) and increment it on each request, resetting after a configured TTL.
7. Bitmap Statistics
For tracking daily active users, Redis BITMAP offers an efficient solution. Use SETBIT to mark a user’s login on a specific date and GETBIT to query it. By iterating over dates, you can compute weekly or monthly active user metrics.
SETBIT user:view:2024-01-17 123456 1 GETBIT user:view:2024-01-17 1234568. Cache Acceleration
Typical cache‑aside pattern: query Redis first; if a hit occurs, return the data. On a miss, fetch from the database, store the result in Redis, then return it. Be aware of cache‑related issues such as penetration, breakdown, and avalanche.
9. Message Queue
Redis supports simple message queues via Pub/Sub. Producers publish to a channel, and consumers subscribed to that channel receive messages. The following Java listener demonstrates handling messages with MessageListener and deduplication using SETNX.
@Slf4j
@Component
public class RedisMessageListenerListener implements MessageListener {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
@Override
public void onMessage(Message message, byte[] pattern) {
String channel = new String(pattern);
RedisSerializer<?> valueSerializer = redisTemplate.getValueSerializer();
Object deserialize = valueSerializer.deserialize(message.getBody());
if (deserialize == null) return;
String md5DigestAsHex = DigestUtils.md5DigestAsHex(deserialize.toString().getBytes(StandardCharsets.UTF_8));
Boolean result = redisTemplate.opsForValue().setIfAbsent(md5DigestAsHex, "1", 20, TimeUnit.SECONDS);
if (Boolean.TRUE.equals(result)) {
log.info("Received result: {}", deserialize.toString());
} else {
log.info("Other service processing");
}
}
}10. Generate Global IDs
Redis can generate globally unique IDs using the atomic INCRBY command, which is useful in sharded environments where batches of IDs are needed.
INCRBY userid 10000Signed-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.
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.
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.
