Designing the backend for seasonal game leaderboards: accepting scores only from game servers, keeping each player's best score, ranking millions of players, tie-breaking, caching the top 100, and when Redis sorted sets beat Postgres.

A leaderboard backend ranks players by score and answers two questions at very different volumes: who is in the top 100, asked on every menu screen, and where am I, asked by each player after each match. It also has to accept new scores without letting a modified client post whatever number it likes.
Sorting scores is straightforward compared with the decisions around them: where scores come from, which score counts (best, latest or a sum), how ties are broken, what happens at season rollover, and how expensive a rank lookup gets for the player in position 180,000. Those decide whether Postgres alone is enough or whether Redis earns its place.
This guide builds a seasonal leaderboard in Go with Encore on Postgres with a cached top 100, measures the queries, and then shows the Redis sorted set version.
Encore is a backend framework with built-in infrastructure, and a leaderboard uses two of its primitives: a Postgres database for scores and a cache cluster for the hot top-100 read. Encore's cache keyspaces cover strings, numbers, lists, sets and structs but not sorted sets, so ranking stays in Postgres and the cache holds the computed result. Locally both run under encore run, and a deploy provisions RDS or Cloud SQL and ElastiCache or Memorystore in your own AWS or GCP account.

Run in your terminal to get started locally.
One row per player per season holds their best score. The second index matches both queries the board runs: the top of a season, and the players ahead of a given score:
-- One row per player per season: their best score, and when they first reached it.
CREATE TABLE best_scores (
season TEXT NOT NULL,
player_id TEXT NOT NULL,
score BIGINT NOT NULL,
reached_at TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (season, player_id)
);
-- Serves "top N" and "how many players are ahead of me" from the index.
CREATE INDEX best_scores_rank_idx ON best_scores (season, score DESC, reached_at ASC);
Submit is a private endpoint, reachable from your game servers but not from the internet, so a modified client cannot post a score. The top 100 is cached for five seconds, and a player's rank is the number of players with a higher score plus one:
// Service leaderboard keeps seasonal high scores and ranks.
package leaderboard
import (
"context"
"errors"
"time"
"encore.dev/beta/errs"
"encore.dev/storage/cache"
"encore.dev/storage/sqldb"
)
var db = sqldb.NewDatabase("leaderboard", sqldb.DatabaseConfig{Migrations: "./migrations"})
var cluster = cache.NewCluster("leaderboard", cache.ClusterConfig{
EvictionPolicy: cache.AllKeysLRU,
})
type Entry struct {
Rank int `json:"rank"`
PlayerID string `json:"player_id"`
Score int64 `json:"score"`
}
type Top struct {
Entries []Entry `json:"entries"`
}
// The top 100 is read on every menu screen; five seconds of staleness is fine.
var topCache = cache.NewStructKeyspace[string, Top](cluster, cache.KeyspaceConfig{
KeyPattern: "top100/:key",
DefaultExpiry: cache.ExpireIn(5 * time.Second),
})
// Server-side cap from game design; anything above it is rejected, not ranked.
const maxScorePerMatch = 50_000
type SubmitParams struct {
Season string `json:"season"`
PlayerID string `json:"player_id"`
Score int64 `json:"score"`
}
// Submit is called by the game server at the end of a match, never by the client.
//
//encore:api private method=POST path=/scores
func Submit(ctx context.Context, p *SubmitParams) error {
if p.Score < 0 || p.Score > maxScorePerMatch {
return &errs.Error{Code: errs.InvalidArgument, Message: "score out of range"}
}
// Keep the best score; reached_at only moves when the score improves, so ties
// are broken by who got there first.
_, err := db.Exec(ctx, `
INSERT INTO best_scores (season, player_id, score) VALUES ($1, $2, $3)
ON CONFLICT (season, player_id) DO UPDATE
SET score = EXCLUDED.score, reached_at = now()
WHERE best_scores.score < EXCLUDED.score`,
p.Season, p.PlayerID, p.Score)
return err
}
//encore:api public method=GET path=/leaderboard/:season
func GetTop(ctx context.Context, season string) (*Top, error) {
if top, err := topCache.Get(ctx, season); err == nil {
return &top, nil
} else if !errors.Is(err, cache.Miss) {
return nil, err
}
rows, err := db.Query(ctx, `
SELECT RANK() OVER (ORDER BY score DESC) AS rank, player_id, score
FROM best_scores WHERE season = $1
ORDER BY score DESC, reached_at ASC
LIMIT 100`, season)
if err != nil {
return nil, err
}
defer rows.Close()
top := Top{Entries: []Entry{}}
for rows.Next() {
var e Entry
if err := rows.Scan(&e.Rank, &e.PlayerID, &e.Score); err != nil {
return nil, err
}
top.Entries = append(top.Entries, e)
}
if err := rows.Err(); err != nil {
return nil, err
}
_ = topCache.Set(ctx, season, top) // a failed cache write only costs a query
return &top, nil
}
type PlayerRank struct {
Rank int `json:"rank"`
Score int64 `json:"score"`
}
// GetPlayerRank answers "where am I?" for any player, not just the top 100,
// by counting the players with a strictly higher score.
//
//encore:api public method=GET path=/leaderboard/:season/players/:playerID
func GetPlayerRank(ctx context.Context, season, playerID string) (*PlayerRank, error) {
r := &PlayerRank{}
err := db.QueryRow(ctx, `
SELECT b.score,
1 + (SELECT count(*) FROM best_scores o
WHERE o.season = b.season AND o.score > b.score)
FROM best_scores b WHERE b.season = $1 AND b.player_id = $2`,
season, playerID).Scan(&r.Score, &r.Rank)
if errors.Is(err, sqldb.ErrNoRows) {
return nil, &errs.Error{Code: errs.NotFound, Message: "no score this season"}
}
return r, err
}
encore check compiled this app. Our build machine has no Docker, which the local database needs, so we ran the queries on Postgres 17 with 200,000 players in one season. The top 100 took 0.17 ms from the index. A rank lookup took 1.7 ms for a player around position 2,000 and 15 ms for the player in last place, since that count reads every index entry ahead of them. Two players on 45,000 both showed rank 1, with the one who reached it first listed first, and a lower score from an existing player left their best score unchanged.
That last-place cost is the number to watch. At a few hundred thousand players per season it is fine, and the five-second cache keeps the top 100 off the database during traffic spikes. If "where am I" for millions of players becomes your hottest query, that is the point to add a sorted set as an index next to Postgres, rather than replace it.
Best fit: Games and competitive apps where scores already live with the rest of the player data, with seasons of up to a few hundred thousand ranked players per board, in your own AWS or GCP account.
A sorted set keeps members ordered by score, which is exactly a leaderboard. With go-redis, ZADD with the GT flag keeps each player's best score, and ZREVRANK returns any player's position in logarithmic time:
// leaderboard.go: a seasonal leaderboard on Redis sorted sets.
package leaderboard
import (
"context"
"github.com/redis/go-redis/v9"
)
type Board struct {
rdb *redis.Client
}
func key(season string) string { return "lb:" + season }
// Submit keeps the best score: ZADD GT only updates when the new score is higher.
func (b *Board) Submit(ctx context.Context, season, player string, score int64) error {
return b.rdb.ZAddArgs(ctx, key(season), redis.ZAddArgs{
GT: true,
Members: []redis.Z{{Score: float64(score), Member: player}},
}).Err()
}
// Top returns the n highest scores, best first.
func (b *Board) Top(ctx context.Context, season string, n int64) ([]redis.Z, error) {
return b.rdb.ZRevRangeWithScores(ctx, key(season), 0, n-1).Result()
}
// Rank is 1-based; ZREVRANK is O(log N) at any position.
func (b *Board) Rank(ctx context.Context, season, player string) (int64, error) {
r, err := b.rdb.ZRevRank(ctx, key(season), player).Result()
return r + 1, err
}
A test against an in-memory Redis confirmed that a lower second score for a player is ignored and the ranks come back in order.
Two details need decisions up front. Ties in a sorted set are ordered by member name, so a "first to reach it" rule has to be encoded into the score, for example by combining the score with an inverted timestamp. And Redis is memory-first: if the leaderboard is the only copy of the scores, its persistence settings decide what a restart loses, so most designs still write each result to a database and treat the sorted set as an index they can rebuild.
Best fit: Very large boards where any player's rank is read constantly, and real-time boards that change many times a second.
Start with Postgres when the board has up to a few hundred thousand players per season, since the top of the board is fast from an index and scores stay durable and joinable. Add a Redis sorted set when rank lookups deep in a large board dominate, and keep Postgres as the record you can rebuild it from. Pick Encore when you want the score database, the cache and the private submit endpoint declared in Go and provisioned in your own AWS or GCP account.
Redis sorted sets are the classic choice because ZADD, ZREVRANGE and ZREVRANK are O(log N) at any rank. Postgres with an index on (season, score DESC) serves the top of the board in well under a millisecond and keeps scores durable and queryable alongside the rest of your data. Many games use Postgres as the record and add Redis when rank lookups for millions of players become hot.
Never accept scores from the game client. Have the authoritative game server, which ran the match, submit the result over a private endpoint, validate it against limits that follow from the game design, and keep match records so suspicious scores can be reviewed and removed.
Decide the rule and store what it needs. A common rule is that the player who reached the score first ranks higher, which means storing the time the best score was set and updating it only when the score improves. Redis sorted sets break ties by member name, so a time-based rule needs the time encoded into the score.
Key every score by season, so a new season starts as an empty board while old seasons stay queryable for rewards and history. With Postgres the season is part of the primary key; with Redis each season is its own sorted set.
Deploy to your cloud on AWS and Google Cloud
without managing infrastructure
Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.