Implementing a Real-Time Leaderboard with Redis for a Mobile Game
This article explains how to build a real‑time, dual‑dimension leaderboard for a mobile tank game using Redis Sorted Sets, covering ranking types, composite score calculations, dynamic updates, efficient data retrieval with pipelines, and a complete PHP implementation.
Introduction: The article describes implementing a real‑time leaderboard for a mobile tank game, supporting full‑server ranking, individual player queries, and dual‑dimension sorting, with data size ranging from 10 k to 500 k entries.
Leaderboard types: character, guild, and tank rankings, each with specific sorting dimensions (e.g., level + combat power, tower floor + clear time, tank type).
Design: Redis Sorted Sets (ZADD) are used for ranking, with composite scores calculated by combining dimensions into a single numeric value; for level ranking, score = level × 10^10 + combat power, fitting within Redis 64‑bit limits.
For the tower ranking, a base timestamp (2050‑01‑01) is subtracted from the clear time to create a relative time component, ensuring earlier clears receive higher scores.
Tank ranking uses a compound member ID (uid_tankId) while storing dynamic player data in a Redis hash as JSON.
Dynamic updates: When a player's level or combat power changes, the corresponding ZADD and HSET operations are executed; the hash stores auxiliary display data (name, avatar, guild, VIP, etc.).
Fetching the leaderboard: ZRANGE (or ZREVRANGE) retrieves the top N member IDs, then HGET obtains each player's JSON data. To reduce round‑trips, Redis pipeline is employed, merging multiple HGET commands into a single request.
PHP implementation: The article provides a class RankList { protected $rankKey; protected $rankItemKey; protected $sortFlag; protected $redis; public function __construct($redis, $rankKey, $rankItemKey, $sortFlag = SORT_DESC) { ... } public function updateScore($uid, $score = null, $rankItem = null) { ... } public function getRank($uid) { ... } public function del($uid) { ... } public function getList($topN, $withRankItem = false) { ... } public function flush() { ... } } class that encapsulates Redis keys, score updates, rank queries, deletions, and list retrieval, using PIPELINE for batch operations and supporting both ascending and descending order.
Conclusion: This simple yet extensible design demonstrates how Redis can efficiently support real‑time multi‑dimensional leaderboards in a game backend.
Architecture Digest
Focusing on Java backend development, covering application architecture from top-tier internet companies (high availability, high performance, high stability), big data, machine learning, Java architecture, and other popular fields.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.