SteelReed

Search

Search posts, questions…

4. Database & SQL

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.

18 Nov 20268 min readMid

–

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:

  • INCR then EXPIRE: if the app dies in between, the counter lives forever and the user is blocked permanently. Combine with MULTI/EXEC, Lua, or EXPIRE key ttl NX (Redis 7) in one transaction.
  • BRPOP removes the element before processing: a dying consumer loses the job. A reliable queue uses BLMOVE queue processing, then LREM when done.
  • ZRANGEBYSCORE then ZREM: several workers get the same list. Claim atomically with Lua.

3. In Java

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=0
Delayed 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 WAITING forever. Claim into a processing ZSET (score = now + 60 seconds) instead of deleting outright, or scan the DB every 5 minutes for rides WAITING longer 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 HINCRBY needs 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 + EXPIRE and ZRANGEBYSCORE + ZREM live in one Lua script or transaction.
  • Queues needing acks use a Stream or a broker, not plain BRPOP.
  • No SINTER, SMEMBERS, HGETALL on 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: EXPIREAT at 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
  • BRPOP removes the element before send runs; 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, then LREM mail:processing 1 job after sending, plus a cleanup job requeueing elements stuck in processing.
  • Proper fix: a Stream with a consumer group, XACK after sending, XAUTOCLAIM to reclaim abandoned work. send must 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

All Caching & Redis questions →

Loading comments…
Next on the roadmapSpring Boot from the inside: auto-configuration, configuration, profiles and the startup lifecycle