Unlock Redis: 12 Powerful Patterns Every Backend Engineer Should Know

Redis offers far more than simple key‑value caching; by leveraging its rich data structures—strings, hashes, lists, sets, sorted sets, bitmaps, HyperLogLog, GEO, and streams—developers can implement distributed locks, rate limiting, leaderboards, session storage, counters, geolocation, delayed queues, messaging, bloom filters, and more, all with concise commands.

Architect's Tech Stack
Architect's Tech Stack
Architect's Tech Stack
Unlock Redis: 12 Powerful Patterns Every Backend Engineer Should Know

Redis is often used merely as a cache with simple SET key value and GET key operations, but its extensive data structures enable a wide range of backend solutions without adding extra middleware.

Distributed Lock

In high‑traffic e‑commerce scenarios such as flash‑sale order placement, a distributed lock prevents overselling. A single atomic command can acquire a lock with an expiration:

// Use Lua script to ensure atomicity, combine check and delete
if redis.call("get", KEYS[1]) == ARGV[1] then
    return redis.call("del", KEYS[1])
else
    return 0
end

Compared with a separate SETNX followed by EXPIRE, the Lua script guarantees atomicity and avoids race conditions.

Rate Limiting

To protect APIs from abuse, Redis can implement a fixed‑window limiter using INCR and an expiration time:

Long count = redisTemplate.opsForValue().increment("rate:limit:" + userId);
if (count == 1) {
    // Set the window to 60 seconds on the first request
    redisTemplate.expire("rate:limit:" + userId, 60, TimeUnit.SECONDS);
}
if (count > 100) {
    // Too many requests – reject
    throw new RuntimeException("Too many requests, please slow down");
}

For finer granularity, a sliding‑window algorithm can be built with a sorted set (ZSet) that scores requests by timestamp.

Leaderboard

Sorted sets (ZSet) excel at ranking scenarios. Use ZADD to add scores, ZREVRANGE to retrieve the top entries, and ZRANK to query a specific rank.

User Sign‑In (Daily Check‑In)

Bitmaps provide an ultra‑compact way to record daily sign‑ins. Each user gets a key; each day maps to a bit position.

// Set the bit for the current day of the year
redisTemplate.opsForValue().setBit("sign:" + userId, dayOfYear, true);
// Count the total signed‑in days for the month
Long signCount = redisTemplate.opsForValue().bitCount("sign:" + userId);

3650 days of records occupy only about 512 bytes, far more efficient than storing a row per day in a relational database.

UV (Unique Visitor) Counting

HyperLogLog offers approximate distinct counting with minimal memory. Adding an IP with PFADD and retrieving the estimate with PFCOUNT yields <1 % error while using only 12 KB for 100 million elements.

Geolocation (Nearby Users, Store Locator)

Redis GEO commands store latitude/longitude as geohash strings in a sorted set. GEOADD inserts coordinates, GEODIST computes distances, and GEORADIUS finds points within a radius.

// Add a store location
redisTemplate.opsForGeo().add("stores", new Point(116.4, 39.9), "Beijing Flagship Store");
// Find stores within 3 km of the flagship
redisTemplate.opsForGeo().radius("stores", "Beijing Flagship Store", 3, RedisGeoCommands.DistanceUnit.KILOMETERS);

Delayed Queue

Sorted sets can act as a delay queue: the score is the execution timestamp, and a periodic job polls with ZRANGEBYSCORE for tasks whose score is less than the current time.

Message Queue

Lists provide a simple queue: producers LPUSH, consumers BRPOP. For advanced features like consumer groups and acknowledgments, Redis 5.0 introduced Streams, offering Kafka‑like durability and ACK mechanisms.

Bloom Filter (Cache Penetration Protection)

RedisBloom (available from Redis 4.0) implements a probabilistic filter that quickly rejects requests for non‑existent keys, reducing unnecessary database hits. Remember that false positives are possible, but false negatives never occur.

Blacklist / Whitelist

Sets handle IP blacklists and whitelists efficiently. Adding an IP with SADD blacklist ip and checking membership with SISMEMBER blocks unwanted traffic instantly.

Shopping Cart

Hashes model a user's cart: the key is cart:{userId}, fields are product IDs, and values are quantities. Commands such as HSET, HINCRBY, DEL, and HGETALL cover add, update, clear, and retrieve operations.

Publish/Subscribe

Basic real‑time notifications use PUBLISH and SUBSCRIBE. Since messages are not persisted, a service restart loses them; for reliable delivery, switch to Streams.

Pre‑Deduct Stock for Flash Sales

Atomic decrement with DECR reserves inventory. When the count reaches zero, further purchases are blocked. The actual order write‑back should be handled asynchronously, and robust fallback mechanisms are essential to recover from Redis failures.

Overall, Redis’s versatile data structures let developers replace multiple specialized middlewares with a single, well‑managed component, simplifying operations and improving reliability.

RedisCachingDistributed LockData Structuresrate limitingleaderboard
Architect's Tech Stack
Written by

Architect's Tech Stack

Java backend, microservices, distributed systems, containerized programming, and more.

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.