Skip to the guide

Top-K and leaderboards

IntermediatePattern5 pages

A supermarket chain wants its ten best-selling products each week. If each store sent only its own top ten, a brand of rice that came eleventh in every store, and first across the chain, would be on no list. So each store's tills total the day and send a tally for every product, split by aisle to the buyer for that aisle. Each buyer then holds every store's numbers for her products and picks her top ten, and the marketing manager merges the buyers' lists into the newsletter everyone reads.

Purchases are events such as views, and products are the items ranked. The tills are app servers summing a second of views per post, and the tallies by aisle are partial counts keyed by item. Each buyer is an aggregator that owns a slice of the items and picks its top K, the manager is the merger, and the newsletter is the finished list in a cache. Interviewers asking for "trending" or "my rank" listen for where the counting happens and whether the merge is right. The move: count each item's events in one place, keep the top K beside the counts, and merge only the short lists; a ranking of players stays one sorted set while one key keeps up.