See my jobs
Home/System design/Top-K / leaderboard

Design a top-K / leaderboard system

Updated Nov 17, 2026

21 of 909 coded candidate reports (Jan 2025 to Nov 2026) mention a leaderboard, top-K or 'design LeetCode' question; 18 are Meta; none in the last 90 days

A leaderboard ranks players by score and answers three questions fast: who is on top, what is my rank, and who is near me. A close cousin asks for the top K trending items (hashtags, songs) over a time window. In our data this is mostly a Meta question, and it often comes wrapped as 'design LeetCode' with a contest leaderboard.

In short
  • 21 of 909 candidate reports mention it; 18 of those are Meta. None fall in the last 90 days, but Meta reports from March and April 2026 still include it.
  • The question comes in three flavors: game or contest leaderboard, 'design LeetCode' (judge plus leaderboard), and trending top-K. Ask which one early.
  • The default building block is a Redis sorted set per board. Updates, rank lookups and top-K reads are all O(log N) plus the size of the result.
  • Senior answers cover exact vs approximate rank at 100M+ players, ties, daily and weekly boards, and keeping a durable source of truth behind the cache.
  • Use absolute best-score writes rather than increments where you can, so retried events cannot double count.

Who asks it and how often

We coded 909 first-hand candidate reports that list questions, dated January 2025 to November 2026. 21 mention a leaderboard, top-K or "design LeetCode" question. Counting only reports that name a single company: Meta 18, Robinhood 1, Coinbase 1. All 21 come from web sources (LeetCode Discuss, PracHub, Blind, blogs), none from Reddit.

None of the 21 are from the last 90 days. That fits a wider pattern in our data: most of Meta's reports come from LeetCode Discuss posts in early 2025, so Meta's named questions rank high overall but rarely show up in recent months. The question has not vanished, though. Two Meta reports from 2026 include it: an online game leaderboard in a loop that also had AI-assisted coding and a new agentic design round (April) [1], and "design LeetCode" with a judge sandbox and leaderboard (March) [2].

FlavorExamples from reports
Game or contest leaderboardMeta online game leaderboard, Apr 2026 [1]; Meta E4 ICPC-style competition platform with a leaderboard, 2025 [10]; Meta E5 live contest leaderboard, 2025 [11]
"Design LeetCode" / online judgeMeta, Mar 2026 [2]; Meta E5 for 50K users, Oct 2025 [4]
Trending top-KMeta E5 top-K trending songs, Jul 2025 [5]; Meta E4 trending hashtags in a phone screen, Mar 2025 [6]; Meta E5 top-K heavy hitters design, Sep 2025 [7]
Coding-round leaderboardCoinbase, May 2026: a leaderboard class that returns the k-th highest score, built with two ordered sets [3]; Robinhood: a referral-chain leaderboard [8]

If you interview at Meta, note that its careers FAQ says design interviews run in CoderPad with Mermaid Markdown and the same built-in AI assistant used in coding rounds [9]. Practise drawing this design as text, not on a whiteboard.

Clarifying questions to ask

  • Which flavor? A per-game leaderboard, a contest on a coding platform, or trending items over a time window. They share ideas but differ in the hard part.
  • How many players per board? 50,000 in one contest is a different problem from 200 million in a global mobile game.
  • What do users need? Top 100 only, their own exact rank, the players just above and below them, or a percentile like "top 3%"?
  • Does rank need to be exact for everyone? Exact for the top 1,000 and approximate for the rest is a very different (and cheaper) system.
  • How is the score computed? Best single score, cumulative points, or problems solved plus a time penalty?
  • How are ties broken? Earlier achievement wins, or shared rank?
  • Which time windows? All-time, daily, weekly, or a rolling last-24-hours board?
  • How fresh must scores be? Must a new score show in under a second, or is a few seconds fine?

Requirements

  • Functional: submit a score; get the top K for a board; get a user's rank and the N players around them; support all-time plus daily and weekly boards; show display names next to scores.
  • Non-functional: read latency well under 100 ms at the 99th percentile; new scores visible within a few seconds; no lost or double-counted scores; boards keep working during a cache node failure.

A back-of-envelope estimate, with assumed numbers: 10 million players on one board and 50 million score events per day come to about 600 writes per second on average, maybe 6,000 at peak. A Redis sorted set with 10 million members takes roughly 1 GB including overhead, which fits on one node. Reads of the top 100 are far more frequent than writes, so a short-lived cache on that one page removes most load.

At 200 million players on a single board, memory and the single-threaded node become the limit, and you need sharding or approximate rank. Say where that line is.

API

POST /v1/boards/{boardId}/scores
  { "userId": "u_42", "score": 1830, "eventId": "match_9917" }   -> 202 Accepted
  # eventId makes retries safe (idempotency)

GET /v1/boards/{boardId}/top?k=100
  -> [{ "rank": 1, "userId": "u_7", "name": "...", "score": 2410 }, ...]

GET /v1/boards/{boardId}/users/{userId}?around=5
  -> { "rank": 18234, "score": 1830, "neighbors": [ ... 5 above, 5 below ... ] }

# boardId encodes game and period, e.g. chess:weekly:2026-W47

High-level design

The game or judge server sends a verified result to the score service. It checks the event ID for duplicates, writes the score event to a durable store (a database table or a log such as Kafka), and returns. An updater reads the events and applies them to a Redis sorted set per board: one for all-time and one for the current day and week. The leaderboard read service answers top-K and rank queries from Redis, adds display names from a user cache, and caches the top page for a second or two.

  • Top K: ZRANGE board 0 K-1 REV WITHSCORES, O(log N + K).
  • My rank: ZREVRANK board user, O(log N).
  • Neighbors: take the rank r, then ZRANGE board r-5 r+5 REV.
  • Best-score update: ZADD board GT score user keeps the higher of old and new, so replaying an event is harmless. Cumulative boards use ZINCRBY, which needs the event-ID check in front of it.
  • The database or event log is the source of truth. If Redis loses data, rebuild the sets from it.

Deep dive 1: how to store and rank

OptionTop KMy rankLimitsWhen to pick
SQL table with an index on scoreFast with the indexCOUNT(*) of higher scores; gets slow at millions of rows with heavy writesRank queries and write loadSmall boards, e.g. a 50K-user contest
Redis sorted set (skip list + hash)O(log N + K)O(log N)Memory of one node; single-threadedDefault up to tens of millions of players per board
Sorted sets sharded by boardSame, per boardSameOne huge board still lives on one nodeMany games or contests, each moderate size
One board sharded by score rangeRead the top shardCount of players in higher shards + local rankShards go uneven as scores drift; rebalancing is workOne giant board with exact rank
Approximate rank (score histogram)Exact from a small top setPlayers in higher buckets + estimate within the bucketNot exact"You are in the top 3%" for hundreds of millions of players
Batch job every few minutesPrecomputedPrecomputedStale by designDaily or weekly boards that do not need live updates

A strong answer often combines two: an exact sorted set for the top 10,000 and a histogram for everyone else. Most users only look at the top page and their own rough position.

Deep dive 2: ties and time windows

On ties, sorted sets order equal scores by member name, which is arbitrary from the user's view. If the earlier achiever should win, pack both into one number: combined = score * 10^10 + (MAX_TS - timestamp). Watch the size: Redis scores are 64-bit floats, exact only up to 2^53, so check that your largest score times the multiplier stays below that. For a coding contest ranked by problems solved, then lowest penalty time, use solved * BIG - penalty.

For fixed windows such as daily or weekly boards, use one key per period, such as chess:weekly:2026-W47, and write each event to the all-time key and the current period keys. Set a TTL so old periods expire after you archive them.

For a rolling window (last 24 hours), keep one set per hour and build the 24-hour view by merging the last 24 sets with ZUNIONSTORE, refreshed every minute or so. A true per-event sliding window costs much more and is rarely needed.

"Top 10 hashtags in the last hour" sounds like a leaderboard but is harder: the set of items is huge, most appear once, and counts must expire. You are counting a stream, not ranking a fixed set of players.

ApproachHow it worksAccuracyCostWhen to pick
Exact windowed counts in a stream processorPartition events by item, count per window (e.g. per minute), each partition keeps its local top K, a final step merges themExactMemory for every active itemItem space fits across the cluster
Count-Min Sketch plus a min-heapA small fixed table of counters estimates each item's count; a heap of size K tracks the current leadersOverestimates; good for heavy hittersFixed small memoryHuge item space, approximate OK
Fast path plus slow pathSketch-based numbers in real time; exact batch recount every hour replaces themApproximate now, exact laterTwo systems to runWhen product wants both speed and correct history

One trap: merging each server's local top K is only correct if events are partitioned by item. If counts for one hashtag are spread across servers, an item that is 11th everywhere can be 1st overall. Partition by item key first, then take top K per partition.

If it is framed as "design LeetCode"

  • Submissions go into a queue; a pool of sandboxed workers (containers with no network, CPU and memory limits, a hard time limit) runs the tests and writes results.
  • Contest start is the load spike: everyone opens problems and submits at once. Pre-scale workers and let the queue absorb bursts; show users "pending" instead of blocking.
  • The contest leaderboard updates only on accepted submissions, ranked by solved count, then penalty time, using the combined score above.
  • Clients poll the top page every few seconds, served from a short cache. Push over WebSockets is optional but worth discussing.

Scaling and failure modes

ProblemWhat to do
Read spike when a contest or season endsCache the top page for 1 to 5 seconds; serve the public board through a CDN
Redis node lostReplica takes over; rebuild from the event log if needed; serve the cached top page in the meantime
Retried score eventsEvent ID check; prefer ZADD GT with absolute scores over increments
Write burstsQueue in front of the updater; batch Redis commands with pipelining
Fake scoresAccept scores only from trusted game or judge servers, never directly from clients
One board outgrows a nodeScore-range shards for exact rank, or exact top set plus histogram for the long tail

What interviewers look for: mid vs senior

Our guidance from how these rounds usually run, not a company rubric.

AreaMid-level answerSenior answer
Core designSorted set per board, correct commands and complexityExplains why, and when SQL would be enough
Rank at scaleExact rank from one sorted setKnows where one node stops; proposes score-range sharding or approximate rank and asks if exact is needed
CorrectnessMentions tiesEncodes tie-breaks in the score, handles idempotent writes, keeps a source of truth
WindowsAll-time boardDaily, weekly and rolling boards with clear key design and expiry
Top-K variantHeap over countsStreaming counts partitioned by item, sketches for huge key spaces, explains the merge trap

Common mistakes

  • Running ORDER BY score plus a COUNT for rank on every request at millions of rows.
  • Using increments on retried events and double counting.
  • Keeping scores only in Redis with no durable store behind it.
  • Ignoring ties until the interviewer asks.
  • Treating trending top-K like a static leaderboard and storing exact counts for every hashtag forever.
  • Merging per-server top-K lists without partitioning by item.
  • Not asking whether every user needs an exact rank.

How to prepare

Know the sorted set commands cold

ZADD with GT, ZINCRBY, ZRANGE with REV, ZREVRANK and their complexity. Interviewers often ask for them by name.

Practise the three flavors

Do one game leaderboard, one 'design LeetCode' and one trending-hashtags design. Time each to 35 minutes.

Prepare the scale jump

Have a crisp answer for 'now there are 500 million players on one board': score-range shards or exact top set plus histogram.

Write the coding version

Coinbase asked for a leaderboard class with a k-th highest query [3]. Build one with a sorted container and a dict of current scores.

Practise the leaderboard design

A mock interview that moves from a small contest board to hundreds of millions of players and trending top-K.

Start free mock

FAQ

Is a Redis sorted set enough for the whole answer?

For one board up to tens of millions of players, mostly yes. The interview moves on to durability, ties, time windows and what happens when one board no longer fits on a node.

How do I give a rank to one user out of 200 million?

Either shard by score range and add up counts from higher shards, or keep a histogram of scores and estimate. Ask first whether the product needs an exact rank for users outside the top few thousand.

Are leaderboard and trending top-K the same question?

They overlap but differ. A leaderboard ranks a known set of players by a stored score. Trending top-K counts a stream of events over a window with a huge, changing item set, so sketches and stream processing come in.

Is this still asked at Meta in 2026?

None of the 21 reports fall in the last 90 days, but Meta reports from March and April 2026 include 'design LeetCode' and an online game leaderboard [1][2]. Our Meta data is heavy on early 2025, so recent counts are low for most Meta questions.

Which other companies ask it?

Among single-company reports, only Robinhood and Coinbase, one each, both as coding problems [3][8]. Outside Meta the data is too thin to say more.

Sources

  1. Candidate report · PracHub: Meta SWE, five rounds incl. AI coding, online game leaderboard and an agentic design round · Apr 2026
  2. Candidate report · PracHub: Meta SWE, two AI coding rounds and a 'design LeetCode' system design · Mar 2026
  3. Candidate report · PracHub: Coinbase SWE onsite, leaderboard with k-th highest score · May 2026
  4. Candidate report · LeetCode Discuss: Meta E5, design LeetCode for 50K users · Oct 2025
  5. Candidate report · LeetCode Discuss: Meta onsite, top-K trending songs and LeetCode leaderboard · Jul 2025
  6. Candidate report · LeetCode Discuss: Meta E4 phone screen, trending hashtags top K · Mar 2025
  7. Candidate report · Blind: Meta E5 experience, top-K heavy hitters system design · Sep 2025
  8. Candidate report · LeetCode Discuss: Robinhood round 1, referral chain leaderboard · Aug 2025
  9. Official · Meta Careers: hiring process FAQ (AI assistant in coding and design interviews)
  10. Candidate report · LeetCode Discuss: Meta E4 infra loop, ICPC-style competition platform with leaderboard · May 2025
  11. Candidate report · LeetCode Discuss: Meta E5 product loop, live contest leaderboard · May 2025

We quote briefly, never name posters, and correct errors on request: report an error.

Related