Leaderboard and top-k
Every score moves a player, and every player wants to see their rank at once. The design question is how to keep a sorted order of millions of players under constant change.
- 1A sorted set answers a rank in O(log n), because each skip-list link stores how many members it skips. SQL reads one row per player above.
- 2Postgres holds the truth and removes repeats. Redis takes totals with ZADD GT, so a repeat or a late write changes nothing, and a rebuild is always possible.
- 3One node goes far: 77.7 bytes a player and about 88k ranks a second. Shard for memory or writes, not for rank reads.
- 4Time windows are separate boards keyed by the event's own time. Anti-cheat is a stage before the board, so a bad score never appears.
Design a leaderboard that ranks millions of players, updated on every score, with rank queries in real time.
| question | answer assumed |
|---|---|
| How many players? | 10 million on the all-time board; 5 million active each day. |
| How does a score change? | Points add up. Scores never fall, except after a ban. |
| Who produces a score? | The game server, never the client. |
| What does a player see? | Their rank, 2 neighbours on each side, and the top 100. |
| What do ties mean? | Tied players share a rank. Prizes use the first to reach the score. |
| Which windows? | All time, daily and weekly, in UTC. |
| Exact, or close? | Exact for the top and for a player's own rank. |
I confirm how many players, what a rank means when scores tie, and which time windows the product needs.
| functional |
|---|
| Record a score from a finished match. |
| Read a player's rank and neighbours. |
| Read the top k, for each window. |
| Remove a banned player. |
| non-functional | target |
|---|---|
| Rank read latency | p99 < 10 ms |
| Score to board | p99 < 1 s |
| A retried score | Counts once |
| Redis lost | Rebuild in about a minute, no score lost |
| Availability | 99.9% |
A score must show within a second, and a rank read must take milliseconds. The total must never be wrong, even after a crash.
| quantity | arithmetic | result |
|---|---|---|
| Scores | 5 M players × 10 a day = 50 M ÷ 86,400 | ≈ 579/s; 3× peak ≈ 1,736/s |
| Rank reads | one per score + 5 M × 4 views = 70 M ÷ 86,400 | ≈ 810/s; 3× peak ≈ 2,431/s |
| All-time board | 10 M × 77.7 B (measured) | ≈ 0.78 GB |
| Day and week boards | 2 × 5 M × 77.7 B | ≈ 0.78 GB; 1.6 GB in all |
| Totals table | 10 M × 151 B (measured, with indexes) | ≈ 1.5 GB |
| Event log | 50 M × 100 B (assumed row) | 5 GB a day; keep 90 days |
| Rebuild | 10 M ÷ 314k players a second (measured) | ≈ 32 s |
Inputs are the assumed answers in panel A. Rates and bytes per player are measured in the lab, panel L. Method: R2.
Peak is about 1,700 scores and 2,400 rank reads a second, on about 1.6 GB. That fits one Redis node with room to spare.
| call | for | retry safe by | success | errors |
|---|---|---|---|---|
| POST /v1/scores {event_id, player_id, points, at, signature} | a match result, from a game server | the event ID | 202 | 400, 401 bad signature |
| GET /v1/boards/{window}/top?k=100 | the top k | a read | 200 + players | 400 k too large |
| GET /v1/boards/{window}/players/{id}?around=2 | rank and neighbours | a read | 200 + rank, place, near | 404 not on this board |
| DELETE /v1/boards/players/{id} | a ban, from a staff tool | DELETE is idempotent | 204 | 403 |
- A window is all, day:2026-10-31 or week:2026-W44.
- POST returns 202, not 200: the score is in the log, and the board shows it within a second.
A score carries an event ID, so a retry counts once. A rank read is one GET that returns the rank and the neighbours together.
| Redis key | holds | lives |
|---|---|---|
| lb:all | Sorted set: player, total score | Always |
| lb:day:20261031 | Sorted set: points of that UTC day | 8 days |
| lb:week:2026-W44 | Sorted set: points of that ISO week | 35 days |
| lb:hist | Hash: bucket, player count | Optional; panel K |
CREATE TABLE scores (
player_id bigint PRIMARY KEY,
score bigint NOT NULL1,
updated_at timestamptz2 NOT NULL DEFAULT clock_timestamp()
);
CREATE TABLE score_events (
event_id text PRIMARY KEY3,
player_id bigint NOT NULL,
delta bigint NOT NULL CHECK (delta > 0),
at timestamptz NOT NULL4
);
CREATE INDEX scores_rank5 ON scores (score DESC, player_id DESC);- 1The total. A worker adds to it in the same statement that stores the event.
- 2A rebuild copies rows changed since it started, so live scores are not lost.
- 3A repeat of an event hits this key and adds nothing.
- 4The time of the match, not of the write. It picks the window, so a late event lands in the right day.
- 5Makes top-k and neighbour reads cheap. It does not make a rank cheap, because a B-tree keeps no counts.
Postgres holds one total per player and every event. Redis holds one sorted set per window, and a rebuild can recreate any of them.
Step 1: Score
- The game server signs the match result. The client never sends a score.
- The API appends an event with its own ID to the log, keyed by player.
- It returns 202. The board moves within a second.
If it fails
The API retries after a timeout: the event ID is the same, so the worker ignores the repeat.
A score goes through the log and the anti-cheat stage. A worker commits it in Postgres, then writes the total to Redis. Rank reads touch only Redis.
| tool | capability | what it gives this design | also used for |
|---|---|---|---|
| Redis | Sorted set: ZREVRANK | A place in O(log n), at any depth of the board. | Percentiles, sliding windows |
| Redis | ZCOUNT with an open range | A shared rank for ties, O(log n) however many players are above. | Rate limit windows |
| Redis | ZREVRANGE WITHSCORES | The top k, and the neighbours by position. O(log n + k). | Timelines, delay queues |
| Redis | ZINCRBY | Adds points in O(log n). A retry counts twice. | Counters by key |
| Redis | ZADD GT | Writes a total only if it is higher, so repeats and late writes do nothing. | High-water marks |
| Redis | Lua scripts | Rank, score and neighbours from one point in time, in one round trip. | Locks, rate limits |
| Redis | RENAME | A rebuilt board replaces the old one in one step. | Any full cache reload |
| Redis | ZUNIONSTORE | Builds a week from 7 days in a job: 700,000 players in about 1.2 s. | Merged rankings |
| Redis | Scores are float64 | Limit Exact only to 2^53, which caps score and tie-break bits together. | |
| Postgres | INSERT ON CONFLICT DO NOTHING | Removes repeats by event ID, and returns only the new rows. | Idempotency keys, inbox tables |
| Postgres | Data-changing CTE | The event and the new total commit in one statement. | Ledgers, counters |
| Postgres | Index on (score DESC, player_id DESC) | Top k and neighbours as short index ranges. | Any ordered page |
| Kafka | Partitioned log keyed by player | One worker per player at a time, and redelivery after a crash. | Feeds, stream jobs |
| Service | Space-Saving sketch | Finds the fastest players in fixed memory. | Hot keys, top-k queries |
Sorted sets give me rank and range in O(log n). Postgres gives me a total that a retry cannot corrupt.
| method | status | cost of one rank |
|---|---|---|
| SQL RANK() per query | Not approved | Numbers every row: 17 queries a second |
| SQL count of higher scores | Small board | One entry per player above: 129 a second at the median |
| Rank table, batch refresh | Stale rank is fine | Cheap to read; old until the next run |
| Redis sorted set | Approved | O(log n): 30k a second from 8 clients |
| Score buckets | Close is fine | No network call; panel K |
- A B-tree finds a row in O(log n), but it stores no count of the rows before it. A rank then walks them.
- ZCOUNT stays O(log n) for the same reason as ZREVRANK: it subtracts two ranks.
- Top-k reads are cheap in both stores. The rank of a player deep in the board is what separates them.
Lab: seeded log-normal scores, 1,000,000 players, median 2,986, top 789,521. Redis complexity from the command documentation.
update(player, points):
ZINCRBY lb:all points player // O(log n); the set stays sorted
standing(player, k): // one script: one point in time1
place = ZREVRANK lb:all player // O(log n); 0-based
score = ZSCORE lb:all player
above = ZCOUNT lb:all (score +inf // O(log n), not O(above)2
near = ZREVRANGE lb:all place-k place+k3 WITHSCORES
RETURN place + 1, above + 1, near
top(k):
ZREVRANGE lb:all 0 k-1 WITHSCORES // O(log n + k)- 1Three separate calls could see three different boards. A script runs as one step.
- 2The documentation states this directly: ZCOUNT uses element ranks to get the size of the range.
- 3Neighbours by position, so ties cause no special case. The lab checks them against a sort.
Tested source Go: add, top, standing · Lua: one standing · SQL: two rank queries
// Add adds points to a player: ZINCRBY, O(log n). A retried call counts twice, so only a path that
// removes repeats first may use it.
func (b Board) Add(ctx context.Context, id int, delta int64) (int64, error) {
s, err := b.RDB.ZIncrBy(ctx, b.Key, float64(delta), Member(id)).Result()
if err != nil {
return 0, fmt.Errorf("zincrby %s: %w", b.Key, err)
}
return int64(s), nil
}
// Top returns the first k players: ZREVRANGE, O(log n + k).
func (b Board) Top(ctx context.Context, k int) ([]Player, error) {
zs, err := b.RDB.ZRevRangeWithScores(ctx, b.Key, 0, int64(k)-1).Result()
if err != nil {
return nil, fmt.Errorf("zrevrange %s: %w", b.Key, err)
}
return toPlayers(zs)
}
// Standing is one player's place on a board, with the players near them.
type Standing struct {
Place int64 `json:"place"` // unique, 1-based
Rank int64 `json:"rank"` // shared by ties
Score int64 `json:"score"`
First int64 `json:"first"` // the place of Near[0]
Near []Player `json:"near"`
}
// Standing runs ZREVRANK, ZCOUNT and ZREVRANGE in one script, so all three see the same board. A
// player who is not on the board gets ErrNoPlayer.
func (b Board) Standing(ctx context.Context, id, k int) (Standing, error) {
raw, err := standingScript.Run(ctx, b.RDB, []string{b.Key}, Member(id), k).Slice()
if errors.Is(err, redis.Nil) {
return Standing{}, ErrNoPlayer
}
if err != nil {
return Standing{}, fmt.Errorf("standing of %d: %w", id, err)
}
return parseStanding(raw)
}
-- KEYS[1]: the board. ARGV[1]: the player. ARGV[2]: neighbours on each side.
-- Returns one player's standing from one point in time, in one round trip.
local pos = redis.call('ZREVRANK', KEYS[1], ARGV[1])
if not pos then return false end
local score = redis.call('ZSCORE', KEYS[1], ARGV[1])
local above = redis.call('ZCOUNT', KEYS[1], '(' .. score, '+inf')
local first = math.max(pos - tonumber(ARGV[2]), 0)
local near = redis.call('ZREVRANGE', KEYS[1], first, pos + tonumber(ARGV[2]), 'WITHSCORES')
return {pos, above, score, first, near}
SELECT rank FROM (
SELECT player_id, RANK() OVER (ORDER BY score DESC) AS rank
FROM scores
) ranked
WHERE player_id = $1;
SELECT 1 + count(*) FROM scores WHERE score > $1;On 1,000,000 players, RANK() took 362 ms and grew with the table. ZREVRANK took 151 µs and stayed flat, because the skip list stores counts.
| tie rule | status | how |
|---|---|---|
| Member name order | Not approved | The default of ZREVRANK. It means nothing to a player. |
| Shared rank: 1, 2, 2, 4 | Approved | 1 + ZCOUNT of the scores strictly above |
| First to reach it wins | Prizes | Time in the low bits of the score |
| Fraction of a point for time | Not approved | Bits vanish as the score grows; a float64 has 53 exact bits |
// shared rank: 1, 2, 2, 4
rank(score) = 1 + ZCOUNT lb:all (score +inf
// unique place: Redis breaks ties by member name
place(player) = 1 + ZREVRANK lb:all player
// first to reach the score ranks higher
encode(score, second) =
score << 221 | (2^22 - 1 - second2) // 53 bits in a float64
decode(v) = v >> 22, 2^22 - 1 - low 22 bits- 122 bits of seconds cover about 48 days, one season. The score keeps 31 bits.
- 2An earlier second gives a larger number, so the first to reach a score ranks higher.
Tested source Go: encode, decode
// TimeBits holds the tie-break: 2^22 seconds is about 48 days, one season. The score then has 31
// bits, because a sorted-set score is a float64 with 53 exact bits.
const TimeBits = 22
// MaxScore is the largest score that Encode keeps exact.
const MaxScore = int64(1)<<(53-TimeBits) - 1
// Encode packs a score and the second it was reached (from the season start) into one float64.
// An earlier second gives a larger number, so of two equal scores the first to reach it ranks higher.
func Encode(score, second int64) float64 {
return float64(score<<TimeBits | (1<<TimeBits - 1 - second))
}
// Decode returns the score and the second.
func Decode(v float64) (score, second int64) {
n := int64(v)
return n >> TimeBits, 1<<TimeBits - 1 - n&(1<<TimeBits-1)
}
Lab: 98.4% of players share a score; the largest tie holds 262 players. The median player has rank 499,940 and place 500,000.
| window method | status | cost |
|---|---|---|
| One board per window, written on each score | Approved | 3 ZINCRBY in one round trip |
| Week from 7 days, ZUNIONSTORE | A job, not a read | About 1.2 s for 700,000 players |
| WHERE at > ... per read | Not approved | Sums a window of events for each query |
| Rolling 24 hours | Product needs it | Hourly boards merged by a job; the board lags up to an hour |
score(player, points, at): // at = the event's own time1
IN ONE ROUND TRIP:
ZINCRBY lb:all points player
ZINCRBY lb:day:{date(at)} points player
ZINCRBY lb:week:{week(at)} points player
EXPIRE lb:day:{date(at)} 8 days2
EXPIRE lb:week:{week(at)} 35 days
repair(day) after it closes3:
totals = SUM(delta) per player FROM score_events IN day
write totals to a new key
RENAME the new key over the board- 1A late event lands in the day it was played, so a retry across midnight does no harm.
- 2Old boards remove themselves. Nothing has to run for memory to stay flat.
- 3ZINCRBY can lose points in a crash. The event log can always restate a window.
Tested source Go: window boards · SQL: window totals
// DayKey and WeekKey name the boards of the UTC day and the ISO week that hold t.
func DayKey(t time.Time) string { return "lb:day:" + t.UTC().Format("20060102") }
// WeekKey is the board of one ISO week.
func WeekKey(t time.Time) string {
y, w := t.UTC().ISOWeek()
return fmt.Sprintf("lb:week:%d-W%02d", y, w)
}
// AllKey is the all-time board.
const AllKey = "lb:all"
// Windows writes each score to the all-time, day and week boards in one round trip.
type Windows struct {
RDB *redis.Client
}
// Score adds points to every board that holds the event's time. The event's own time picks the
// boards, so a late event lands in the window it belongs to. Old boards expire on their own.
func (w Windows) Score(ctx context.Context, id int, delta int64, at time.Time) error {
day, week := DayKey(at), WeekKey(at)
_, err := w.RDB.Pipelined(ctx, func(p redis.Pipeliner) error {
for _, key := range []string{AllKey, day, week} {
p.ZIncrBy(ctx, key, float64(delta), Member(id))
}
p.Expire(ctx, day, 8*24*time.Hour)
p.Expire(ctx, week, 35*24*time.Hour)
return nil
})
if err != nil {
return fmt.Errorf("score %d: %w", id, err)
}
return nil
}
// MergeWeek builds a week board from its 7 day boards with ZUNIONSTORE, which sums the scores of a
// player. The cost is O(n) + O(m log m), so it suits a job, not the read path.
func (w Windows) MergeWeek(ctx context.Context, dst string, monday time.Time) (int64, error) {
keys := make([]string, 7)
for i := range keys {
keys[i] = DayKey(monday.AddDate(0, 0, i))
}
n, err := w.RDB.ZUnionStore(ctx, dst, &redis.ZStore{Keys: keys, Aggregate: "SUM"}).Result()
if err != nil {
return 0, fmt.Errorf("merge week into %s: %w", dst, err)
}
return n, nil
}
SELECT player_id, sum(delta)::bigint FROM score_events
WHERE at >= $1 AND at < $2
GROUP BY player_id;98% of the seeded players share their score, so ties are the normal case. I show a shared rank, and I use a packed score only where the first to reach it must win.
| write path | status | after a retry |
|---|---|---|
| ZINCRBY only, no truth | Not approved | Counts twice, and no record shows it |
| Redis persistence alone | Scores can be lost | Same; a failover can also drop recent writes |
| Postgres event ID, then ZADD GT | Approved | No change; a crash heals on redelivery |
apply(batch from the log):
IN ONE POSTGRES STATEMENT:
INSERT events ON CONFLICT (event_id) DO NOTHING1
add the new deltas to scores // a repeat adds nothing
totals = read scores of these players
ZADD lb:all GT total player // never moves a score down2
rebuild():
start = now
copy every row of scores to lb:all:next
RENAME lb:all:next lb:all3 // readers switch at once
ZADD GT every row changed since start - 5 s4- 1The repeat stops here, so the total adds it once. Only rows that are new reach the sum.
- 2Two workers can read totals in one order and write them in the other. GT drops the older one.
- 3Readers keep the old board until this one command. There is no empty moment.
- 4A worker can write to the old key during the copy. Its row has a new timestamp, so it comes back here.
Tested source Go: apply · SQL: apply · Go: rebuild
// Apply stores a batch of events and copies the new totals to the board. Postgres removes repeats
// with the event's ID. The board takes each total with ZADD GT, so a repeat changes nothing and an
// older total never replaces a newer one.
func (w *Worker) Apply(ctx context.Context, events []Event) error {
ids, players, deltas, ats := make([]string, len(events)), make([]int64, len(events)), make([]int64, len(events)), make([]time.Time, len(events))
seen := map[int64]bool{}
var touched []int64
for i, e := range events {
ids[i], players[i], deltas[i], ats[i] = e.ID, int64(e.Player), e.Delta, e.At
if !seen[players[i]] {
seen[players[i]] = true
touched = append(touched, players[i])
}
}
if _, err := w.DB.Exec(ctx, sqls["apply"], ids, players, deltas, ats); err != nil {
return fmt.Errorf("apply events: %w", err)
}
if w.AfterCommit != nil {
if err := w.AfterCommit(); err != nil {
return err
}
}
rows, err := w.DB.Query(ctx, sqls["totals"], touched)
if err != nil {
return fmt.Errorf("read totals: %w", err)
}
return w.Board.copyGreater(ctx, rows)
}
// copyGreater reads player and score rows and writes them with ZADD GT, in batches of 1,000.
func (b Board) copyGreater(ctx context.Context, rows pgx.Rows) error {
defer rows.Close()
batch := make([]redis.Z, 0, 1000)
flush := func() error {
if len(batch) == 0 {
return nil
}
err := b.RDB.ZAddArgs(ctx, b.Key, redis.ZAddArgs{GT: true, Members: batch}).Err()
batch = batch[:0]
if err != nil {
return fmt.Errorf("zadd gt %s: %w", b.Key, err)
}
return nil
}
for rows.Next() {
var id, score int64
if err := rows.Scan(&id, &score); err != nil {
return fmt.Errorf("scan total: %w", err)
}
batch = append(batch, redis.Z{Score: float64(score), Member: Member(int(id))})
if len(batch) == cap(batch) {
if err := flush(); err != nil {
return err
}
}
}
if err := rows.Err(); err != nil {
return fmt.Errorf("read rows: %w", err)
}
return flush()
}
WITH fresh AS (
INSERT INTO score_events (event_id, player_id, delta, at)
SELECT * FROM unnest($1::text[], $2::bigint[], $3::bigint[], $4::timestamptz[])
ON CONFLICT (event_id) DO NOTHING
RETURNING player_id, delta
)
INSERT INTO scores AS s (player_id, score)
SELECT player_id, sum(delta) FROM fresh
GROUP BY player_id
ORDER BY player_id
ON CONFLICT (player_id) DO UPDATE
SET score = s.score + EXCLUDED.score, updated_at = clock_timestamp();
// Margin is longer than any scoring transaction. A row that committed during the copy has an
// updated_at no older than the start time minus this margin.
const Margin = 5 * time.Second
// Rebuild writes a new board from Postgres under a second key, swaps it in with RENAME, then
// copies every row that changed since the start. Readers see the old board until the swap, and
// live writes that landed on the old board come back in the last step.
func Rebuild(ctx context.Context, db *pgxpool.Pool, b Board) (int, error) {
var start time.Time
if err := db.QueryRow(ctx, "SELECT clock_timestamp()").Scan(&start); err != nil {
return 0, fmt.Errorf("read the start time: %w", err)
}
next := Board{RDB: b.RDB, Key: b.Key + ":next"}
if err := b.RDB.Del(ctx, next.Key).Err(); err != nil {
return 0, fmt.Errorf("clear %s: %w", next.Key, err)
}
rows, err := db.Query(ctx, sqls["snapshot"])
if err != nil {
return 0, fmt.Errorf("read scores: %w", err)
}
if err := next.copyGreater(ctx, rows); err != nil {
return 0, err
}
if err := b.RDB.Rename(ctx, next.Key, b.Key).Err(); err != nil {
return 0, fmt.Errorf("swap %s: %w", b.Key, err)
}
rows, err = db.Query(ctx, sqls["changed"], start.Add(-Margin))
if err != nil {
return 0, fmt.Errorf("read changes: %w", err)
}
if err := b.copyGreater(ctx, rows); err != nil {
return 0, err
}
n, err := b.RDB.ZCard(ctx, b.Key).Result()
if err != nil {
return 0, fmt.Errorf("zcard %s: %w", b.Key, err)
}
return int(n), nil
}
// RebuildWindow writes one window board from the event log. A window board takes ZINCRBY, so a
// crash can leave it behind. This repairs it, and it runs after a day closes.
func RebuildWindow(ctx context.Context, db *pgxpool.Pool, b Board, from, to time.Time) (int, error) {
next := Board{RDB: b.RDB, Key: b.Key + ":next"}
if err := b.RDB.Del(ctx, next.Key).Err(); err != nil {
return 0, fmt.Errorf("clear %s: %w", next.Key, err)
}
rows, err := db.Query(ctx, sqls["window_totals"], from, to)
if err != nil {
return 0, fmt.Errorf("read window: %w", err)
}
if err := next.copyGreater(ctx, rows); err != nil {
return 0, err
}
if err := b.RDB.Rename(ctx, next.Key, b.Key).Err(); err != nil {
return 0, fmt.Errorf("swap %s: %w", b.Key, err)
}
n, err := b.RDB.ZCard(ctx, b.Key).Result()
if err != nil {
return 0, fmt.Errorf("zcard %s: %w", b.Key, err)
}
return int(n), nil
}
The lab stops a worker between the commit and the Redis write, then redelivers. It also rebuilds 30,000 players with 4 workers writing, and compares every total with Postgres.
| check | catches | status |
|---|---|---|
| Signed result from the game server | Forged requests | Approved |
| Score above the most a match can give | Impossible scores | Approved |
| Too many events in a batch | Bots | Approved |
| Replay of the match on a server | Skilled cheats | High prizes |
| Review after the board shows it | Everything, late | Not approved |
screen(batch):
sketch = 256 counters, Space-Saving1
FOR EACH event: sketch.add(player)
fast = players whose count - error > 3002 in this batch
FOR EACH event:
IF delta > 1,000: reject // impossible score
ELSE IF player in fast: hold for review3
ELSE: accept- 1Fixed memory, whatever the number of players. The full method is on sheet B10.
- 2Count minus error is a lower bound on the true count, so a sketch error never holds an honest player.
- 3Held events wait in a review queue. A person or a slower model decides, and accepted events then go through the same worker.
Tested source Go: the stage
// Stage is the check that events pass before they reach the board. It works on one batch from the
// log at a time.
type Stage struct {
MaxDelta int64 // the most one match can score; above it the event is impossible
RateLimit int64 // the most events one player can have in a batch
Counters int // the size of the sketch that counts events per player
}
// Screened is the result of one batch.
type Screened struct {
Accepted []Event
Held []Event // kept for review, not on the board
Rejected []Event
}
// Screen rejects impossible scores and holds every event of a player who plays too fast. The
// Space-Saving sketch counts players in fixed memory. Count minus Err is a lower bound on the true
// count, so an honest player is never held by a sketch error.
func (s Stage) Screen(batch []Event) Screened {
table := sketches.NewSpaceSaving(s.Counters)
for _, e := range batch {
table.Add(strconv.Itoa(e.Player))
}
fast := map[string]bool{}
for _, it := range table.Top(s.Counters) {
if int64(it.Count-it.Err) > s.RateLimit {
fast[it.Key] = true
}
}
var out Screened
for _, e := range batch {
switch {
case e.Delta > s.MaxDelta:
out.Rejected = append(out.Rejected, e)
case fast[strconv.Itoa(e.Player)]:
out.Held = append(out.Held, e)
default:
out.Accepted = append(out.Accepted, e)
}
}
return out
}
- stream
- 136,040 events, 10,000 honest players, 5 cheaters.
- top 10
- 5 cheaters without the stage; 0 with it.
- stopped
- 36,000 events held, 40 rejected, 0 honest events among them.
- top-k
- 1,000 counters found 85 of the 100 most active players.
The worker writes totals, not increments, so a retry is harmless. If Redis loses the board, Postgres rebuilds it while scores keep arriving.
| design | top k | rank | score change | status |
|---|---|---|---|---|
| Hash shards, scatter-gather | All shards | All shards | One shard | Write heavy |
| Range shards, quantile cuts | Top shard | Sizes, then one shard | Moves at a cut | Read heavy |
| Range shards, equal widths | Top shard | Sizes, then one shard | Moves at a cut | Not approved |
| Exact top, buckets below | One small set | Approximate | 2 HINCRBY | Close is fine |
| Read replicas of one node | One replica | One replica | Primary only | Reads only; memory stays |
// hash shards: each player has one home
top(k): ask EVERY shard for its top k1, merge, keep k
rank(s): 1 + SUM over shards of ZCOUNT2 (s +inf
// range shards: each score range has one home
top(k): read the first shard, walk down only if short3
rank(s): 1 + ZCARD of each shard above + ZCOUNT in s's shard
move(p): ZADD on the new shard4, then ZREM on the old one- 1The top k does not spread evenly. Asking for 12 each found only 85 of the true top 100.
- 2Each count is O(log n), but a read costs one command per shard, so a rank read gets more expensive.
- 3Of 8 shards, a top 100 reads one. Cuts must sit on quantiles, or one shard holds nearly everyone.
- 4Add first, then remove. A read in the gap counts the player twice, which is better than losing them.
Tested source Go: scatter-gather · Go: score ranges
// Top asks every shard for its own top k and merges them. A player in the true top k is in the top
// k of their shard, so the merge is exact. Asking each shard for fewer than k is not.
func (h *HashBoard) Top(ctx context.Context, k int) ([]Player, error) {
return h.TopEach(ctx, k, k)
}
// TopEach merges the top each players of every shard and keeps k.
func (h *HashBoard) TopEach(ctx context.Context, each, k int) ([]Player, error) {
lists := make([][]Player, len(h.Shards))
err := gather(len(h.Shards), func(i int) error {
var err error
lists[i], err = h.Shards[i].board().Top(ctx, each)
return err
})
if err != nil {
return nil, err
}
merged := slices.Concat(lists...)
slices.SortFunc(merged, byBoardOrder)
return merged[:min(k, len(merged))], nil
}
// Rank sums ZCOUNT (score +inf over every shard: one O(log n) count per shard.
func (h *HashBoard) Rank(ctx context.Context, score int64) (int64, error) {
counts := make([]int64, len(h.Shards))
err := gather(len(h.Shards), func(i int) error {
var err error
counts[i], err = h.Shards[i].RDB.ZCount(ctx, h.Shards[i].Key, "("+strconv.FormatInt(score, 10), "+inf").Result()
return err
})
if err != nil {
return 0, fmt.Errorf("rank of %d: %w", score, err)
}
var rank int64 = 1
for _, c := range counts {
rank += c
}
return rank, nil
}
// Move changes a player's score. A score that crosses a cut adds the player to the new shard, then
// removes them from the old one. A read in the gap can count the player twice, never zero times.
func (r *RangeBoard) Move(ctx context.Context, id int, from, to int64) error {
a, b := r.ShardOf(from), r.ShardOf(to)
if err := r.Shards[b].RDB.ZAdd(ctx, r.Shards[b].Key, redis.Z{Score: float64(to), Member: Member(id)}).Err(); err != nil {
return fmt.Errorf("add to %s: %w", r.Shards[b].Key, err)
}
if a == b {
return nil
}
if err := r.Shards[a].RDB.ZRem(ctx, r.Shards[a].Key, Member(id)).Err(); err != nil {
return fmt.Errorf("remove from %s: %w", r.Shards[a].Key, err)
}
return nil
}
// sizes reads ZCARD of the shards before upTo.
func (r *RangeBoard) sizes(ctx context.Context, upTo int) ([]int64, error) {
out := make([]int64, upTo)
err := gather(upTo, func(i int) error {
var err error
out[i], err = r.Shards[i].RDB.ZCard(ctx, r.Shards[i].Key).Result()
return err
})
return out, err
}
// Rank adds the sizes of the shards above to a count in the score's own shard.
func (r *RangeBoard) Rank(ctx context.Context, score int64) (int64, error) {
at := r.ShardOf(score)
sizes, err := r.sizes(ctx, at)
if err != nil {
return 0, fmt.Errorf("sizes: %w", err)
}
here, err := r.Shards[at].RDB.ZCount(ctx, r.Shards[at].Key, "("+strconv.FormatInt(score, 10), "+inf").Result()
if err != nil {
return 0, fmt.Errorf("zcount: %w", err)
}
rank := 1 + here
for _, s := range sizes {
rank += s
}
return rank, nil
}
// Top walks down from the first shard until it has k players. Most reads stop at the first shard.
func (r *RangeBoard) Top(ctx context.Context, k int) ([]Player, error) {
var out []Player
for _, s := range r.Shards {
part, err := s.board().Top(ctx, k-len(out))
if err != nil {
return nil, err
}
out = append(out, part...)
if len(out) == k {
break
}
}
return out, nil
}
| checked on 1,000,000 players | hash | range |
|---|---|---|
| top 1 equals a full sort | Yes | Yes |
| top 10 equals a full sort | Yes | Yes |
| top 100 equals a full sort | Yes | Yes |
| top 1,000 equals a full sort | Yes | Yes |
| real nodes | updates/s | ranks/s | top 10/s |
|---|---|---|---|
| 1 node | 284,576 | 88,350 | 91,956 |
| 4 nodes, hash | 881,072 | 39,425 | 34,877 |
| buckets | p50 error | p99 error | top 1,000, p50 |
|---|---|---|---|
| 100, geometric | 0.09% | 1.26% | 1.7% |
| 1,000, geometric | under 0.01% | 0.07% | 0.2% |
| 1,000, equal width | 0.31% | 2.36% | 0% |
counts[b]: one number per score range, in a Redis hash
on a score change:
HINCRBY hist old_bucket -1
HINCRBY hist new_bucket +1
rank(score): // from a copy, refreshed each second1
b = bucket of score
guess = counts[b]2 x (top(b) - score) / width(b)
RETURN 1 + SUM(counts above b) + guess- 129 KB of counters against 78 MB for the full board. A rank costs no network call.
- 2A straight line inside one bucket. The seeded scores are smooth, which flatters it. Scores with spikes do worse.
Tested source Go: buckets
// Move shifts one player between counters: two HINCRBY calls, whatever the board's size.
func (b Buckets) Move(ctx context.Context, from, to int64) error {
i, j := b.index(from), b.index(to)
if i == j {
return nil
}
_, err := b.RDB.Pipelined(ctx, func(p redis.Pipeliner) error {
p.HIncrBy(ctx, b.Key, strconv.Itoa(i), -1)
p.HIncrBy(ctx, b.Key, strconv.Itoa(j), 1)
return nil
})
if err != nil {
return fmt.Errorf("move in %s: %w", b.Key, err)
}
return nil
}
// Counts reads every counter. A service keeps this copy and refreshes it about once a second, so
// a rank read costs no call to Redis.
func (b Buckets) Counts(ctx context.Context) ([]int64, error) {
raw, err := b.RDB.HGetAll(ctx, b.Key).Result()
if err != nil {
return nil, fmt.Errorf("read %s: %w", b.Key, err)
}
out := make([]int64, len(b.Cuts)-1)
for k, v := range raw {
i, err := strconv.Atoi(k)
if err != nil {
return nil, fmt.Errorf("bucket %q: %w", k, err)
}
out[i], err = strconv.ParseInt(v, 10, 64)
if err != nil {
return nil, fmt.Errorf("bucket %q: %w", k, err)
}
}
return out, nil
}
// Estimate is the sum of the buckets above, plus a straight-line guess inside the score's bucket.
func (b Buckets) Estimate(counts []int64, score int64) int64 {
i := b.index(score)
var above int64
for _, c := range counts[i+1:] {
above += c
}
lo, hi := b.Cuts[i], b.Cuts[i+1]
return 1 + above + counts[i]*(hi-1-min(score, hi-1))/max(hi-lo, 1)
}
Nodes: Redis server processes on one 8-core laptop with the load generator, 64 clients, 16 commands per update batch. Each rank read costs one command per node. Errors are a share of the true rank, on 5,000 seeded players.
78 GB holds a billion players, so one node goes a long way. I shard only for write rate or memory, and I know that hash shards make rank reads slower.
- score
- 2,986
- rank
- 499,940
- place
- 500,000
- same score
- 101
| place | player | score |
|---|---|---|
| 499,998 | p399315 | 2,986 |
| 499,999 | p396563 | 2,986 |
| 500,000 | p394176 | 2,986 |
| 500,001 | p393289 | 2,986 |
| 500,002 | p382726 | 2,986 |
| design | rank it gives | commands | median time |
|---|---|---|---|
| 499,940 | 4 in 1 call | 170 µs | |
| 499,940 | 1 in 1 call | 352.7 ms | |
| 499,940 | 4 in 4 calls | 63.8 ms | |
| 499,940 | 24 in 16 calls | 652 µs | |
| 499,940 | 10 in 10 calls | 639 µs | |
| ≈ 499,930 | 0 | 0.4 µs |
One sorted set. One script reads the rank, the score and the neighbours from one point in time.
Bars use a log scale, from the fastest design for this player to the slowest. One laptop, shared with other jobs. Read the times as orders of magnitude.
| one Redis, 1,000,000 players | rate | from |
|---|---|---|
| ZINCRBY, one a call | 27,787/s | 8 clients |
| ZINCRBY, 100 a call | 251,000/s | 8 clients |
| ZREVRANK | 30,100/s | 8 clients |
| Rank, score, 4 neighbours | 17,385/s | 8 clients |
| Top 10 | 30,573/s | 8 clients |
| Events through Postgres to Redis | 83,200/s | 8 clients, 100 events a commit |
Redis 8 and Postgres 16 on one 8-core laptop shared with other jobs. Each rate is the median of 3 runs of 2 s. These 8 clients wait for each reply, so they limit single-call rates; panel K shows the server limit with 64 clients.
Every exact design gives the same rank. They differ in what one read costs. Redis takes about a millisecond at every depth; SQL takes tens of milliseconds or more deep in the board.
| event | result | why it is safe | saved by |
|---|---|---|---|
| The log delivers a batch twice | The worker sees repeats. | The event IDs conflict, so the totals do not change. | event_id |
| A worker dies after the commit | The board is behind Postgres. | Redelivery adds nothing, reads the totals, and writes them. | ZADD GT |
| Two workers write out of order | An older total arrives last. | GT refuses a lower score. | ZADD GT |
| Redis loses the board | Rank reads fail. | Rebuild from Postgres to a new key, then rename. About 32 s for 10 M players. | Rebuild |
| A rebuild runs under live scores | Writes land on the old key. | The last step copies every row changed since the start. | updated_at |
| A window board misses points | ZINCRBY was lost in a crash. | Restate the window from the event log. | score_events |
| A late event arrives after midnight | Its day has ended. | The event's own time picks the board, up to the day board's 8-day life. | Event time |
| A cheater reaches the top | Staff ban the player. | ZREM removes the player; everyone below moves up by one. | ZREM |
| A score nears the float64 limit | Low bits would vanish. | The packed score keeps 31 bits, about 2.1 billion. Alert well below that, or start a new season. | Encode |
| step | add | it handles | move up when you see |
|---|---|---|---|
| 1 | One Postgres, rank by a count over an index. | About 129 ranks a second at the median of 1,000,000 players. | Rank reads above that rate, or a board past 100,000 players. |
| 2 | A sorted set in Redis; Postgres stays the truth. | About 88k ranks a second; 0.8 GB for 10 M players. | Direct writes block the API, or retries change totals. |
| 3 | An event log and workers, with the anti-cheat stage and window boards. | About 83k events a second through Postgres. This prompt stops here. | Read traffic fills the node, and a stale read of a few ms is fine. |
| 4 | Read replicas and a 1 s cache of the top page. | Reads grow with replicas. Writes and memory do not. | Updates reach 285k a second, or memory passes one machine. |
| 5 | Shards by hash for writes, or by score range for reads, with buckets for deep ranks (X2). | 881k updates a second on 4 nodes. A billion players is 78 GB. | Top of the ladder. |
Demand from panel C. Capacity measured in the lab on 1,000,000 players. Repeat runs moved these rates by up to 2×, so read them as orders of magnitude.
I start with Postgres for a small board. I move ranks to one Redis sorted set, then add windows and replicas. Sharding is the last step.
| question | answer | deeper |
|---|---|---|
| Show a board among my friends only. | Read each friend's score in one pipeline and sort in the service. A few hundred friends cost one round trip, and no new board. | B4 |
| Push rank changes to players live. | A worker publishes the moved players, and a socket gateway sends the update. Rate-limit it per player, because ranks change on every score. | C6 |
| Keep the board in several regions. | Keep one primary board and read replicas in each region. A rank then lags by the replication delay, which a player will not notice. | X1 |
| Find the top 100 of anything, not players. | Use a sketch in a stream job when the key space is huge. Space-Saving gives the heavy keys in fixed memory, with a known error. | B10 |
| How do you partition the log? | Key by player, so one worker handles a player at a time. A hot player then stays on one partition, in order. | B6 |
| How do you pay prizes safely? | Freeze the final board in Postgres, then pay from it with a ledger. A unique key per window and player stops a double payment. | T9 |
| A rank must never be stale. Now what? | Read the primary only, and accept that a replica cannot help. Then a rank read waits for the score's write, so the worker must finish first. | X3 |
0 of 10 known
Why is a rank O(log n) in a sorted set and O(n) in SQL?
A window query takes 362 ms on 1,000,000 rows. Can an index fix it?
Two players share a score. What do ZREVRANK and ZCOUNT give them?
How do you rank the player who reached a score first higher?
Why does the worker use ZADD GT with a total, and not ZINCRBY?
Each of 8 hash shards returns its top 12 for a top 100. How many are right?
Range shards put every top player on one shard. What is the cost?
Going from 1 node to 4, what happened to updates and to rank reads?
With 1,000 score buckets, how far off is a rank?
Why is anti-cheat a stage in front of the board, not a sweep after it?
- demand
- About 1,736 scores and 2,431 ranks a second at peak.
- memory
- 77.7 B a player: 0.78 GB for 10 M.
- rank
- 151 µs in Redis; 362 ms with RANK() on 1,000,000 rows.
- growth
- 100× the players: RANK() 66× slower; ZREVRANK flat.
- one node
- About 285k batched updates and 88k ranks a second.
- 4 nodes
- Updates 3.1×; ranks 0.4×.
- rebuild
- 314k players a second from Postgres.
- scores
- A float64 is exact to 2^53.
Redis 8 and Postgres 16 on an 8-core laptop shared with other jobs. Ranks and top-k checks repeat exactly; rates vary between runs.