15 Common Redis Use Cases with Code Examples
This article presents fifteen practical Redis usage scenarios—including caching, distributed locks, leaderboards, counters, message queues, session management, bitmap sign‑ins, geolocation, rate limiting, pub/sub, delayed tasks, global IDs, recommendation models, user follow relationships, and timeline feeds—each illustrated with concise code snippets.
In daily development we often interact with Redis. This article outlines fifteen typical Redis usage scenarios, ranging from caching to distributed locks, leaderboards, counters, message queues, session management, bitmap sign‑in, geolocation, rate limiting, pub/sub, delayed tasks, global IDs, recommendation models, user follow relationships, and timeline feeds.
1. Caching
Redis is most commonly used as a cache to accelerate application response times by storing frequently accessed data in memory.
SET user:1001 "{name: 'Alice', age: 30}" EX 3600 # set 1 hour expiration2. Distributed Lock
Redis can serve as a distributed lock to coordinate access to shared resources across multiple nodes, ensuring atomic operations.
Example lock template using Redisson:
public
T executeWithLock(String lockKey, long timeout, Callable
action) {
RLock lock = redissonClient.getLock(lockKey);
boolean isLock = false;
try {
// try to acquire lock, wait max 1s, auto‑release after timeout seconds
isLock = lock.tryLock(1, timeout, TimeUnit.SECONDS);
if (isLock) {
try {
// execute the passed action and return result
return action.call();
} finally {
// release if still held
if (lock.isHeldByCurrentThread()) {
lock.unlock();
}
}
} else {
System.out.println("Failed to acquire lock, retry later");
return null; // or throw exception
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
System.out.println("Lock acquisition interrupted");
return null; // or throw exception
} catch (Exception e) {
System.out.println("Error during operation: " + e.getMessage());
return null; // or throw exception
}
}3. Leaderboard
Redis Sorted Set (ZSET) is ideal for real‑time ranking such as game scores or live‑gift leaderboards.
ZADD game_leaderboard 1000 "player_1" # add score
ZINCRBY game_leaderboard 50 "player_1" # increase score
ZREVRANGE game_leaderboard 0 9 WITHSCORES # get Top104. Counter
Redis can act as a counter for page views, likes, etc.
# User 1001 likes article 123
SADD article:123:likes 1001
# Get like count
SCARD article:123:likes
# Check if user liked
SISMEMBER article:123:likes 1001
# User 1001 unlikes
SREM article:123:likes 10015. Message Queue
Using Redis List with blocking operations (BLPOP/BRPOP) provides a simple, high‑performance message queue.
Producer adds tasks:
LPUSH task_queue "task1"
LPUSH task_queue "task2"Consumer retrieves with timeout:
BLPOP task_queue 56. Session Management
Redis is well‑suited for distributed session storage, supporting automatic expiration.
Distributed sessions: share session data across servers.
Fast expiration via EXPIRE.
HSET session:abc123 user_id 1001 last_active 1690000000
EXPIRE session:abc123 1800 # 30‑minute TTL7. Bitmap Sign‑In
Redis Bitmap efficiently records daily sign‑ins.
# Mark user 101 as signed in
SETBIT sign_in_bitmap 101 1
# Query sign‑in status
GETBIT sign_in_bitmap 101
# Count total sign‑ins
BITCOUNT sign_in_bitmap8. Geolocation Service
Redis GEO stores and queries location data, useful for finding nearby points of interest.
# Add restaurants
GEOADD restaurants 13.361389 38.115556 "RestaurantA"
GEOADD restaurants 15.087269 37.502669 "RestaurantB"
GEOADD restaurants 9.191383 45.464211 "RestaurantC"
# Find within 100 km of (14, 37)
GEORADIUS restaurants 14 37 100 km9. Rate Limiting
Redis ZSET can implement sliding‑window rate limiting.
def sliding_window_rate_limit(user_id, limit=10, window_size=60):
key = f"rate_limit:{user_id}"
current_time = int(time.time())
window_start = current_time - window_size
# Remove old entries
redis_client.zremrangebyscore(key, 0, window_start)
# Add current request timestamp
redis_client.zadd(key, {current_time: current_time})
# Count requests in window
request_count = redis_client.zcard(key)
if request_count > limit:
return False # reject
return True # allow10. Pub/Sub
Real‑time message broadcasting via Redis channels.
# Subscribe
SUBSCRIBE news_updates
# Publish
PUBLISH news_updates "Breaking: Redis 7.0 released!"11. Delayed Task
Using Sorted Set to schedule tasks for future execution.
# Add delayed task
ZADD delayed_tasks
"task_data"
# Poll for due tasks
ZRANGEBYSCORE delayed_tasks 012. Global ID
Generate unique IDs across distributed systems.
# Simple increment
INCR global_id # returns unique ID
# Snowflake‑style
SET global_id_snowflake 0
INCR global_id_snowflake13. Recommendation Model
Store recommendation scores in a Sorted Set.
ZADD recommendations:user1001 0.9 "product_1" 0.8 "product_2"
ZRANGE recommendations:user1001 0 9 WITHSCORES14. User Follow
Maintain follower/following relationships with Sets.
SADD user:1001:followers "user2"
SADD user:1002:following "user1"15. Timeline Feed
Implement a user timeline using List operations.
# Push new post to the head
LPUSH timeline:user1001 "New post: Hello, Redis!"
# Retrieve latest 10 posts
LRANGE timeline:user1001 0 9IT Services Circle
Delivering cutting-edge internet insights and practical learning resources. We're a passionate and principled IT media platform.
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.