Redis: choosing data structures for real problems
A hash or a JSON string for an object, a shopping cart as a hash, a queue as a list or a stream, sets for likes and mutual friends, sorted sets for leaderboards, and a case study of a ZSET delay queue that auto-cancels ride requests: why read-then-delete processed 784 duplicates out of 2,000 rides.
On this page
1. The problem
A ride nobody accepts within 10 minutes is cancelled automatically. Four workers each run ZRANGEBYSCORE to fetch due rides and only then ZREM: with 2,000 rides expiring within 1 second, 784 rides are cancelled more than once, and customers get two notifications and two refunds.
2. Key idea
Redis is a toolbox: each data type comes with commands that run atomically on the server. Stuffing everything into JSON strings is using only the hammer: with GET → edit → SET, two instances editing different fields overwrite each other.
| Type | Use when | Don't use when |
|---|---|---|
| String | serialised caches, INCR counters, SET NX PX locks |
you need to edit single fields of an object |
| Hash | objects edited by field, carts via HINCRBY cart:{u1} p100 2 |
deeply nested objects you always read whole |
| List | recent items (LPUSH + LTRIM), queues where losing a few jobs is fine |
you need acks or several consumer groups |
| Stream | acks (XACK), consumer groups, reclaiming abandoned work (XAUTOCLAIM) |
high volume, long retention on disk: Kafka, RabbitMQ |
| Set | likes, dedup (SADD returns 0 if present), mutual friends |
SINTER on two million-member sets: blocks all of Redis |
| Sorted set | leaderboards, top N, delayed queues (score = due time) | tie-breaking by time without encoding it in the score |
2.1 The two-command trap
Any "read then write" or "write then set TTL" split across two commands has a gap:
INCRthenEXPIRE: if the app dies in between, the counter lives forever and the user is blocked permanently. Combine withMULTI/EXEC, Lua, orEXPIRE key ttl NX(Redis 7) in one transaction.BRPOPremoves the element before processing: a dying consumer loses the job. A reliable queue usesBLMOVE queue processing, thenLREMwhen done.ZRANGEBYSCOREthenZREM: several workers get the same list. Claim atomically with Lua.
3. In Java
static final String CLAIM = """
local due = redis.call('ZRANGE', KEYS[1], '-inf', ARGV[1], 'BYSCORE', 'LIMIT', 0, ARGV[2])
if #due > 0 then redis.call('ZREM', KEYS[1], unpack(due)) end
return due
"""; // read and delete in ONE atomic command
@SuppressWarnings("unchecked")
List<String> claimDue(long nowMs, int batch) {
return (List<String>) redis.eval(CLAIM, List.of(KEY),
List.of(String.valueOf(nowMs), String.valueOf(batch)));
}
void cancel(String rideId) { // the DB is still the source of truth
int rows = jdbc.update("UPDATE ride SET status = 'CANCELLED' WHERE id = ? AND status = 'WAITING'", rideId);
if (rows == 1) notifier.rideCancelled(rideId); // driver already accepted: 0 rows, skip
}
// naive: duplicates=784 / 2000 atomic: duplicates=0Delayed queues: what else can break
| Delayed-queue approach | Gain | Cost |
|---|---|---|
Scan the DB WHERE status = 'WAITING' AND expires_at < now() with SKIP LOCKED |
one source of truth, nothing lost | steady DB load; fine for a few thousand jobs a minute, consider it first |
| Key TTL + keyspace notifications | no scanning | notifications are unreliable pub/sub: a lost connection loses events |
| ZSET + Lua claim | low latency, work spread across instances | you handle crashes, idempotency, a safety net |
| Broker with delay (RabbitMQ, SQS) | acks, retries | more infrastructure; cancelling a scheduled message is hard |
- Crash after claiming: the element left the ZSET and the ride sits in
WAITINGforever. Claim into aprocessingZSET (score = now + 60 seconds) instead of deleting outright, or scan the DB every 5 minutes for ridesWAITINGlonger than 11 minutes. - Lost Redis data (async failover, an accidental flush): the DB scan safety net covers this too. Redis shouldn't be the only place that knows which rides to cancel.
- Duplicate notifications: only send after a successful
UPDATE, ideally through an outbox. - A huge ZSET on Cluster is one key on one node: split into buckets
order:pending-timeout:{0..15}. - Cart hashes: a 30-day TTL extended on every edit; never store prices in the cart; a negative
HINCRBYneeds a Lua "decrement, delete the field at ≤ 0".
4. Working with AI
Delegate to AI: Lua scripts for multi-step operations, tests with many workers claiming at once, measuring MEMORY USAGE of two storage options.
Check yourself:
- No read-modify-write of JSON objects; edit fields with
HSET, or delete the cache after writing the DB. -
INCR+EXPIREandZRANGEBYSCORE+ZREMlive in one Lua script or transaction. - Queues needing acks use a Stream or a broker, not plain
BRPOP. - No
SINTER,SMEMBERS,HGETALLon collections that can grow large.
5. Exercises
Exercise 1: A monthly leaderboard with tie-breaking
You need the top 10, the current player's rank, and ties broken by who reached the score first. Max score is 100,000. Old monthly boards are kept 3 months, then deleted. AI suggests ZINCRBY lb 50 alice. Is that enough?
Solution to Exercise 1
- No: with
ZINCRBY, ties sort by member name, not by time. - Score =
points × 10^10 + (9_999_999_999 − epochSecond when reached). With points ≤ 100,000 the max score is ~10¹⁵ < 2⁵³, so a double stays exact. - Add points with Lua: read the old score, extract points (
math.floor(score / 1e10)), add, combine with the new timestamp,ZADD. - Top 10:
ZREVRANGE lb:{2026-11} 0 9 WITHSCORES; rank:ZREVRANK+ 1. Cleanup:EXPIREATat the end of the third month. With tens of millions of players keep only the top 10,000 (ZREMRANGEBYRANK) and full scores in the DB.
Exercise 2: Review an email queue that's "simple and reliable"
AI wrote the consumer String job = redis.opsForList().rightPop("mail:queue", Duration.ofSeconds(5)); send(job);, describing it as "reliable, no lost emails". During deploys a few dozen emails vanish. Why? How do you fix it?
Solution to Exercise 2
BRPOPremoves the element beforesendruns; an instance killed during a deploy between the two steps loses the job silently.- Light fix: a reliable queue with
BLMOVE mail:queue mail:processing RIGHT LEFT, thenLREM mail:processing 1 jobafter sending, plus a cleanup job requeueing elements stuck inprocessing. - Proper fix: a Stream with a consumer group,
XACKafter sending,XAUTOCLAIMto reclaim abandoned work.sendmust be idempotent since it can repeat.
Summary
- Each data type has atomic server-side commands; use them instead of read-modify-write in the app.
- Hashes for objects edited by field; JSON when you always read/write the whole object.
- Lists have no acks; need acks, use a Stream or a broker.
- Two separate commands leave a gap: combine with Lua or
MULTI/EXEC. - The DB is the source of truth; Redis has a safety net behind it.
Further reading: Reviewing a Redis distributed lock.
Practice interview questions on this topic
- What are Redis's main data types, and what problem does each one solve?
- How do pipelining, MULTI/EXEC and Lua scripts differ in Redis?
- How do you build a queue on Redis: List, Sorted Set, Pub/Sub, Streams, or should you move to Kafka?
- Caching in Spring Boot with Redis: how does @Cacheable work, and where is cache-aside in it?
- How do Redis and Memcached differ, and when do you choose each for a project?
- How do RDB and AOF differ, and can Redis be your primary data store?
Comments
Community rules