intermediate

Sorted sets

Use sorted sets for leaderboards, time windows, delayed jobs, ranking, and range queries by score.

Sorted sets (ZSET) pair each member with a numeric score — unique members ordered by score. They power leaderboards, priority queues, sliding time windows, delayed jobs, and rank/range queries.

					ZADD leaderboard 1520 user:42 980 user:7
ZREVRANK leaderboard user:42
ZRANGEBYSCORE delayed:jobs 0 1718448000 LIMIT 0 10
ZINCRBY leaderboard 50 user:42
ZREMRANGEBYSCORE sessions:active 0 1718440000
				

| Pattern | ZSET approach | |---------|---------------| | Leaderboard | Score = points; `ZREVRANGE` top N | | Delayed jobs | Score = run-at timestamp | | Rate limit window | Score = event time; trim by score | | Unique ranking | Member unique; score ties broken by Redis rules |

Range by score is O(log N + M). Updates are O(log N). For tie-breaking beyond score, encode tie data in member string or use composite scoring carefully.

On interviews: explain why a sorted set fits ranking or scheduling and how you prune old scores.

Common pitfalls: using ZSET as full document store; millions of members in one key without sharding; clock skew on timestamp scores; confusing lexicographic vs numeric range APIs.

The trade-off is ordered range queries versus memory and log-time updates — sorted sets excel when score-driven ordering is the access pattern.

Checklist:

  • Define score semantics (points, epoch ms, priority).
  • Pick range commands for read path.
  • Plan pruning (`ZREMRANGEBYSCORE`) for time windows.
  • Shard hot ZSETs when cardinality explodes.