Code Reference

Sorted Sets

Redis · Reference cheat sheet

Sorted Sets

Redis · Reference cheat sheet


📋 Overview

Sorted sets (ZSETs) store unique members with a floating-point score. Ideal for leaderboards, time indexes, and range queries by score or rank.

🔧 Core concepts

CommandRole
ZADD key score memberAdd/update
ZRANGEBy rank (low→high)
ZREVRANGEBy rank high→low
ZRANGEBYSCOREBy score range
ZRANK / ZREVRANKRank of member
ZSCOREScore of member
ZINCRBYIncrement score
ZREMRemove member
ZCARD / ZCOUNTCounts
Use caseScore idea
LeaderboardPoints
ScheduleUnix timestamp
Rate windowEvent time

💡 Examples

Leaderboard:

ZADD lb:game 100 alice 250 bob 180 cara
ZREVRANGE lb:game 0 2 WITHSCORES
ZINCRBY lb:game 20 alice

Due jobs by time:

ZADD queue:due 1735689600 job:1
ZRANGEBYSCORE queue:due -inf +inf LIMIT 0 10

⚠️ Pitfalls

  • Members are unique — re-ZADD updates the score.
  • Large ranges without LIMIT can return huge payloads.
  • Lexicographical commands (ZRANGEBYLEX) require same score — easy to misuse.

On this page