Mastering Redis: Caching, Distributed Locks, Counters, and More for Scalable Backend Systems

This article explores how to leverage Redis for a wide range of backend functionalities—including caching, distributed data sharing, locks, global IDs, counters, rate limiting, bitmap statistics, shopping carts, timelines, message queues, lotteries, likes, product tagging, filtering, follow relationships, and leaderboards—providing practical code examples and usage patterns.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Mastering Redis: Caching, Distributed Locks, Counters, and More for Scalable Backend Systems

1. Cache

String type can be used for hot data caching such as reports or popular items, object caching, and full-page caching to improve access speed for frequently accessed data.

2. Distributed Data Sharing

Redis, as an independent distributed service, enables data sharing across multiple applications, e.g., distributed sessions.

<dependency>
  <groupId>org.springframework.session</groupId>
  <artifactId>spring-session-data-redis</artifactId>
</dependency>

3. Distributed Lock

Use the SETNX command to acquire a lock only when the key does not exist, returning true on success.

public static boolean getLock(String key) {
    Long flag = jedis.setnx(key, "1");
    if (flag == 1) {
        jedis.expire(key, 10);
    }
    return flag == 1;
}

public static void releaseLock(String key) {
    jedis.del(key);
}

4. Global ID

Use integer type with INCRBY for atomic increment, e.g., INCRBY userid 1000, suitable for sharding scenarios where a block of IDs is allocated at once.

5. Counter

Integer type with INCR can track metrics such as article views or likes, allowing asynchronous writes to Redis and periodic synchronization to the database.

6. Rate Limiting

Use INCR with a key composed of the visitor's IP and other attributes; each request increments the counter, and exceeding a predefined limit returns false.

7. Bitmap Statistics

String type BITCOUNT (available since Redis 1.6.6) stores characters as 8‑bit binary, enabling space‑efficient large‑scale statistics such as online user counts.

set k1 a
setbit k1 6 1
setbit k1 7 0
get k1
/* 6 and 7 modify the binary bits of 'a' (ASCII 97 = 01100001) */

Bitwise operations like AND, OR, XOR, NOT are supported via BITOP commands, e.g., calculating users online for seven consecutive days.

8. Shopping Cart

Implemented with String or Hash; each user ID is a key, product ID is a field, and the value stores quantity. Operations include HINCRBY to add, HDECRBY to subtract, HDEL to remove, HGETALL to retrieve all items, and HLEN for the number of products.

9. User Timeline

Use Redis List (a doubly linked list) to store timeline entries in order, enabling efficient insertion and retrieval.

10. Message Queue

Redis List provides blocking pop operations BLPOP and BRPOP with timeout, analogous to Java's blocking queue. Lists implement FIFO queues (push right, pop left), while using the same commands in reverse yields a LIFO stack.

11. Lottery

Use the set command SPOP to randomly draw a member from a set.

spop myset

12. Likes, Check‑in, Clock‑in

Maintain a set per post, e.g., like:t1001, to store user IDs who liked the post.

SADD like:t1001 u3001 – add a like

SREM like:t1001 u3001 – remove a like

SISMEMBER like:t1001 u3001 – check if liked

SMEMBERS like:t1001 – list all likers

SCARD like:t1001 – count likes

13. Product Tags

Use a set tags:i5001 to store all tags for a product, e.g., SADD tags:i5001 "clear display".

14. Product Filtering

Store attributes in sets (brand, OS, screen size, screen type) and compute intersections to filter products.

sadd brand:apple iPhone11
sadd brand:ios iPhone11
sadd screensize:6.0-6.24 iPhone11
sadd screentype:lcd iPhone11
sinter brand:apple brand:ios screensize:6.0-6.24 screentype:lcd

15. User Follow & Recommendation Model

Use sets to represent follow and fan relationships, enabling operations such as mutual follows, intersection for common interests, and difference to discover potential connections.

sadd 1:follow 2
sadd 2:fans 1
sinter 1:follow 2:fans   # users both follow and are fans
sdiff 2:follow 1:follow   # users followed by 2 but not by 1

16. Leaderboard

Use sorted sets to track scores, e.g., increment news click count with ZINCRBY hotNews:20190926 1 n6001 and retrieve top 15 items with ZREVRANGE hotNews:20190926 0 15 WITHSCORES.

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.

cachingBitmapbackend-developmentCountermessage-queuedistributed-lockrate-limiting
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

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.