Databases 9 min read

15 Powerful Redis Patterns for Scalable Backend Systems

This article presents fifteen practical Redis usage patterns—including caching, distributed sessions, locks, global IDs, counters, bitmaps, shopping carts, timelines, message queues, lotteries, likes, product tags, filtering, follow relationships, and ranking—illustrating how each can be implemented with commands and code snippets to build efficient, scalable backend services.

dbaplus Community
dbaplus Community
dbaplus Community
15 Powerful Redis Patterns for Scalable Backend Systems

Caching

Store hot data such as reports, popular content, object cache, or full‑page cache in Redis STRING keys. Access is O(1) and latency is sub‑millisecond.

Distributed Data Sharing

Because Redis is a standalone distributed service, the same key space can be accessed by multiple applications. A common use‑case is shared session storage with Spring Session Data Redis.

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

Distributed Lock

Implement a simple lock with SETNX (set if not exists) and an expiration to avoid dead‑locks. Release the lock with DEL.

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);
}

Global ID Generation

Use the atomic INCRBY command on an INTEGER key to generate sequential identifiers (e.g., user IDs, order numbers) without race conditions.

INCRBY user:id 1   # returns the next user ID

Counter

Increment event counters (page views, likes, etc.) with INCR. A write‑through pattern stores the count in Redis first and synchronises it to a relational database asynchronously.

INCR article:12345:views

Bitmaps (Bit Statistics)

Redis strings can be treated as bitmaps. SETBIT and GETBIT manipulate individual bits, while BITOP provides AND/OR/XOR/NOT across multiple bitmaps. This is ideal for massive binary‑state tracking such as online‑user statistics.

SET k1 a
SETBIT k1 6 1   # set the 7th bit of character 'a'
SETBIT k1 7 0   # clear the 8th bit
GET k1
BITOP AND daily_online_7days day1 day2 day3 day4 day5 day6 day7

Shopping Cart

Model a cart with a Redis HASH: key = userId, field = productId, value = quantity. Common operations: HINCRBY cart:1001 product:2002 1 – add one item HDEL cart:1001 product:2002 – remove item HGETALL cart:1001 – retrieve full cart HLEN cart:1001 – number of distinct products

User Timeline (Message Feed)

Use a Redis LIST as a double‑ended queue. New entries are appended with RPUSH; ordered retrieval is done with LRANGE (e.g., LRANGE timeline:user:1001 0 99 for the latest 100 items).

Message Queue

Redis LIST also supports blocking pop operations: BLPOP queue:tasks 5 – block up to 5 seconds for the first element (FIFO) BRPOP queue:tasks 5 – block for the last element (LIFO when combined with RPOP)

This gives a lightweight FIFO queue without external brokers.

Lottery

Store participants in a SET and draw a random winner with SPOP.

SPOP lottery:participants

Likes / Check‑in / Attendance

Maintain a SET per post (or per event). Typical commands: SADD like:post:123 user:456 – add a like SREM like:post:123 user:456 – remove a like SISMEMBER like:post:123 user:456 – test if a user liked SCARD like:post:123 – total likes SMEMBERS like:post:123 – list all users who liked

Product Tags

Each product has a tag SET (e.g., tags:product:5001). Adding tags:

SADD tags:product:5001 "high‑resolution screen"
SADD tags:product:5001 "true‑color display"

Product Filtering

Combine multiple tag sets with SINTER to find products that satisfy all criteria. Example: find Apple iPhones running iOS, with a 6.0‑6.24‑inch screen and LCD technology.

SINTER brand:apple brand:ios screensize:6.0-6.24 screentype:lcd

Follow / Recommendation Model

Represent follow relationships with two sets per user: user:follow (people the user follows) and user:fans (people who follow the user). Set operations enable simple recommendation logic:

Mutual follows: SINTER user:1:follow user:2:fans Potential connections:

SDIFF user:2:follow user:1:follow

Ranking

Use a ZSET (sorted set) to keep scores such as news click counts. Increment a score with ZINCRBY and retrieve the top N items with ZREVRANGE (descending order).

ZINCRBY hotNews:20230414 1 news:6001
ZREVRANGE hotNews:20230414 0 14 WITHSCORES

These patterns illustrate how Redis can serve as a high‑performance backbone for caching, distributed coordination, real‑time analytics, and ranking in modern backend systems.

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.

Distributed SystemsData Structures
dbaplus Community
Written by

dbaplus Community

Enterprise-level professional community for Database, BigData, and AIOps. Daily original articles, weekly online tech talks, monthly offline salons, and quarterly XCOPS&DAMS conferences—delivered by industry experts.

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.