Choosing Redis data structures

Caching and Redis Mid-level Python 3.13+ PostgreSQL 17+ Reviewed By Best Latest Apps

Predict the output

What does the leaderboard query print?

Python 3.13
import redis

r = redis.Redis(decode_responses=True)
r.zadd("board", {"ana": 30, "ben": 50, "cy": 40})
r.zincrby("board", 25, "ana")
print(r.zrevrange("board", 0, 1, withscores=True))

Options
Hint 1 of 1

What does ZINCRBY do to ana?

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A [('ana', 55.0), ('ben', 50.0)]

Correct. ana goes from 30 to 55 and moves to the top; scores come back as floats.

ZINCRBY adds 25 to ana's score, making it 55. Reading the sorted set from highest to lowest gives the top two, and the Python client returns scores as floats.

Why not the others?
  • B [('ben', 50.0), ('cy', 40.0)]. That ignores the ZINCRBY.
  • C [('ana', 55), ('ben', 50)]. Sorted-set scores are returned as floats.
  • D ['ana', 'ben']. withscores=True returns pairs.

30-second answer

Leaderboard: a sorted set (ZADD, ZRANGE … REV) keeps members ordered by score. Rate limiter: a string counter with INCR and EXPIRE, or a hash plus Lua for a token bucket. Session: a hash per session with a TTL. Simple queue: a list (LPUSH, BRPOP) or, with consumer groups and acknowledgement, a stream (XADD, XREADGROUP). Unique visitors: a HyperLogLog (PFADD, PFCOUNT) counts distinct items in about 12 KB with roughly 0.81% standard error.

Practise saying it · 35 s. No recording, just a timer

Pick Redis data types.

Say your answer out loud, then check which of these points you covered:

  • Sorted set: leaderboard
  • Hash + TTL: session
  • Stream: queue with acks
  • HyperLogLog: unique counts
  • Lua for atomic steps

Deep dive

Sets for membership and tags; bitmaps for per-day flags by user id.

Streams keep messages until acknowledged and trimmed, unlike pub/sub which drops messages for absent subscribers.

Pipelines and Lua scripts cut round trips and make multi-step updates atomic.

Large collections in one key are a hot spot and slow to delete (use UNLINK).

Common mistakes

  • Using lists as reliable queues without acknowledgement.
  • Storing a whole JSON document and rewriting it for each field change.
  • Counting unique visitors with a set of millions of ids.

Senior take & follow-ups

Map each use case to a type and one command, then mention atomicity.

Follow-up questions

Think of your answer first, then open the hint.

  1. Pub/sub or streams for jobs?

    Show hint

    Streams: they persist and support consumer groups and acks.

  2. How accurate is HyperLogLog?

    Show hint

    About 0.81% standard error in a fixed ~12 KB.

Suggest a fix if something here is wrong or out of date.