Skip to the page

Redis in depth · mid

Redis counting and ranking: bitmaps, HyperLogLog and sorted sets

Pick the structure by the question and the memory cost. Bitmaps and HyperLogLog count users cheaply. Sorted sets rank them, but one huge key lives on one node.

The notes

What you must know

  • Bitmap: one bit per user, with the user id as the offset (ids must be dense integers). 10 crore ids is about 12.5 MB for one day. SETBIT, GETBIT, BITCOUNT, and BITOP OR for a union over days. Set: exact and works with any id, but costs tens of bytes per member, so it does not fit large daily active sets.
  • HyperLogLog: up to about 12 KB per key at any size, with a standard error of 0.81%. PFADD, PFCOUNT, PFMERGE. It cannot tell if one user is in the set.
  • Picks: daily active users, HyperLogLog (or bitmaps if exact). A 30-day streak, a bitmap per day with GETBIT. UUIDs need a dense integer id for bitmaps.
  • Leaderboard: a sorted set. ZREVRANK for my rank, then ZRANGE with REV for rank minus 5 to rank plus 5. The top 100 is cheap and can be cached for a second or two. ZRANGE 0 -1 on a huge set returns everything: the cost grows with the number returned, and every other client on that node waits.
  • Write cost: lakhs of ZINCRBY one by one means a round trip each. Pipeline, or write in bulk from a stream job.
  • One key lives on one node, so a cluster cannot spread it. Options: replica reads, caching top N, or splitting the board into several keys and merging. Ties sort by member name, so encode a tie-breaker in the score, within a double's exact integer range.

The red pen

Common traps: mistake → fix

  • Mistake: A set per day for 10 crore users

    Fix: gigabytes of memory.

  • Mistake: HyperLogLog tells if a user was active

    Fix: it only gives a count.

  • Mistake: Add cluster nodes to speed up a big key

    Fix: one key stays on one node.

  • Mistake: Huge BITOP on a busy primary is fine

    Fix: it blocks other traffic.

Easy to hard

Questions interviewers ask, easy to hard

  1. Which structure for daily active users, and what does it cost?
  2. How do you build a streak feature?
  3. The leaderboard API is slow for 80 lakh teams. What do you look at?
  4. How do you rank a user without loading everything?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview