Databases 10 min read

16 Powerful Ways to Leverage Redis in Your Applications

This article presents a comprehensive guide to 16 practical Redis use cases—including caching, distributed locks, global IDs, counters, rate limiting, bitmaps, shopping carts, timelines, message queues, lotteries, likes, product tagging, filtering, follow‑recommendation models, and ranking—complete with code snippets and data‑structure examples.

Architecture Digest
Architecture Digest
Architecture Digest
16 Powerful Ways to Leverage Redis in Your Applications

1. Cache

Redis strings are ideal for caching hot data such as reports, popular content, or full‑page HTML. Store the value with SET key value and optionally set a TTL using EXPIRE key seconds to ensure automatic eviction.

2. Distributed Data Sharing (Session Store)

Because Redis runs as an independent distributed service, multiple applications can share the same data store. A common pattern is to use Redis as a centralized session repository for Spring Boot applications.

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

3. Distributed Lock

Implement a lock with the SETNX command, which succeeds only when the key does not exist. Immediately set an expiration to avoid dead‑locks.

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

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

4. Global ID Generation

Use the atomic INCRBY command on an integer key to allocate a block of sequential IDs, which is useful for sharding scenarios.

INCRBY userid 1000   # allocate a range of 1000 IDs

5. Counter

Simple integer counters are created with INCR. Typical use cases include article view counts, likes, or any metric where occasional latency is acceptable. The counter can be flushed to a relational database later.

6. Rate Limiting

Combine INCR with a client identifier (e.g., IP address) as the key. Increment on each request and set a short TTL. If the count exceeds a predefined threshold, reject the request.

INCR ip:192.168.1.10
EXPIRE ip:192.168.1.10 60   # 1‑minute window

7. Bitmaps for Statistics

Redis strings support bit‑level operations. SETBIT and GETBIT manipulate individual bits, while BITCOUNT returns the number of set bits. This enables space‑efficient large‑scale counting such as online‑user tracking.

SET k1 a
SETBIT k1 6 1
SETBIT k1 7 0
GET k1   # returns "a"
BITCOUNT k1   # number of bits set to 1

Bitwise aggregation across multiple days can be performed with BITOP:

BITOP AND day7_online day1_online day2_online ... day7_online

8. Shopping Cart

Model a cart with a Redis hash where the hash key is the user ID, each field is a product ID, and the field value is the quantity.

Shopping cart data structure
Shopping cart data structure

Increment quantity: HINCRBY cart:12345 product:987 1 Decrement quantity: HINCRBY cart:12345 product:987 -1 Remove a product: HDEL cart:12345 product:987 Retrieve all items: HGETALL cart:12345 Count distinct products:

HLEN cart:12345

9. User Message Timeline

Use a Redis list (a doubly‑linked list) to store a chronological feed. New entries are pushed to the head with LPUSH, and the most recent N items are read with LRANGE.

10. Message Queue

Redis lists provide blocking pop operations BLPOP and BRPOP, which turn the list into a reliable FIFO or LIFO queue.

FIFO queue: RPUSH queue key + BLPOP queue timeout LIFO stack: RPUSH stack key +

BRPOP stack timeout

11. Lottery / Random Draw

Store participants in a Redis set and draw a random element with SPOP.

SPOP participants_set

12. Likes, Check‑in, Clock‑in

Model a like set with the key pattern like:{postId}. Set operations provide O(1) add, remove, membership test, and count.

Add like: SADD like:t1001 u3001 Remove like: SREM like:t1001 u3001 Check like: SISMEMBER like:t1001 u3001 All likers: SMEMBERS like:t1001 Like count:

SCARD like:t1001
Like data structure
Like data structure

13. Product Tags

Maintain tags for a product with a set named tags:{productId}. Adding a tag is a simple SADD operation.

Product tag example
Product tag example
SADD tags:i5001 "clear display"
SADD tags:i5001 "true color"
SADD tags:i5001 "smooth workflow"

14. Product Filtering

Store each attribute as a set (e.g., brand:apple, screensize:6.0-6.24). Intersect the relevant sets to obtain products that satisfy all criteria.

# Add attributes
SADD brand:apple iPhone11
SADD brand:ios iPhone11
SADD screensize:6.0-6.24 iPhone11
SADD screentype:lcd iPhone11

# Query products that match all attributes
SINTER brand:apple brand:ios screensize:6.0-6.24 screentype:lcd
Product filtering example
Product filtering example

15. User Follow & Recommendation Model

Model follow relationships with two sets per user: {userId}:follow (users this user follows) and {userId}:fans (followers). Set operations enable mutual‑follow detection, recommendation of potential acquaintances, and other graph analyses.

Follow: SADD 1:follow 2 Fans: SADD 2:fans 1 Mutual follow (intersection): SINTER 1:follow 2:fans Potential acquaintances (difference):

SDIFF 2:follow 1:follow

16. Ranking / Leaderboard

Use a sorted set to maintain a leaderboard. Increment a member’s score with ZINCRBY and retrieve the top N entries with ZREVRANGE (descending order).

# Increment click count for news item 6001
ZINCRBY hotNews:20190926 1 n6001

# Get the top 15 items for today
ZREVRANGE hotNews:20190926 0 14 WITHSCORES
Ranking example
Ranking example
CachedatabaseRedisMessage QueueDistributed LockData Structuresleaderboard
Architecture Digest
Written by

Architecture Digest

Focusing on Java backend development, covering application architecture from top-tier internet companies (high availability, high performance, high stability), big data, machine learning, Java architecture, and other popular fields.

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.