System Design

C21

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.

Not startedSaved in this browser only.
  1. 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.
  2. 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.
  3. 3One node goes far: 77.7 bytes a player and about 88k ranks a second. Shard for memory or writes, not for rank reads.
  4. 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.
C21
    A

    The prompt

    as the interviewer says it
    Design a leaderboard that ranks millions of players, updated on every score, with rank queries in real time.
    questionanswer 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.

    B

    Requirements

    as numbers
    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-functionaltarget
    Rank read latencyp99 < 10 ms
    Score to boardp99 < 1 s
    A retried scoreCounts once
    Redis lostRebuild in about a minute, no score lost
    Availability99.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.

    C

    Estimates

    the arithmetic, on the board
    quantityarithmeticresult
    Scores5 M players × 10 a day = 50 M ÷ 86,400≈ 579/s; 3× peak ≈ 1,736/s
    Rank readsone per score + 5 M × 4 views = 70 M ÷ 86,400≈ 810/s; 3× peak ≈ 2,431/s
    All-time board10 M × 77.7 B (measured)≈ 0.78 GB
    Day and week boards2 × 5 M × 77.7 B≈ 0.78 GB; 1.6 GB in all
    Totals table10 M × 151 B (measured, with indexes)≈ 1.5 GB
    Event log50 M × 100 B (assumed row)5 GB a day; keep 90 days
    Rebuild10 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.

    D

    API

    endpoints, status codes, retries
    callforretry safe bysuccesserrors
    POST /v1/scores {event_id, player_id, points, at, signature}a match result, from a game serverthe event ID202400, 401 bad signature
    GET /v1/boards/{window}/top?k=100the top ka read200 + players400 k too large
    GET /v1/boards/{window}/players/{id}?around=2rank and neighboursa read200 + rank, place, near404 not on this board
    DELETE /v1/boards/players/{id}a ban, from a staff toolDELETE is idempotent204403
    • 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.

    E

    Data model

    Postgres is the truth, Redis is the index
    the truth: two tables in Postgres1 : nscoresPKplayer_idscoretotalupdated_atidx (score, player_id) DESCscore_eventsPKevent_idremoves repeatsFKplayer_iddeltaatpicks the windowappend only
    Redis keyholdslives
    lb:allSorted set: player, total scoreAlways
    lb:day:20261031Sorted set: points of that UTC day8 days
    lb:week:2026-W44Sorted set: points of that ISO week35 days
    lb:histHash: bucket, player countOptional; panel K
    scores, score_eventssql
    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);
    1. 1The total. A worker adds to it in the same statement that stores the event.
    2. 2A rebuild copies rows changed since it started, so live scores are not lost.
    3. 3A repeat of an event hits this key and adds nothing.
    4. 4The time of the match, not of the write. It picks the window, so a late event lands in the right day.
    5. 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.

    F

    The architecture

    click a step; its path lights up
    Game serversigns resultsClientapp, browserScore APIstatelessRank APIcache, 1 sEvent logby playerAnti-cheat stageone batch at a timeScore workersone per partitionRebuild jobon loss, on closePostgresscores, eventsRedisall, day, week boards

    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.

    G

    Capabilities used

    what each tool gives you
    toolcapabilitywhat it gives this designalso used for
    RedisSorted set: ZREVRANKA place in O(log n), at any depth of the board.Percentiles, sliding windows
    RedisZCOUNT with an open rangeA shared rank for ties, O(log n) however many players are above.Rate limit windows
    RedisZREVRANGE WITHSCORESThe top k, and the neighbours by position. O(log n + k).Timelines, delay queues
    RedisZINCRBYAdds points in O(log n). A retry counts twice.Counters by key
    RedisZADD GTWrites a total only if it is higher, so repeats and late writes do nothing.High-water marks
    RedisLua scriptsRank, score and neighbours from one point in time, in one round trip.Locks, rate limits
    RedisRENAMEA rebuilt board replaces the old one in one step.Any full cache reload
    RedisZUNIONSTOREBuilds a week from 7 days in a job: 700,000 players in about 1.2 s.Merged rankings
    RedisScores are float64Limit Exact only to 2^53, which caps score and tie-break bits together.
    PostgresINSERT ON CONFLICT DO NOTHINGRemoves repeats by event ID, and returns only the new rows.Idempotency keys, inbox tables
    PostgresData-changing CTEThe event and the new total commit in one statement.Ledgers, counters
    PostgresIndex on (score DESC, player_id DESC)Top k and neighbours as short index ranges.Any ordered page
    KafkaPartitioned log keyed by playerOne worker per player at a time, and redelivery after a crash.Feeds, stream jobs
    ServiceSpace-Saving sketchFinds 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.

    H

    Deep dive: why a rank is cheap here

    sorted set against SQL
    one rank query, median, log scales100 µs1 ms10 ms100 ms1 s10 s10k players100k players1M playersSQL RANK()362 msSQL count, last place33 msZREVRANK151 µs
    each link stores its span; the sum on the path is the rankL244L12222L011111111head1201401502002603103404004 + 2 + 1 = 7: the member with score 340 is 7th from the low end.ZREVRANK counts from the high end: n - 7, here 1, 0-based.Each level holds a fraction of the level below, so the path has about log n links.
    methodstatuscost of one rank
    SQL RANK() per queryNot approvedNumbers every row: 17 queries a second
    SQL count of higher scoresSmall boardOne entry per player above: 129 a second at the median
    Rank table, batch refreshStale rank is fineCheap to read; old until the next run
    Redis sorted setApprovedO(log n): 30k a second from 8 clients
    Score bucketsClose is fineNo 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, standing, toppseudo code
    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)
    1. 1Three separate calls could see three different boards. A script runs as one step.
    2. 2The documentation states this directly: ZCOUNT uses element ranks to get the size of the range.
    3. 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
    Go: add, top, standinggo
    
    // 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)
    }
    
    Lua: one standinglua
    -- 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}
    
    SQL: two rank queriessql
    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.

    I

    Deep dive: ties and windows

    what a rank means
    tie rulestatushow
    Member name orderNot approvedThe default of ZREVRANK. It means nothing to a player.
    Shared rank: 1, 2, 2, 4Approved1 + ZCOUNT of the scores strictly above
    First to reach it winsPrizesTime in the low bits of the score
    Fraction of a point for timeNot approvedBits vanish as the score grows; a float64 has 53 exact bits
    three meanings of rankpseudo code
    // 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
    1. 122 bits of seconds cover about 48 days, one season. The score keeps 31 bits.
    2. 2An earlier second gives a larger number, so the first to reach a score ranks higher.
    Tested source Go: encode, decode
    Go: encode, decodego
    
    // 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 methodstatuscost
    One board per window, written on each scoreApproved3 ZINCRBY in one round trip
    Week from 7 days, ZUNIONSTOREA job, not a readAbout 1.2 s for 700,000 players
    WHERE at > ... per readNot approvedSums a window of events for each query
    Rolling 24 hoursProduct needs itHourly boards merged by a job; the board lags up to an hour
    write and repair windowspseudo code
    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
    1. 1A late event lands in the day it was played, so a retry across midnight does no harm.
    2. 2Old boards remove themselves. Nothing has to run for memory to stay flat.
    3. 3ZINCRBY can lose points in a crash. The event log can always restate a window.
    Tested source Go: window boards · SQL: window totals
    Go: window boardsgo
    
    // 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
    }
    
    SQL: window totalssql
    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.

    J

    Deep dive: scores that stay right

    retries, rebuild, cheats
    write pathstatusafter a retry
    ZINCRBY only, no truthNot approvedCounts twice, and no record shows it
    Redis persistence aloneScores can be lostSame; a failover can also drop recent writes
    Postgres event ID, then ZADD GTApprovedNo change; a crash heals on redelivery
    apply and rebuildpseudo code
    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
    1. 1The repeat stops here, so the total adds it once. Only rows that are new reach the sum.
    2. 2Two workers can read totals in one order and write them in the other. GT drops the older one.
    3. 3Readers keep the old board until this one command. There is no empty moment.
    4. 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
    Go: applygo
    
    // 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()
    }
    
    SQL: applysql
    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();
    Go: rebuildgo
    
    // 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.

    checkcatchesstatus
    Signed result from the game serverForged requestsApproved
    Score above the most a match can giveImpossible scoresApproved
    Too many events in a batchBotsApproved
    Replay of the match on a serverSkilled cheatsHigh prizes
    Review after the board shows itEverything, lateNot approved
    the anti-cheat stagepseudo code
    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
    1. 1Fixed memory, whatever the number of players. The full method is on sheet B10.
    2. 2Count minus error is a lower bound on the true count, so a sketch error never holds an honest player.
    3. 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
    Go: the stagego
    
    // 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.

    K

    Deep dive: when a board outgrows a node

    memory or write rate, not rank reads
    players on each of 8 shards, one scalehash of the playerfullest 1.21× mean106k to 151kscore range, equal countsfullest 1.00× mean125k to 125kscore range, equal widthsfullest 7.99× mean1 to 998k
    designtop krankscore changestatus
    Hash shards, scatter-gatherAll shardsAll shardsOne shardWrite heavy
    Range shards, quantile cutsTop shardSizes, then one shardMoves at a cutRead heavy
    Range shards, equal widthsTop shardSizes, then one shardMoves at a cutNot approved
    Exact top, buckets belowOne small setApproximate2 HINCRBYClose is fine
    Read replicas of one nodeOne replicaOne replicaPrimary onlyReads only; memory stays
    two ways to shardpseudo code
    // 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
    1. 1The top k does not spread evenly. Asking for 12 each found only 85 of the true top 100.
    2. 2Each count is O(log n), but a read costs one command per shard, so a rank read gets more expensive.
    3. 3Of 8 shards, a top 100 reads one. Cuts must sit on quantiles, or one shard holds nearly everyone.
    4. 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
    Go: scatter-gathergo
    
    // 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
    }
    
    Go: score rangesgo
    
    // 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 playershashrange
    top 1 equals a full sortYesYes
    top 10 equals a full sortYesYes
    top 100 equals a full sortYesYes
    top 1,000 equals a full sortYesYes
    real nodesupdates/sranks/stop 10/s
    1 node284,57688,35091,956
    4 nodes, hash881,07239,42534,877
    bucketsp50 errorp99 errortop 1,000, p50
    100, geometric0.09%1.26%1.7%
    1,000, geometricunder 0.01%0.07%0.2%
    1,000, equal width0.31%2.36%0%
    approximate rankpseudo code
    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
    1. 129 KB of counters against 78 MB for the full board. A rank costs no network call.
    2. 2A straight line inside one bucket. The seeded scores are smooth, which flatters it. Scores with spikes do worse.
    Tested source Go: buckets
    Go: bucketsgo
    
    // 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.

    L

    See it: pick a player

    recorded from a seeded board of 1,000,000 players
    score
    2,986
    rank
    499,940
    place
    500,000
    same score
    101
    neighbours in board order
    placeplayerscore
    499,998p3993152,986
    499,999p3965632,986
    500,000p3941762,986
    500,001p3932892,986
    500,002p3827262,986
    designrank it givescommandsmedian time
    499,9404 in 1 call170 µs
    499,9401 in 1 call352.7 ms
    499,9404 in 4 calls63.8 ms
    499,94024 in 16 calls652 µs
    499,94010 in 10 calls639 µs
    ≈ 499,93000.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 playersratefrom
    ZINCRBY, one a call27,787/s8 clients
    ZINCRBY, 100 a call251,000/s8 clients
    ZREVRANK30,100/s8 clients
    Rank, score, 4 neighbours17,385/s8 clients
    Top 1030,573/s8 clients
    Events through Postgres to Redis83,200/s8 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.

    M

    Failure cases

    what breaks, and why the board stays right
    eventresultwhy it is safesaved by
    The log delivers a batch twiceThe worker sees repeats.The event IDs conflict, so the totals do not change.event_id
    A worker dies after the commitThe board is behind Postgres.Redelivery adds nothing, reads the totals, and writes them.ZADD GT
    Two workers write out of orderAn older total arrives last.GT refuses a lower score.ZADD GT
    Redis loses the boardRank reads fail.Rebuild from Postgres to a new key, then rename. About 32 s for 10 M players.Rebuild
    A rebuild runs under live scoresWrites land on the old key.The last step copies every row changed since the start.updated_at
    A window board misses pointsZINCRBY was lost in a crash.Restate the window from the event log.score_events
    A late event arrives after midnightIts 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 topStaff ban the player.ZREM removes the player; everyone below moves up by one.ZREM
    A score nears the float64 limitLow bits would vanish.The packed score keeps 31 bits, about 2.1 billion. Alert well below that, or start a new season.Encode
    N

    Scale ladder

    start simple; climb only on a signal
    Each step adds one component1Postgres, count2+ sorted set3+ log, worker4+ replicas5+ shardsmore load →
    Capacity against this prompt's demand101001k10k100k1MDemand: scores, peak: 1,736 operations per secondDemand: scores, peak1,736Demand: rank reads, peak: 2,431 operations per secondDemand: rank reads, peak2,431Postgres: RANK(): 17 operations per secondPostgres: RANK()17Postgres: count, median: 129 operations per secondPostgres: count, median129Postgres: scoring events: 83,200 operations per secondPostgres: scoring events83,200Redis: ranks, 1 node: 88,350 operations per secondRedis: ranks, 1 node88,350Redis: updates, 1 node: 284,576 operations per secondRedis: updates, 1 node284,576Redis: updates, 4 nodes: 881,072 operations per secondRedis: updates, 4 nodes881,072operations per second, log scale
    stepaddit handlesmove up when you see
    1One 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.
    2A 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.
    3An 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.
    4Read 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.
    5Shards 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.

    O

    Follow-ups

    what the interviewer asks next
    questionanswerdeeper
    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
    P

    Drill

    predict, then reveal

    0 of 10 known

    1. Why is a rank O(log n) in a sorted set and O(n) in SQL?

    2. A window query takes 362 ms on 1,000,000 rows. Can an index fix it?

    3. Two players share a score. What do ZREVRANK and ZCOUNT give them?

    4. How do you rank the player who reached a score first higher?

    5. Why does the worker use ZADD GT with a total, and not ZINCRBY?

    6. Each of 8 hash shards returns its top 12 for a top 100. How many are right?

    7. Range shards put every top player on one shard. What is the cost?

    8. Going from 1 node to 4, what happened to updates and to rank reads?

    9. With 1,000 score buckets, how far off is a rank?

    10. Why is anti-cheat a stage in front of the board, not a sweep after it?

    Q

    Numbers to say

    measured, derived or cited
    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.