Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 37 ยท Projects and Practice

Project: Leaderboard and Sessions

Model a game backend in DynamoDB: a top-N leaderboard with a sort-key index, sharded score buckets, expiring sessions with TTL and safe counters, with runnable stand-ins.

Games, learning platforms and apps with rankings share a few data problems: keeping a leaderboard that returns the top players fast, tracking sessions that expire by themselves, and updating counters safely under heavy concurrent writes. DynamoDB can do all three at very large scale, but each one has a trap: the leaderboard tempts you to scan, the sessions need correct expiry handling, and the counter creates a hot key.

In this project you will model each piece and run it on a Python stand-in (DynamoDB is not available in the browser). The real API calls are shown as read-only code. It builds on hot partitions, TTL and conditional writes.

Access patterns

# Pattern
B1 Record a player's score for a game; keep only the personal best
B2 Show the top 10 of a game
B3 Show one player's best score for a game
B4 Create a session on login; read it on every request; it expires after 30 minutes of inactivity
B5 Count total plays per game, with thousands of increments per second

The leaderboard

Store each player's best score in an item PK = PLAYER#<id>, SK = SCORE#<game>. For ranking, a sort key must hold the score. A GSI does that: GSI1PK = GAME#<game>, GSI1SK = <score zero-padded>#<playerId>. Zero-padding matters: sort keys sort as text, so 00950 sorts before 01200 but 950 would sort after 1200. Padding to a fixed width makes numeric order equal to text order.

The top 10 is then one query:

Python
# boto3 sketch (read-only here)
resp = table.query(
    IndexName="GSI1",
    KeyConditionExpression=Key("GSI1PK").eq("GAME#asteroids"),
    ScanIndexForward=False,      # highest score first
    Limit=10,
)

To keep only the personal best (B1), update with a condition: SET score = :new, GSI1SK = :key only if attribute_not_exists(score) OR score < :new.

Python Personal best and top 10

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Zero-padding is why 0000001500 ranks above 0000001200. Without it, the text 950 would beat 1500.

Scaling the leaderboard: score buckets

A single GSI1PK = GAME#asteroids puts every write and read on one index partition. For a small game that is fine. For millions of players it is a hot key. Two remedies:

  1. Bucket by score range. GSI1PK = GAME#asteroids#B<n> where n = score // 10000. The top players live in the highest non-empty buckets; "top 10" queries the highest bucket first and moves down if it holds fewer than 10 players.
  2. Shard and merge. Write to GAME#asteroids#<hash % N>, read the top 10 from each shard and merge them (scatter-gather). The merged top 10 is exact, because each global top-10 player is also in the top 10 of their own shard.

"Exact rank of one player" ("you are number 48,213") is hard: DynamoDB cannot count items cheaply. Approximate it, precompute ranks on a schedule, or keep an ordered set in a cache such as Redis, with DynamoDB as the system of record.

Python Top 10 from sharded buckets

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Sessions with TTL

A session item: PK = SESSION#<token>, SK = META, userId, expiresAt (epoch seconds, the TTL attribute). On every request, read the item (GetItem) and check expiresAt yourself, since deletion lags. To make the session sliding (B4), update expiresAt to now + 30 minutes. Do that with a conditional update so an expired session cannot be revived:

Python
table.update_item(
    Key={"PK": f"SESSION#{token}", "SK": "META"},
    UpdateExpression="SET expiresAt = :new",
    ConditionExpression="expiresAt > :now",
    ExpressionAttributeValues={":new": now + 1800, ":now": now},
)

To list or revoke all sessions of a user, add GSI1PK = USER#<id> on session items. Updating the TTL on every request costs a write each time, so only extend if more than a few minutes have passed.

Python Sliding sessions that cannot be revived

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Counters

A play counter (B5) is UpdateItem ... SET plays = plays + :one (or ADD plays :one). Atomic increments are safe from concurrent clients, but one item takes at most about 1,000 writes per second. Options:

  • Shard the counter: COUNT#asteroids#0 to COUNT#asteroids#9; increment a random one; sum them on read (BatchGetItem of 10 keys).
  • Aggregate before writing: each server counts in memory and flushes every second.
  • Stream aggregation: write events, aggregate with a stream consumer (idempotently; see streams).

Note that an increment is not idempotent. A retried request after a timeout can count twice. If exactness matters, use an item per event with a condition on the event ID, and count asynchronously.

Python A sharded counter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why zero-pad a numeric score in a sort key?

    As text, '950' sorts after '1200'. Fixed-width padding makes '0000000950' sort before '0000001200'.
  2. 2. How do you fetch the top 10 players for a game?

    An index sorted by score returns the highest scores first in one request that reads only ten items.
  3. 3. Why must code check expiresAt even with TTL enabled?

    TTL deletion is a delayed background process, so the application must treat expired items as invalid.
  4. 4. What is a downside of a simple ADD counter on one item?

    One item handles roughly 1,000 writes per second, and a retried increment may count twice.

Summary

  • A score-sorted GSI gives top-N queries; zero-pad numbers so text order equals numeric order.
  • Use conditional writes to keep personal bests.
  • Bucket or shard hot leaderboards and merge top-N results from the shards.
  • Sessions use TTL for cleanup but are validated on read; sliding expiry uses a conditional update.
  • Counters are atomic but hot and non-idempotent: shard them or aggregate first.

Next: Practice: Design Challenges