---
title: Leaderboard API
canonical_url: "https://trophy.so/developers/leaderboards"
description: "Leaderboard API for apps with daily, weekly, monthly, and all-time rankings. Real-time rankings with support for dynamic segmentation based on user attributes. SDKs for Node.js, Python, Go, Java, PHP, Ruby, and .NET."
---

# The API for leaderboards

Add recurring, all-time, and segmented leaderboards to your app in under an hour. Trophy handles scaling high-frequency leaderboard infrastructure so you stay focused on user experience. Start for free, scale to millions of users.

[Full feature documentation](https://docs.trophy.so/features/leaderboards.md)

## Quickstart: rank users from metric events

Send metric events to update rankings automatically, then fetch the board or a user’s position. Segment rankings with user attributes when you need cohorts.

```ts
import { TrophyApiClient } from "@trophyso/node";

const trophy = new TrophyApiClient({ apiKey: process.env.TROPHY_API_KEY });

// 1. Track activity that powers the leaderboard
const eventResponse = await trophy.metrics.event("lessons", {
  user: {
    id: "user-123",
    attributes: { city: "London" },
  },
  value: 1,
});

console.log("Leaderboard updates:", eventResponse.leaderboards);

// 2. Fetch the full board rankings
const board = await trophy.leaderboards.get("weekly-words");

for (const entry of board.rankings) {
  console.log(entry.rank, entry.userName, entry.value);
}

// 3. Fetch one user's rank and history
const ranking = await trophy.users.leaderboards("user-123", "weekly-words");

console.log("Rank:", ranking.rank, "Value:", ranking.value);
```

## Why use Trophy's leaderboard API?

Building a real-time leaderboard API from scratch is a classic distributed systems challenge. Ranking at scale requires more than a sorted query. Trophy's API handles the infrastructure so you can keep focused on the user experience.

| Consideration | Trophy | Build in-house | Why it matters |
| --- | --- | --- | --- |
| Integration Time | Leaderboards populate automatically from user activity events. Fetch ranked results with one API call. | Build ranking engine, score aggregation, pagination, time-windowed boards, and tie-breaking logic. Expect 4-8 weeks. | Leaderboards are more than a sorted list. Time-windowed boards, pagination, tie-breaking, and real-time position updates require careful design. |
| Reliability | Consistent rankings with atomic score updates and real-time position accuracy. | Concurrent score updates can cause ranking inconsistencies. Ensuring globally consistent ordering under write contention requires distributed locking or conflict resolution. | Users notice immediately if their leaderboard position is wrong. Ranking bugs erode trust and undermine the competitive motivation leaderboards are meant to create. |
| Scalability | Trophy's Redis-based infrastructure processes millions of synchronous leaderboard updates every day, handling edge cases like tie-breaks, concurrent updates, automated reset mechanics and more. | Real-time leaderboards are a classic hot-key scaling problem. Every score update triggers a re-rank, and naive implementations hit database contention walls even at modest scale. | Sorted set operations that work at 1K users break at 100K. Sharding leaderboards without sacrificing global consistency is one of the harder distributed systems problems. |
| Ongoing Maintenance | Use the Trophy dashboard to configure ranking logic, repetition and segmentation settings in minutes. | Adding recurring leaderboards (weekly, monthly), archiving historical results, and managing time-window transitions requires ongoing engineering. | Product teams will want to experiment with different leaderboard formats — weekly sprints, seasonal competitions, team boards. Each should be a config change, not a backlog item. |
| Feature Development | Recurring boards, user position lookups, surrounding-user context, and historical archives ship regularly. | Each new feature — relative positioning, group boards, recurring resets — adds complexity to your ranking and aggregation infrastructure. | Leaderboards evolve from simple all-time lists to recurring competitions with surrounding-user context. Building each iteration in-house adds up quickly. |

## Leaderboard API endpoints

Use Trophy's leaderboard API to fetch real-time rankings and user positions. Leaderboards populate automatically from the metric events you track — no additional ranking code needed.

### `POST /metrics/{key}/event`

Send a metric event to track user activity and power leaderboards.

Docs: https://docs.trophy.so/api-reference/endpoints/metrics/send-a-metric-change-event.md

```ts
// Track a user event
await trophy.metrics.event("lessons", {
    user: {
      id: "user-123",
      "attributes": {
        "city": "London" // Optional, segment rankings by user attributes
      }
    },
    value: 1
  }
);

// This single event:
// - Records user activity
// - Computes leaderboard rankings
// - Returns new leaderboard rankings
```

### `GET /leaderboards/{key}`

Get a specific leaderboard and rankings. Supports pagination and filtering.

Docs: https://docs.trophy.so/api-reference/endpoints/leaderboards/get-leaderboard.md

```ts
// Fetch leaderboard rankings
const board = await trophy.leaderboards.get("weekly-words");

// Response:
// {
//   rankings: [
//     { rank: 1, userId: "...", value: 5000, userName: "Sarah" },
//     { rank: 2, userId: "...", value: 4500, userName: "Alex" },
//     ...
//   ],
//   runUnit: "day",
//   runInterval: 7
// }
```

### `GET /users/{id}/leaderboards/{key}`

Get a user's rank, value, and history for a specific leaderboard.

Docs: https://docs.trophy.so/api-reference/endpoints/users/get-a-users-leaderboard.md

```ts
// Get a user's leaderboard data
const ranking = await trophy.users.leaderboards(
  "user-123", "weekly-words"
);

// Response:
// { rank: 2, value: 4500, history: [...] }
```

## Code examples

### leaderboard-ui.tsx

```ts
// Fetch and render leaderboard

const board = await trophy.leaderboards
  .get("weekly-words");

// Render leaderboard rows
return board.rankings.map(entry => (
  <LeaderboardRow
    rank={entry.rank}
    name={entry.userName}
    score={entry.value}
  />
));
```

## FAQ

### What types of leaderboards and scoreboards can I create?

Trophy's leaderboard API supports perpetual (all-time) rankings and recurring leaderboards that reset on a schedule — daily, weekly, monthly, or any custom interval. You can run multiple leaderboards tracking different metrics simultaneously.

### How are leaderboard rankings calculated?

Leaderboard rankings are automatically calculated from the metric events you send. When a user sends an event for a metric tied to a real-time leaderboard, their score updates and their rank recalculates immediately.

### Can I build competitive features and competitions?

Yes. Trophy's recurring leaderboard API lets you run time-bounded competitions — weekly writing challenges, monthly contests, or custom periods. The API returns rankings with user scores, making it easy to display standings, announce winners, and drive re-engagement. Across Trophy's platform, apps using social leaderboard features average 34% longer user streaks (5.69 days versus 4.25 without).

### How do I get a specific user's rank and position?

Use the [get user leaderboard](https://docs.trophy.so/api-reference/endpoints/users/get-a-users-leaderboard) endpoint to fetch a user's rank, score, and rank history for any leaderboard. This is useful for showing users their personal standing and progress over time.

### Does the leaderboard API support pagination?

Yes. The [get leaderboard](https://docs.trophy.so/api-reference/endpoints/leaderboards/get-leaderboard) endpoint supports limit and offset parameters for paginating through rankings. This lets you load leaderboards incrementally and build infinite-scroll or paginated UIs.

### Can I show leaderboards in React, React Native, or mobile apps?

Yes. Adding a mobile app leaderboard with Trophy uses server-side SDKs (Node.js, Python, Go, Java, PHP, Ruby, and .NET) to handle ranking logic on your backend. The API returns ranked entries with scores and user data that you can render in any frontend — React, React Native, Next.js, Swift, Kotlin, Flutter, or any other framework.
