Thuta Learning
Redis
BasicData & Databasesbeginner

Sorted Sets and Leaderboards

What you'll walk away with

  • Explain the core ideas behind Sorted Sets and Leaderboards
  • Run the sample Redis command or code and verify its output
  • Apply the technique correctly to the Tutorial Platform and production scenarios

Build the mental model

A sorted set keeps unique members ordered by floating-point scores. `ZINCRBY` updates scores atomically; `ZRANK` or `ZREVRANK` returns position; score or rank ranges return leaders. Define tie behavior, score precision, season rollover, and member-removal policy up front.

Connect it to a real scenario

Store weekly completed-lesson counts in `leaderboard:lessons:2026-W35` and return the top ten in descending order. PostgreSQL completion events remain the source of truth so the leaderboard can be rebuilt. If the weekly key expires, retain it longer than the reporting requirement.

Try the working example

shell
ZINCRBY leaderboard:lessons:2026-W35 1 user:42
ZINCRBY leaderboard:lessons:2026-W35 3 user:7
ZINCRBY leaderboard:lessons:2026-W35 2 user:9
ZREVRANGE leaderboard:lessons:2026-W35 0 9 WITHSCORES
ZREVRANK leaderboard:lessons:2026-W35 user:42
EXPIRE leaderboard:lessons:2026-W35 7776000
You should see
You get a weekly leaderboard with top users, scores, and user 42's rank.

5-minute try-it

Build a course-specific leaderboard and document product behavior for equal-score ties.

One important caution

Do not use sorted-set floating scores as the source of truth for money or exact decimal accounting.

Redis — Sorted SetsRedis

Easy traps

  • Do not use sorted-set floating scores as the source of truth for money or exact decimal accounting.
  • Validate sample commands on a local or test instance with recoverable data before applying them to production Redis.

Exercise

Build a course-specific leaderboard and document product behavior for equal-score ties.

You'll know it worked when: You get a weekly leaderboard with top users, scores, and user 42's rank.

Sorted Sets and Leaderboards | Thuta Learning