{
  "id": "go",
  "title": "Redis leaderboard with Go",
  "url": "https://redis.io/docs/latest/develop/use-cases/leaderboard/go/",
  "summary": "Implement a Redis leaderboard in Go with go-redis and sorted sets",
  "tags": [
    "docs",
    "develop",
    "stack",
    "oss",
    "rs",
    "rc"
  ],
  "last_updated": "2026-04-28T13:01:52-05:00",
  "children": [],
  "page_type": "content",
  "content_hash": "b4e3d70f62c03eb75e82adf090b4481a1bd8c325f8336705bff5a610da6aa7c0",
  "sections": [
    {
      "id": "overview",
      "title": "Overview",
      "role": "overview",
      "text": "This guide shows you how to implement a Redis-backed leaderboard in Go with [`go-redis`](https://redis.io/docs/latest/develop/clients/go). It uses a sorted set to store rank order, Redis hashes to store per-user metadata, and an exported local demo server so you can explore the leaderboard interactively in your browser."
    },
    {
      "id": "overview",
      "title": "Overview",
      "role": "overview",
      "text": "Leaderboards are a natural fit for Redis. A sorted set stores each member together with a numeric score, and Redis maintains the ranking order automatically.\n\nThat gives you:\n\n* Fast score updates for existing users\n* Simple top `n` leaderboard queries\n* Efficient queries for entries around a specific rank position\n* Straightforward trimming to a fixed leaderboard size\n* A clean separation between rank data and richer user metadata\n\nIn this example, the leaderboard score data is stored in a sorted set called `leaderboard:demo`, and each user's metadata is stored in a hash such as `leaderboard:demo:user:player-17`."
    },
    {
      "id": "how-it-works",
      "title": "How it works",
      "role": "content",
      "text": "The flow looks like this:\n\n1. Store each user ID in a sorted set with their score\n2. Store per-user metadata in a separate Redis hash keyed by user ID\n3. Fetch the highest-ranked users with a reverse range query\n4. Fetch users around a given rank by calculating a rank window\n5. Trim the leaderboard after updates so only the top configured entries remain\n\nSeparating rank data from metadata keeps leaderboard operations efficient while still letting the application render richer profile details."
    },
    {
      "id": "installation",
      "title": "Installation",
      "role": "setup",
      "text": "Install the `go-redis` package:\n\n[code example]"
    },
    {
      "id": "the-go-package",
      "title": "The Go package",
      "role": "content",
      "text": "The `RedisLeaderboard` type wraps common leaderboard operations\n([source](leaderboard.go)):\n\n[code example]"
    },
    {
      "id": "data-model",
      "title": "Data model",
      "role": "content",
      "text": "The implementation uses two Redis structures:\n\n[code example]\n\nThe score data lives in the sorted set, while the user details live in hashes keyed by the same user ID.\n\nThe implementation uses:\n\n* [`ZADD`](https://redis.io/docs/latest/commands/zadd) to add or update leaderboard scores\n* [`ZRANGE`](https://redis.io/docs/latest/commands/zrange) with the `REV` option to fetch the highest-ranked members\n* [`ZREVRANK`](https://redis.io/docs/latest/commands/zrevrank) to find a user's rank from the top\n* [`ZREMRANGEBYRANK`](https://redis.io/docs/latest/commands/zremrangebyrank) to trim the lowest-ranked overflow entries\n* [`HSET`](https://redis.io/docs/latest/commands/hset) and [`HGETALL`](https://redis.io/docs/latest/commands/hgetall) to store and load user metadata\n* [`DEL`](https://redis.io/docs/latest/commands/del) to remove metadata for trimmed or deleted users"
    },
    {
      "id": "leaderboard-implementation",
      "title": "Leaderboard implementation",
      "role": "content",
      "text": "The `UpsertUser()` method writes the score, updates metadata, and then trims the board if it exceeds the configured limit:\n\n[code example]\n\nTo fetch users around a rank, the implementation converts the requested rank and count into a reverse range window:\n\n[code example]\n\nGo's `context.Context` is passed to every call, allowing you to set deadlines, propagate cancellation, and control request lifetimes explicitly."
    },
    {
      "id": "metadata-design",
      "title": "Metadata design",
      "role": "content",
      "text": "The leaderboard stores only user IDs and scores in the sorted set. Richer details stay in a separate per-user hash. That means the same user ID can be ranked efficiently while still exposing extra fields such as:\n\n* Display name\n* Short description\n* Team or country\n* Avatar URL\n* Other lightweight profile fields\n\nThis is a useful pattern when the ranking view and the profile view need different data shapes."
    },
    {
      "id": "running-the-demo",
      "title": "Running the demo",
      "role": "content",
      "text": "A local demo server is included to show the leaderboard in action\n([source](demo_server.go)):\n\nTo run the demo, create a small `main.go` file in a separate directory that imports this package and calls `RunDemoServer()`:\n\n[code example]\n\nThen build and run:\n\n[code example]\n\nThe demo server uses the Go standard library for HTTP handling and exposes a small interactive page where you can:\n\n* Add or update a player score and metadata\n* Increase a player's score incrementally\n* View the top `n` players on the leaderboard\n* View the `n` players around a chosen rank\n* Change the maximum number of entries the leaderboard keeps\n* Reset the demo dataset to a known starting state\n\nAfter starting the server, visit `http://localhost:8080`."
    },
    {
      "id": "production-usage",
      "title": "Production usage",
      "role": "content",
      "text": "This guide uses a deliberately small local demo so you can focus on the Redis leaderboard pattern. In production, you will usually want to add more validation, tighter concurrency control, and application-specific lifecycle rules."
    },
    {
      "id": "decide-how-ties-should-behave",
      "title": "Decide how ties should behave",
      "role": "content",
      "text": "Redis sorted sets order primarily by score. When two members have the same score, Redis uses the member value as a secondary ordering rule. If your application needs a different tie-breaker, you may want to encode it in the score or store additional state."
    },
    {
      "id": "consider-how-you-expire-or-archive-old-data",
      "title": "Consider how you expire or archive old data",
      "role": "content",
      "text": "Some leaderboards are permanent, while others reset daily, weekly, or seasonally. Depending on your use case, you may want to:\n\n* Namespace keys by season or event\n* Snapshot historical results elsewhere\n* Rebuild the current leaderboard from upstream data"
    },
    {
      "id": "keep-metadata-lightweight",
      "title": "Keep metadata lightweight",
      "role": "content",
      "text": "Per-user hashes work best for small, frequently accessed profile details. Large profile documents or rarely used attributes are often better kept in another store, with Redis holding only the fields needed to render the leaderboard quickly."
    }
  ],
  "examples": [
    {
      "id": "installation-ex0",
      "language": "bash",
      "code": "go get github.com/redis/go-redis/v9",
      "section_id": "installation"
    },
    {
      "id": "the-go-package-ex0",
      "language": "go",
      "code": "package main\n\nimport (\n    \"context\"\n    \"fmt\"\n    \"log\"\n\n    leaderboard \"leaderboard\"\n\n    \"github.com/redis/go-redis/v9\"\n)\n\nfunc main() {\n    ctx := context.Background()\n\n    rdb := redis.NewClient(&redis.Options{\n        Addr: \"localhost:6379\",\n    })\n\n    board := leaderboard.NewRedisLeaderboard(leaderboard.Config{\n        Client:     rdb,\n        Key:        \"leaderboard:demo\",\n        MaxEntries: 100,\n    })\n\n    _, err := board.UpsertUser(ctx, \"player-1\", 1200, map[string]string{\n        \"name\":        \"Ada\",\n        \"description\": \"Solves production incidents before breakfast.\",\n    })\n    if err != nil {\n        log.Fatal(err)\n    }\n\n    if _, err := board.IncrementScore(ctx, \"player-1\", 25, nil); err != nil {\n        log.Fatal(err)\n    }\n\n    topPlayers, err := board.GetTop(ctx, 5)\n    if err != nil {\n        log.Fatal(err)\n    }\n\n    fmt.Println(topPlayers)\n}",
      "section_id": "the-go-package"
    },
    {
      "id": "data-model-ex0",
      "language": "text",
      "code": "leaderboard:demo\n  player-1 => 1225\n  player-2 => 1180\n  player-3 => 1105\n\nleaderboard:demo:user:player-1\n  name = Ada\n  description = Solves production incidents before breakfast.",
      "section_id": "data-model"
    },
    {
      "id": "leaderboard-implementation-ex0",
      "language": "go",
      "code": "func (lb *RedisLeaderboard) UpsertUser(\n    ctx context.Context,\n    userID string,\n    score float64,\n    metadata map[string]string,\n) (*Entry, error) {\n    metadataKey := lb.metadataKey(userID)\n\n    pipe := lb.client.TxPipeline()\n    pipe.ZAdd(ctx, lb.key, redis.Z{\n        Score:  score,\n        Member: userID,\n    })\n    if len(metadata) > 0 {\n        payload := make(map[string]any, len(metadata))\n        for field, value := range metadata {\n            payload[field] = value\n        }\n        pipe.HSet(ctx, metadataKey, payload)\n    }\n    if _, err := pipe.Exec(ctx); err != nil {\n        return nil, err\n    }\n\n    trimmedUserIDs, err := lb.trimToMaxEntries(ctx)\n    if err != nil {\n        return nil, err\n    }\n\n    entry, err := lb.GetUserEntry(ctx, userID)\n    if err != nil {\n        return nil, err\n    }\n    if entry != nil {\n        entry.TrimmedUserIDs = trimmedUserIDs\n    }\n    return entry, nil\n}",
      "section_id": "leaderboard-implementation"
    },
    {
      "id": "leaderboard-implementation-ex1",
      "language": "go",
      "code": "func (lb *RedisLeaderboard) GetAroundRank(\n    ctx context.Context,\n    rank int,\n    count int,\n) ([]Entry, error) {\n    normalizedRank, err := normalizePositiveInt(rank, \"rank\")\n    if err != nil {\n        return nil, err\n    }\n    normalizedCount, err := normalizePositiveInt(count, \"count\")\n    if err != nil {\n        return nil, err\n    }\n\n    totalEntries, err := lb.GetSize(ctx)\n    if err != nil {\n        return nil, err\n    }\n\n    if totalEntries <= int64(normalizedCount) {\n        return lb.ListAll(ctx)\n    }\n\n    halfWindow := normalizedCount / 2\n    start := max(0, normalizedRank-1-halfWindow)\n    maxStart := int(totalEntries) - normalizedCount\n    if start > maxStart {\n        start = maxStart\n    }\n    end := start + normalizedCount - 1\n\n    entries, err := lb.client.ZRangeArgsWithScores(ctx, redis.ZRangeArgs{\n        Key:   lb.key,\n        Start: start,\n        Stop:  end,\n        Rev:   true,\n    }).Result()\n    if err != nil {\n        return nil, err\n    }\n\n    return lb.hydrateEntries(ctx, entries, start+1)\n}",
      "section_id": "leaderboard-implementation"
    },
    {
      "id": "running-the-demo-ex0",
      "language": "go",
      "code": "package main\n\nimport leaderboard \"leaderboard\"\n\nfunc main() { leaderboard.RunDemoServer() }",
      "section_id": "running-the-demo"
    },
    {
      "id": "running-the-demo-ex1",
      "language": "bash",
      "code": "# Install dependencies\ngo get github.com/redis/go-redis/v9\n\n# Build and run the demo server\ngo build -o demo ./...\n./demo",
      "section_id": "running-the-demo"
    }
  ]
}
