Skip to the page

Redis and caching · core

Redis data structures for real features

Redis is more than a cache. Choose the structure that matches the feature: sorted sets, hashes, HyperLogLog, lists and streams. Each command runs atomically.

The notes

What you must know

  • Leaderboard: a sorted set. ZADD, ZINCRBY, ZRANGE with REV, and ZREVRANK. Updates cost O(log n).
  • Fixed-window rate limit: INCR plus EXPIRE on a per-minute key, done atomically (a pipeline in MULTI, or a Lua script). The edge of the window allows a burst of double the limit.
  • Sliding-window rate limit: a sorted set of timestamps (ZADD, ZREMRANGEBYSCORE, ZCARD), or a token bucket in Lua.
  • Sessions: a hash or a string with a TTL.
  • Unique visitors: HyperLogLog (PFADD, PFCOUNT) uses at most about 12 KB per key with a standard error of 0.81%. A set is exact but uses much more memory.
  • Simple queue: a list with LPUSH and BRPOP, or LMOVE to a processing list for safety. Streams (XADD, XREADGROUP, XACK) add consumer groups and a pending list so another worker can claim work after a crash.
  • Nearby search: GEOADD and GEOSEARCH.
  • Each single command is atomic because commands run one at a time on the main thread.

The red pen

Common traps: mistake → fix

  • Mistake: Use KEYS to find a user's data

    Fix: KEYS walks the whole keyspace and blocks Redis; use SCAN or design the key.

  • Mistake: A list is a safe queue

    Fix: if a worker crashes after popping, the job is lost unless you use a processing list or Streams.

  • Mistake: A set is the way to count visitors

    Fix: at large scale it costs gigabytes; HyperLogLog costs kilobytes.

Easy to hard

Questions interviewers ask, easy to hard

  1. Which Redis structure do you use for a leaderboard?
  2. How do you build a rate limit of 100 requests a minute?
  3. How do you count unique visitors per day cheaply?
  4. What are the problems of a list as a queue?

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