GitHubGet started
Multiplayer & Modding

leaderboard/selfhost

import "github.com/nsgo-dev/game/pkg/online/leaderboard/selfhost"

leaderboard/selfhost is a self-hostable leaderboard service for games that run on several platforms or on platforms without a game service (the web, Windows, Linux). Where leaderboard shows Game Center's and Play Games' own boards, this service keeps one board for every platform, keyed by the account the account service signs players in to, so a score from a browser and a score from a phone land on the same board.

It is server-side code. It needs only the standard library, the YAML package, accounts/authtoken and admin, whose settings block its configuration carries, so it links none of the account service's database drivers.

Package What it holds
leaderboard/selfhost Service, Config, the Store interface with MemoryStore and FileStore, ProofSigner and the HTTP Handler
cmd/leaderboardd A standalone HTTP server with its scores in a directory

Declaring boards

The service reads its boards from a versioned YAML file:

version: 1
audience: leaderboard
proofTTL: 10m
boards:
  - name: high-score
    order: descending
    reset: allTime
  - name: weekly-sprint
    order: ascending
    reset: weekly
    weekStart: monday
    keep: 4
    validation: signed
    min: 1
    max: 3600000
serverKeys:
  - id: 2317febd373fcbcd
    key: hze+0cYruVRddgjkbHzgCeWWJbEsBkn6K8JNHRDf6Wg=
allowedOrigins:
  - https://play.example.com
metrics: 127.0.0.1:9103
Field Meaning
version Schema version, 1
audience The token audience the handler accepts, leaderboard when absent; the account service must list it in its audiences, and it must differ from the key set's audience
proofTTL How old a game server's score proof may be, from 1s to 24h; 10m when absent
boards The boards, in the order the service lists them
name The board's key in URLs and in the data directory: a-z, 0-9, ., _ and -, up to 64 characters, starting with a letter or digit
order descending ranks the highest score first (points), ascending the lowest (times)
reset allTime, daily (midnight UTC) or weekly (midnight UTC on weekStart)
weekStart The day a weekly board resets on, a lowercase English weekday; monday when absent
keep How many earlier periods of a daily or weekly board stay readable after a reset, 1 to 1000; 1 when absent
validation signed accepts a score only with a game server's proof; absent trusts the player's client
min, max The scores the board accepts; at most 2^53-1 either way, so every score survives a JSON number in JavaScript
serverKeys The Ed25519 public keys game servers sign proofs with; a signed board needs at least one
allowedOrigins Web origins whose pages may call the service; omitted when empty
metrics The address leaderboardd serve serves /healthz, /readyz and /metrics on, such as 127.0.0.1:9103, a listener of its own (see Health and metrics); omitted when unset, and then none of them is served

ParseConfig refuses unknown fields, duplicate keys, other versions, a second YAML document, a metrics address without a port and an origin that is duplicated or has a path, query, fragment, user, wildcard, port outside 1 to 65535 or scheme other than http and https. Optional fields keep what the file says, and Config.Marshal writes the fields in the order above, omitting allowedOrigins when empty and metrics when unset, so a file in that form parses and marshals back byte for byte.

Ranking

A board ranks each account's best score in its current period. A score only counts when it beats the account's best, by the board's order; an equal score keeps the earlier one. Equal scores rank by who reached them first, then by account ID, so every entry has its own rank.

Periods are in UTC. A daily or weekly board starts a new, empty period at its reset, and the period before stays readable, with as many earlier ones as keep says. Each period has an ID: all for an all-time board, otherwise the UTC date it starts on, such as 2026-11-23. A query names its period as current (the default), previous, or an earlier period's ID.

svc, err := selfhost.New(ctx, cfg, selfhost.Options{
	Store:  store,      // selfhost.OpenFileStore("scores", selfhost.FileStoreOptions{})
	Tokens: verifier,   // authtoken.NewVerifierFor(keySet, cfg.TokenAudience()), not authtoken.NewVerifier
	Logger: slog.Default(),
})

res, err := svc.Submit(ctx, selfhost.Submission{Board: "high-score", Account: claims.Subject, Score: 4200})
// res.Entry.Rank, res.Improved, res.Period.ID

page, err := svc.Top(ctx, "high-score", "current", 0, 25)               // ranks 1-25
near, err := svc.Around(ctx, "weekly-sprint", "previous", account, 5)   // 5 above and 5 below
pals, err := svc.Friends(ctx, "high-score", "", friendIDs)              // these accounts, ranked
Method What it does
Submit Records a score in the board's current period; Result.Improved reports whether it became the account's best
Top Up to limit entries (at most 100) from rank offset+1
Around The account's entry with up to radius entries (at most 50) each side, shifted at either end so the window keeps its size
Friends The entries of up to 200 accounts the game supplies (a platform friend list, its own social graph), each with its rank on the whole board
Rank One account's entry
Boards Every board with its current period and the earlier periods still readable

Errors are ErrUnknownBoard, ErrUnknownPeriod (no such period, or no longer kept), ErrNotRanked, ErrInvalidAccount, ErrScoreOutOfRange, ErrProofRequired, ErrInvalidProof, ErrProofExpired and ErrInvalidQuery.

Each period is an order-statistic skip list in memory, so every query costs O(log n) plus the entries it returns. On a board of a million accounts the benchmarks take about 7 µs for the top 100, 60 µs for 100 entries deep in the board, 40 µs around an account and 10 µs to submit (go tool nsgo test ./pkg/online/leaderboard/selfhost -run '^$' -bench .); a benchmark fails when a query takes more than 50 ms, and CI runs the query benchmarks on every pull request.

Server-validated scores

A client can send any score it likes. A board with validation: signed accepts a score only with a proof from the game server: after the server decides a match or checks a replay, it signs the board, the account and the score, and hands the proof to that player's client, which submits it beside the score.

key, err := authtoken.ParsePrivateKey(pemData) // from leaderboardd genkey
prover, err := selfhost.NewProofSigner(key)
proof, err := prover.Sign("weekly-sprint", claims.Subject, result.TimeMillis)
// send proof to the player with the match result

A proof is v1.<key id>.<unix seconds>.<signature>, an Ed25519 signature over the board, account, score and time. The service refuses a missing proof (ErrProofRequired), one signed by a key not in serverKeys, for another board, account or score, or issued in the future (ErrInvalidProof), and one older than proofTTL or, on a daily or weekly board, issued before the current period began (ErrProofExpired), so a score signed before a reset does not count after it. Options.Leeway allows for clock skew between the machines. Because a proof names the account, a player cannot submit someone else's.

Operators, metadata and monthly periods

A board may declare operator: best|set|increment|decrement, metadataMaxBytes and reset: monthly. best is the default and keeps the better score. set replaces the score, increment adds the submitted score, which must not be negative, and decrement subtracts it; a result beyond MaxSafeScore is score_out_of_range. These three operators require validation: signed, because a client could otherwise submit any change, and the configuration refuses an unknown operator. A submission may carry a subscore and a JSON metadata object, which replace the entry's together with its score: on a best board a higher subscore wins a tie in score, and the metadata is limited to metadataMaxBytes (0 to 4096, 4096 when zero). A server proof signs the board, account and score, not the subscore or the metadata. A monthly board starts over on the first day of each UTC calendar month and names its periods YYYY-MM. A configuration without these fields means what it meant before.

HTTP

Service.Handler serves the service as JSON. Every request except GET /v1/openapi.yaml carries the player's account token as Authorization: Bearer <token>; the handler verifies it offline with Options.Tokens and accepts only a token for the configuration's audience (see Token audiences), so the token a player sends a game server cannot submit scores for them; New refuses a verifier for another audience or for the game servers' audience of its key set, and the configuration cannot name accounts, the account service's own audience. The token's subject is the account a score is submitted for, so a player can only submit their own scores. The full machine-readable contract is published as an OpenAPI 3.1 description and served live at GET /v1/openapi.yaml.

Request Response
GET /v1/openapi.yaml the OpenAPI 3.1 description in YAML (unauthenticated)
GET /v1/boards {"boards": [{"name", "order", "operator", "metadataMaxBytes", "reset", "validation", "current", "previous"}]}
POST /v1/boards/{board}/scores {"score", "subscore", "metadata", "proof"} {"period", "entry", "total", "improved"}
GET /v1/boards/{board}/top?period=&offset=&limit= a page; limit 25 when absent
GET /v1/boards/{board}/around?period=&radius= a page around the token's account; radius 5 when absent
POST /v1/boards/{board}/friends?period= {"accounts": [id]} a page of those accounts

Pages leave out the accounts an operator hid (see Operator routes), except the token's own account, and the ranks below a hidden account close up. A page is {"board", "period", "total", "entries"}, a period {"id", "start", "end"} (no start or end for an all-time board) and an entry {"rank", "account", "score", "subscore", "metadata", "achieved"}. Errors are {"error": code}: invalid_token 401; proof_required, invalid_proof and proof_expired 403; unknown_board, unknown_period and not_ranked 404; bad_request, invalid_account, invalid_metadata and score_out_of_range 400; request_too_large 413; unavailable 503; internal 500.

Entries carry account IDs; a game that shows names looks them up in its own profiles. For allowedOrigins the handler answers CORS preflight requests and allows Authorization and Content-Type; other origins receive no CORS headers. Put the handler behind TLS and a rate limiter.

Storage

The service keeps its records in a Store. NewMemoryStore is for tests. OpenFileStore keeps one JSON Lines file per board period at <dir>/<board>/<period>.jsonl, a line per new best score:

{"account":"3f9a...","score":4200,"achieved":"2026-11-24T09:15:02.5Z"}

New loads the files. It cuts off a last line a crash left half written, rewrites a file whose lines are mostly superseded scores with one line per account, and deletes the periods that are older than the ones a board keeps; a reset deletes them as it happens. A failed write is taken back, so the file never holds a score the client was told was lost. New deletes only what it can place: scores of a board removed from the configuration, and of periods stored under a board's earlier reset or weekStart, stay on disk, are not served, and are logged as a warning. A period later than the current one, as a machine whose clock is behind at boot sees it, is kept and served once the clock reaches it. FileStoreOptions.Sync flushes every write to the disk, for a machine that may lose power. Operators' changes besides scores, the hidden accounts and the manual resets, live in <dir>/_admin.yaml, a versioned YAML file (see File formats) rewritten through a temporary file and a rename; deleting an account's entry rewrites its period file the same way. A Store of your own implements Load, Save, Drop, DeleteAccount, LoadAdmin, SaveHidden, DeleteHidden and SaveReset.

SQL persistence

selfhost/sqlitestore.Open opens a pure-Go SQLite database and selfhost/pgstore.Open opens Postgres; pass either store to selfhost.New. Both create three tables, leaderboard_records with one row per board, period and account holding the score, achievement time, subscore and metadata, leaderboard_hidden with one row per hidden account and leaderboard_resets with one row per manual reset, and record the schema version in leaderboard_schema (3); a version 1 database gains the subscore and metadata columns, its rows reading as subscore 0 and no metadata, a version 2 database gains the two new tables, and a newer version is refused. Each write is a transaction: on a best board it keeps the better score, then the higher subscore, so retries and concurrent writers cannot replace a best score with a worse one; on a set, increment or decrement board it stores the result the service computed. The service still ranks from memory, so only one process may serve a board. SQLite uses a single writer connection and WAL mode; Postgres takes transaction advisory locks for the migration and each record's write.

leaderboardd

leaderboardd init   -config leaderboards.yaml
leaderboardd genkey -key server.pem
leaderboardd serve  -config leaderboards.yaml -keyset keys.yaml -data scores -addr :8081

init writes a configuration with one all-time high-score board and no allowedOrigins to edit; if a web build calls the service from another origin, add the game page's origin to allowedOrigins in leaderboards.yaml before serve. genkey writes a game server signing key and prints the serverKeys entry to paste into the configuration. serve verifies player tokens with the account service's key set file (accountsd genkey writes it), accepts only those for the configuration's audience, refuses to start when that is the key set's audience, which names the game's servers, keeps scores under -data, and stops on SIGINT or SIGTERM. -sync flushes every score to the disk before acknowledging it, for a machine that may lose power. In place of -data, -sqlite <file> keeps scores in an SQLite database and -postgres <dsn> (or LEADERBOARD_POSTGRES_DSN) in Postgres; serve refuses more than one of the three. With metrics set, serve also answers /healthz, /readyz and /metrics on that address, exporting requests and the entries of each board's current period (see Health and metrics).

An optional admin: block at the end of leaderboards.yaml makes serve run an admin listener on an address of its own, which accepts operator sessions and the account service's admin bearer tokens and serves the operator routes; without it no admin route exists. The configuration refuses admin as its audience.

Operator routes

Service.AdminRoutes returns the leaderboard's operator routes, which leaderboardd serve adds to its admin listener when the configuration has an admin: block. Each needs one permission, and every call that changes something writes an audit record naming the operator, with board:<board>/<account> or board:<board> as its subject. The built-in moderator role may read, delete and hide; operator and owner may also reset.

Request Permission Response
GET /admin/v1/leaderboard/boards leaderboard.read {"boards": [{"name", "reset", "current", "previous", "hidden"}]}, each period with its number of entries and hidden the number of accounts hidden on the board
GET /admin/v1/leaderboard/boards/{board}/entries?period=&account=&offset=&limit= leaderboard.read a page ranking every entry, hidden ones included, each with "hidden"; with account, that account's entry alone
DELETE /admin/v1/leaderboard/boards/{board}/entries/{account}?period= leaderboard.delete {"board", "account", "periods"}, latest first; period is required: current, previous, a kept period's ID, or all to erase the account from the board
GET /admin/v1/leaderboard/boards/{board}/hidden leaderboard.read {"hidden": [{"account", "until", "reason", "by", "at"}]}
POST /admin/v1/leaderboard/boards/{board}/hide {"account", "until", "reason"} leaderboard.hide the hiding now in force
POST /admin/v1/leaderboard/boards/{board}/unhide {"account"} leaderboard.hide 204; audited as leaderboard.unhide
POST /admin/v1/leaderboard/boards/{board}/reset leaderboard.reset {"board", "current", "previous"}

Every change goes through the ranking in memory, so it shows on the next query, and through the store, so it survives a restart. A deleted entry is gone from top, around and friends, and the ranks below it close up. A hidden account is left out of every other player's pages, with the ranks below it closing up for them, while its own top, around, friends and submissions still show it at the rank it holds among the accounts not hidden; until, an RFC 3339 time in the future, ends the hiding, and without it the account stays hidden until unhidden. reason (up to 256 bytes) and the operator are kept for operators and never shown to players. A reset of a daily, weekly or monthly board ends the current period at the present second and begins one whose ID is that UTC time (20261125T163000Z), running to the end of the period it cut short; the ended period becomes previous, the board keeps as many earlier periods as its keep says, and its own reset still comes on schedule. An all-time board keeps no earlier period, so its reset removes every entry. A second reset within the same second, or one at a time before the board's last reset because the clock stepped back, is reset_too_soon (409). The audit record of a delete lists each removed entry's period, score, subscore and achievement time, and that of a reset the number of entries it removed, so an operator's mistake can be seen and repaired by hand. Errors are {"error": code}: bad_request and invalid_account 400, unauthorized 401, forbidden and csrf 403, unknown_board, unknown_period, not_ranked and not_hidden 404, request_too_large 413, unavailable 503, internal 500. The routes are in the OpenAPI description beside the player routes.

From Go, Service.DeleteAccount, Hide, Unhide, HiddenAccounts and ResetBoard do the same; DeleteAccount(ctx, board, selfhost.AllPeriods, account) erases an account's data from the board: it also forgets the account in periods the service does not serve and removes its hiding, with the reason and operator, and it succeeds even when no served period held an entry. Top and Friends show what any player sees; TopAs and FriendsAs take the viewing account, which the HTTP handler passes from the token. Changes made through one process show in another process sharing a Postgres store only after it restarts, as scores do.

Tournament lifecycle core

selfhost.Tournament adds a deterministic lifecycle boundary for limited-entry competitions. Join enforces the scheduled window and MaxEntrants, Submit enforces JoinRequired and MaxAttempts, and Round computes recurring windows from the configured duration. Each round keeps its own best scores and attempt counts, so MaxAttempts is per round, and the last round ends at End even when that cuts it short. EndRound settles every round that has ended, once each and in round order, sorts ties by account ID and invokes OnRoundEnd with each round's ranked entries, outside the tournament's lock; a submission to a settled round is ErrTournamentClosed. The core is in-memory: a restart forgets entrants, scores and which rounds were settled, so persistent adapters must record closed rounds before enabling reward delivery.

See Deploying backend services for production store and daemon topology.

Edit this page