16 Essential Redis Patterns Every Backend Engineer Should Master
This article compiles sixteen practical Redis use‑cases—from caching and distributed locks to rate limiting, bitmaps, shopping carts, timelines, queues, likes, tags, filtering, follow/fan relationships, and leaderboards—providing code snippets and command examples to help backend developers design scalable systems.
This article presents 16 practical Redis patterns for building scalable backend services, including caching, distributed sessions, distributed locks, global ID generation, counters, rate limiting, bitmap statistics, shopping cart, user timeline, message queue, lottery, likes/check‑in/clock‑in, product tags, product filtering, follow/fan relationships, and leaderboards.
Cache
Distributed data sharing (session store)
Distributed lock
Global ID
Counter
Rate limiting
Bitmap statistics
Shopping cart
User timeline
Message queue
Lottery
Like / Check‑in / Clock‑in
Product tags
Product filtering
User follow / recommendation model
Leaderboard
1. Cache
Store hot data such as report results, popular items, or full‑page HTML in Redis strings. Reads are served from memory, dramatically reducing latency.
2. Distributed Data Sharing (Session Store)
Redis runs as a standalone distributed service, so multiple applications can share data. A common use‑case is a distributed session store. Example Maven dependency for Spring Session with Redis (escaped):
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
</dependency>3. Distributed Lock
Implement a lock with the SETNX command. If the key does not exist the command succeeds; set an expiration to avoid deadlocks.
public static boolean getLock(String key) {
Long flag = jedis.setnx(key, "1");
if (flag == 1) {
jedis.expire(key, 10); // lock expires after 10 seconds
}
return flag == 1;
}
public static void releaseLock(String key) {
jedis.del(key);
}4. Global ID
Use the atomic integer command INCRBY to generate sequential IDs across the cluster, e.g. INCRBY userid 1000 to allocate a block of IDs for sharding.
5. Counter
Simple integer counters with INCR can track page views, likes, etc. The value can be periodically persisted to a relational database.
6. Rate Limiting
Key each client (e.g., IP) with an integer counter. Increment on each request and reject when the counter exceeds a predefined threshold within a time window.
7. Bitmap Statistics
Redis bitmap commands ( SETBIT, BITCOUNT) store one‑bit flags efficiently. Example: track online users.
SET k1 a
SETBIT k1 6 1
SETBIT k1 7 0
GET k1To find users online every day for a week, use BITOP AND on the daily bitmap keys.
BITOP AND 7_days_both_online_users day_1_online_users day_2_online_users ... day_7_online_users8. Shopping Cart
Store a cart in a Redis HASH where key = userId, field = productId, value = quantity. Common operations: HINCRBY – add or increase quantity HDEL – remove a product HGETALL – list all items HLEN – count distinct products
9. User Timeline
Use a Redis LIST (doubly linked list) to store ordered timeline entries. New entries are pushed with LPUSH or RPUSH, preserving order.
10. Message Queue
Redis lists provide blocking pop operations BLPOP and BRPOP with a timeout, enabling a reliable FIFO queue. BLPOP key timeout – removes and returns the first element, blocking if the list is empty. BRPOP key timeout – removes and returns the last element, blocking if the list is empty.
11. Lottery
Use a Redis SET and the SPOP command to draw a random element.
SPOP myset12. Like / Check‑in / Clock‑in
Model likes with a set keyed by like:postId. Example commands: SADD like:t1001 u3001 – add a like SREM like:t1001 u3001 – remove a like SISMEMBER like:t1001 u3001 – test if a user liked SMEMBERS like:t1001 – list all users who liked SCARD like:t1001 – count likes
13. Product Tags
Maintain tags for a product with a set, e.g. SADD tags:i5001 "clear display". Each tag is a separate member.
14. Product Filtering
Combine attribute sets with set operations to filter products. Example: intersect brand, OS, screen size range, and screen type.
# add attributes
SADD brand:apple iPhone11
SADD brand:ios iPhone11
SADD screensize:6.0-6.24 iPhone11
SADD screentype:lcd iPhone11
# filter
SINTER brand:apple brand:ios screensize:6.0-6.24 screentype:lcd15. User Follow / Recommendation Model
Represent follow relationships with two sets per user: follow:userId (users this user follows) and fans:userId (users who follow this user). Set operations enable mutual follows, suggestions, etc.
SADD 1:follow 2 SADD 2:fans 1 SINTER 1:follow 2:fans– users I follow who also follow me (mutual). SDIFF 2:follow 1:follow – users followed by user 2 but not by user 1 (potential acquaintances).
16. Leaderboard
Use a sorted set ( ZSET) to maintain scores. Increment a member’s score with ZINCRBY and retrieve the top N with ZREVRANGE … WITHSCORES.
ZINCRBY hotNews:20190926 1 n6001 # increase click count
ZREVRANGE hotNews:20190926 0 14 WITHSCORES # top 15 itemsSigned-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
Professional architect sharing high‑quality architecture insights. Topics include high‑availability, high‑performance, high‑stability architectures, big data, machine learning, Java, system and distributed architecture, AI, and practical large‑scale architecture case studies. Open to ideas‑driven architects who enjoy sharing and learning.
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.
