Skip to main content
Why CacheeHow It Works
All Verticals5G TelecomAd TechAI InfrastructureFraud DetectionGamingTrading
PricingDocsBlogSchedule DemoLog InStart Free Trial
← Back to Blog

Real-Time Leaderboard Caching with Redis

December 22, 2025 • 6 min read • Gaming & Analytics

Leaderboards need to update instantly when scores change, handle millions of entries, and return rankings in milliseconds. Redis sorted sets make this possible. Here's how to build production-grade leaderboards.

Why Sorted Sets Are Perfect

Redis sorted sets (ZSET) provide:

A sorted set with 10 million players still returns top 100 in under 1ms.

Basic Leaderboard Operations

// Add or update score
await redis.zadd('leaderboard:global', score, playerId);

// Get player's rank (0-indexed, highest score first)
const rank = await redis.zrevrank('leaderboard:global', playerId);

// Get player's score
const score = await redis.zscore('leaderboard:global', playerId);

// Get top 10 players with scores
const top10 = await redis.zrevrange('leaderboard:global', 0, 9, 'WITHSCORES');
// Returns: ['player1', '9500', 'player2', '9200', ...]

// Get players ranked 50-60
const page = await redis.zrevrange('leaderboard:global', 49, 59, 'WITHSCORES');

Handling Score Updates

For games where scores accumulate:

// Increment score (atomic)
await redis.zincrby('leaderboard:global', pointsEarned, playerId);

// Update only if higher (for high scores)
async function updateHighScore(playerId, newScore) {
    const currentScore = await redis.zscore('leaderboard:global', playerId);

    if (!currentScore || newScore > parseFloat(currentScore)) {
        await redis.zadd('leaderboard:global', newScore, playerId);
        return true;  // New high score!
    }
    return false;
}
Atomic operations matter: Use ZINCRBY instead of GET + SET to avoid race conditions when multiple score updates happen simultaneously.

Time-Based Leaderboards

Most leaderboards reset daily, weekly, or monthly:

function getLeaderboardKey(period) {
    const now = new Date();

    switch (period) {
        case 'daily':
            return `leaderboard:daily:${now.toISOString().slice(0, 10)}`;
        case 'weekly':
            const week = getWeekNumber(now);
            return `leaderboard:weekly:${now.getFullYear()}-W${week}`;
        case 'monthly':
            return `leaderboard:monthly:${now.toISOString().slice(0, 7)}`;
        case 'alltime':
            return 'leaderboard:alltime';
    }
}

// Update all relevant leaderboards
async function recordScore(playerId, score) {
    const pipeline = redis.pipeline();

    pipeline.zincrby(getLeaderboardKey('daily'), score, playerId);
    pipeline.zincrby(getLeaderboardKey('weekly'), score, playerId);
    pipeline.zincrby(getLeaderboardKey('monthly'), score, playerId);
    pipeline.zincrby(getLeaderboardKey('alltime'), score, playerId);

    await pipeline.exec();
}

Adding Player Context

Leaderboards need more than just scores—show names, avatars, levels:

async function getLeaderboardWithDetails(period, start, count) {
    const key = getLeaderboardKey(period);

    // Get ranked player IDs with scores
    const rankings = await redis.zrevrange(key, start, start + count - 1, 'WITHSCORES');

    // Extract player IDs
    const playerIds = rankings.filter((_, i) => i % 2 === 0);

    // Batch fetch player details (cached)
    const players = await getPlayersCached(playerIds);

    // Combine rankings with player data
    return playerIds.map((id, i) => ({
        rank: start + i + 1,
        playerId: id,
        score: parseInt(rankings[i * 2 + 1]),
        name: players[id].name,
        avatar: players[id].avatar,
        level: players[id].level
    }));
}

async function getPlayersCached(playerIds) {
    const pipeline = redis.pipeline();

    for (const id of playerIds) {
        pipeline.hgetall(`player:${id}`);
    }

    const results = await pipeline.exec();

    return Object.fromEntries(
        playerIds.map((id, i) => [id, results[i][1]])
    );
}

Showing Player's Neighborhood

Show players around the current user's rank:

async function getPlayerNeighborhood(playerId, radius = 5) {
    const key = getLeaderboardKey('daily');
    const rank = await redis.zrevrank(key, playerId);

    if (rank === null) return null;

    const start = Math.max(0, rank - radius);
    const end = rank + radius;

    const neighborhood = await redis.zrevrange(key, start, end, 'WITHSCORES');

    return {
        playerRank: rank + 1,
        players: formatLeaderboard(neighborhood, start)
    };
}

Scaling to Millions

Strategies for massive leaderboards:

  1. Shard by region: Separate leaderboards per geography
  2. Approximate ranking: Use percentiles for lower ranks
  3. Lazy cleanup: Remove inactive players periodically
// Clean up inactive players (run daily)
async function cleanupInactivePlayers(period, daysInactive) {
    const cutoff = Date.now() - (daysInactive * 24 * 60 * 60 * 1000);
    const key = getLeaderboardKey(period);

    // Get players not active recently
    const inactive = await redis.zrangebyscore(
        'player:lastActive',
        0,
        cutoff
    );

    if (inactive.length > 0) {
        await redis.zrem(key, ...inactive);
    }
}

Real-time leaderboards at any scale

Cachee.ai handles leaderboard operations for games with millions of concurrent players.

Start Free Trial

Related Reading

The Numbers That Matter

Cache performance discussions get philosophical fast. Here are the actual measured numbers from production deployments running on documented hardware, so you can compare against your own infrastructure instead of trusting marketing copy.

The compounding effect matters more than any single number. A 28-nanosecond L0 hit means your application spends almost zero time on cache lookups in the hot path, leaving the CPU free for the actual business logic that generates revenue.

When Caching Actually Helps

Caching isn't free. It introduces a consistency problem you didn't have before. Before adding any cache layer, the question to answer is whether your workload actually benefits from caching at all.

Caching helps when three conditions hold simultaneously. First, your reads dramatically outnumber your writes — typically a 10:1 ratio or higher. Second, the same keys get read repeatedly within a window where a cached value remains valid. Third, the cost of computing or fetching the underlying value is meaningfully higher than the cost of a cache lookup. Database queries that hit secondary indexes, RPC calls to slow upstream services, expensive computed aggregations, and rendered template fragments all qualify.

Caching hurts when those conditions don't hold. Write-heavy workloads suffer because every write invalidates a cache entry, multiplying your work. Workloads with poor key locality suffer because the cache wastes memory storing entries that never get reused. Workloads where the underlying fetch is already fast — well-indexed primary key lookups against a properly tuned database, for example — gain almost nothing from caching and inherit the consistency complexity for no reason.

The honest first step before any cache deployment is measuring your actual read/write ratio, key access distribution, and underlying fetch latency. If your read/write ratio is below 5:1 or your underlying database is already returning results in single-digit milliseconds, the engineering time is better spent elsewhere.

Memory Efficiency Is The Hidden Cost Lever

Throughput numbers get the headlines but memory efficiency determines your monthly bill. A cache that stores the same hot data in less RAM lets you run a smaller instance class — and on AWS that's the difference between profitable and breakeven for a lot of services.

Redis stores each key as a Simple Dynamic String with 16 bytes of header overhead, plus dictEntry pointers in the main hashtable, plus embedded TTL metadata. For 1KB values, per-entry overhead lands around 1100-1200 bytes once you account for hashtable load factor and slab fragmentation. At a million keys, that's roughly 1.2 GB of resident memory just for the data.

Cachee's L1 layer uses sharded DashMap entries with compact packing — a 64-bit key hash, value bytes, an 8-byte expiry timestamp, and a small frequency counter for the CacheeLFU admission filter. Per-entry overhead lands at roughly 40 bytes of structural data on top of the value itself. For the same million-key workload, that's about 13% smaller resident memory. On AWS ElastiCache pricing, that gap is the difference between needing a cache.r7g.large versus a cache.r7g.xlarge for borderline workloads.

What This Actually Costs

Concrete pricing math beats hypothetical. A typical SaaS workload with 1 billion cache operations per month, average 800-byte values, and a 5 GB hot working set currently runs on AWS ElastiCache cache.r7g.xlarge primary plus a read replica — roughly $480 per month for the two nodes, plus cross-AZ data transfer charges that quietly add another $50-150 per month depending on access patterns.

Migrating the hot path to an in-process L0/L1 cache and keeping ElastiCache as a cold L2 fallback drops the dedicated cache spend to $120-180 per month. For workloads where the hot working set fits inside the application's existing memory budget, you can eliminate the dedicated cache tier entirely. The cache becomes a library you link into your binary instead of a separate service to operate.

Compounded over twelve months, that's $3,600 to $4,500 per year on a single small workload. Multiply across a fleet of services and the savings start showing up in finance team conversations. The bigger savings usually come from eliminating cross-AZ data transfer charges, which Redis-as-a-service architectures incur on every read that crosses an availability zone.