Real-Time
Global Leaderboard
Implement a massive multiplayer gaming leaderboard using Sorted Sets to rank millions of players instantly.
Architecture
Traditional SQL databases struggle with sorting millions of records in real-time. VelocityDB uses Sorted Sets (ZSETs), a specialized data structure that keeps elements sorted by a score upon insertion, allowing for O(log(N)) rank retrieval.
Why Sorted Sets?
- Automatic ordering by score
- No "ORDER BY" query cost
- Unique members (no duplicate players)
Use Cases
- MMR / ELO Rankings
- Most Active Users
- Trending Content Feed
Live Playground
Modify scores in real-time. The Sorted Set engine re-ranks all members instantly with O(log N) complexity.
Real-Time Sorted Set Demo
Z-Protocol Event Log
Engine Complexity
Update Player Score
When a player finishes a match, update their score. ZADD creates the member if they don't exist, or updates their score if they do.
// Backend Service (Node.js)
async function updatePlayerScore(playerId, newScore) {
// ZADD key score member
await client.zadd('leaderboard:season_4', newScore, playerId);
console.log(`Updated ${playerId} to ${newScore}`);
}Get Top 10 Players
Retrieve the highest scoring players instantly functionality. ZREVRANGE fetches from high scores to low.
app.get('/api/leaderboard/top', async (req, res) => {
// ZREVRANGE key start stop WITHSCORES
const topPlayers = await client.zrevrange('leaderboard:season_4', 0, 9, 'WITHSCORES');
// Format: ["player1", "5000", "player2", "4900"]
// Transform to object array
const formatted = [];
for (let i = 0; i < topPlayers.length; i += 2) {
formatted.push({
rank: (i/2) + 1,
id: topPlayers[i],
score: parseInt(topPlayers[i+1])
});
}
res.json(formatted);
});Get My Rank
Show the current user their exact global ranking without scanning the whole table.
app.get('/api/leaderboard/me', async (req, res) => {
const { playerId } = req.user;
// ZREVRANK key member
// Returns 0-based index (0 is 1st place)
const rankIndex = await client.zrevrank('leaderboard:season_4', playerId);
if (rankIndex === null) {
return res.json({ unranked: true });
}
res.json({
rank: rankIndex + 1,
playerId
});
});CLI Commands
ZADD lb:2024 1050 "user_x"ZREVRANGE lb:2024 0 2 WITHSCORESZCARD lb:2024Pro Tip
Use `ZINCRBY` to add points to an existing score instead of overwriting it. Perfect for accumulating XP or damage points.