Build the mental model
Leaderboard scores should derive from durable completion events and be applied idempotently to a sorted set. Pub/Sub is only a UI refresh hint; reconnecting clients fetch the canonical leaderboard API. Season keys, tie policy, privacy, and rebuild tooling are project requirements.
Connect it to a real scenario
Check each PostgreSQL completion ID against an idempotency record before incrementing a weekly sorted set. Publish a rank-changed hint. The API returns the top 100 and the requesting user's neighborhood; an admin rebuild constructs a fresh key from DB events and switches atomically.
Try the working example
SADD processed:completion:2026-W35 completion:9001
ZINCRBY leaderboard:2026-W35 1 user:42
ZREVRANGE leaderboard:2026-W35 0 99 WITHSCORES
ZREVRANK leaderboard:2026-W35 user:42
PUBLISH leaderboard:changed '{"season":"2026-W35","userId":42}'You get an idempotent weekly score, rank API data, and a live refresh signal.5-minute try-it
Write tests for top-three ties, deleted users, season rollover, and rebuilds during traffic.
One important caution
Separate non-atomic SADD and ZINCRBY calls can mark an event without scoring it after a crash; use a script or transaction.
Redis — Sorted Sets — Redis