Databases 11 min read

10 Real-World Redis Use Cases Every Backend Engineer Should Know

Discover ten practical Redis scenarios—from counting page visits and caching category trees to implementing distributed locks, leaderboards, rate limiting, bitmap analytics, message queues, and global ID generation—each illustrated with concise code snippets and best‑practice tips for robust backend development.

macrozheng
macrozheng
macrozheng
10 Real-World Redis Use Cases Every Backend Engineer Should Know

Redis is a high‑performance key/value cache widely used in development and interviews.

This article presents ten practical Redis scenarios with code examples and implementation tips.

1. Count page visits

Define a key such as OFFICIAL_INDEX_VISIT_COUNT and use INCR to increment the count, or INCRBY to add a larger value.

INCR OFFICIAL_INDEX_VISIT_COUNT
INCRBY OFFICIAL_INDEX_VISIT_COUNT 5

2. Retrieve category tree

Cache the JSON representation of a category tree in Redis with a key like MALL_CATEGORY_TREE. A scheduled job populates the cache, and the API reads directly from this key, avoiding expensive recursive database queries.

3. Implement distributed lock

Use Redis SET with the NX and PX options to acquire a lock atomically. Example Java code:

try{String result=jedis.set(lockKey,requestId,"NX","PX",expireTime);if("OK".equals(result)){return true;}return false;}finally{unlock(lockKey);}

Be aware of edge cases where a lock may be released unintentionally.

4. Build leaderboards

Store ranking data in a Sorted Set. Use ZADD to add scores and ZRANGE (with WITHSCORES) to retrieve the ordered list.

ZADD rank:score 100 "周星驰"
ZADD rank:score 90 "周杰伦"
ZADD rank:score 80 "周润发"
ZRANGE rank:score 0 -1 WITHSCORES
1) "周星驰"
2) "100"
3) "周杰伦"
4) "90"
5) "周润发"
6) "80"

5. Record user login status

Store a user's login information in Redis with an expiration time (e.g., 1800 seconds). Subsequent requests check this key to verify authentication.

jedis.set(userId, userInfo, 1800);

6. Rate limiting

Track request counts per IP or user ID in Redis. Increment a counter for each request and set an expiration (e.g., one day). If the count exceeds a threshold, reject the request.

7. Bitmaps for statistics

Use Redis bitmap commands to record daily user activity. SETBIT marks a user as active on a specific date; GETBIT checks the status.

SETBIT user:view:2024-01-17 123456 1
GETBIT user:view:2024-01-17 123456

Iterate over user IDs to compute weekly or monthly active user metrics.

8. Cache acceleration

Implement a read‑through cache: query Redis first; if a miss occurs, fetch from the database, store the result in Redis, and return it. Be mindful of cache‑related issues such as penetration, breakdown, and avalanche.

9. Message queue

Redis Pub/Sub can serve as a lightweight message queue. Implement a Java MessageListener to consume messages from a channel.

@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

Use INCRBY on a dedicated key to obtain atomic, incrementing identifiers, useful for sharding or batch ID allocation.

INCRBY userid 10000
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.

rediscachingBitmapMessage Queuedistributed-lockrate limitingglobal IDleaderboard
macrozheng
Written by

macrozheng

Dedicated to Java tech sharing and dissecting top open-source projects. Topics include Spring Boot, Spring Cloud, Docker, Kubernetes and more. Author’s GitHub project “mall” has 50K+ stars.

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.