Velocity
Back to Examples
Advanced Structure

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

1
HyperSonic15,400 PTS
2
Rustacean14,200 PTS
3
VelocityDev12,800 PTS
4
BinaryKing11,500 PTS
5
LSM_Master9,800 PTS

Z-Protocol Event Log

Awaiting leaderboard interaction...

Engine Complexity

O(log N)Constant Sort
1

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}`);
}
2

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);
});
3

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

Set Score
ZADD lb:2024 1050 "user_x"
Get Top 3
ZREVRANGE lb:2024 0 2 WITHSCORES
Count Players
ZCARD lb:2024

Pro Tip

Use `ZINCRBY` to add points to an existing score instead of overwriting it. Perfect for accumulating XP or damage points.

ZINCRBY lb:2024 50 "user_x"