Multiplayer Game
IMPORTANT: Before doing anything, you MUST read BASE_SKILL.md in this skill's directory. It contains essential guidance on debugging, error handling, state management, deployment, and project setup. Those rules and patterns apply to all RivetKit work. Everything below assumes you have already read and understood it.
Working Examples
If you need a reference implementation, read the raw working example code in these templates:
Patterns for building multiplayer games with RivetKit, intended as a practical checklist you can adapt per genre.
Starter Code
Start with one of the working examples on GitHub and adapt it to your game. Do not start from scratch for matchmaking and lifecycle flows.
| Game Classification |
Starter Code |
Common Examples |
| Battle Royale |
GitHub |
Fortnite, Apex Legends, PUBG, Warzone |
| Arena |
GitHub |
Call of Duty TDM/FFA, Halo Slayer, Counter-Strike casual, VALORANT unrated, Overwatch Quick Play, Rocket League |
| IO Style |
GitHub |
Agar.io, Slither.io, surviv.io |
| Open World |
GitHub |
Minecraft survival servers, Rust-like worlds, MMO zone/chunk worlds |
| Party |
GitHub |
Fall Guys private lobbies, custom game rooms, social party sessions |
| Physics 2D |
GitHub |
Top-down physics brawlers, 2D arena games, platform fighters |
| Physics 3D |
GitHub |
Physics sandbox sessions, 3D arena games, movement playgrounds |
| Ranked |
GitHub |
Chess ladders, competitive card games, duel arena ranked queues |
| Turn-Based |
GitHub |
Chess correspondence, Words With Friends, async board games |
| Idle |
GitHub |
Cookie Clicker, Idle Miner Tycoon, Adventure Capitalist |
Server Simulation
Game Loop And Tick Rates
| Pattern |
Use When |
Implementation Guidance |
| Fixed realtime loop |
Battle Royale, Arena, IO Style, Open World, Ranked |
Run in run with sleep(tickMs) and exit on c.aborted. |
| Action-driven updates |
Party, Turn-Based |
Mutate and broadcast only on actions/events rather than scheduled ticks. |
| Coarse offline progression |
Any mode with idle progression |
Use c.schedule.after(...) with coarse windows (for example 5 to 15 minutes) and apply catch-up from elapsed wall clock time. |
Physics
Start with custom kinematic logic for simple games. Switch to a full physics engine when you need joints, stacked bodies, high collision density, or complex shapes (rotated polygons, capsules, convex hulls, triangle meshes).
Pick one engine per simulation. Keep frontend-only libs out of backend simulation paths and treat server state as authoritative.
| Dimension |
Primary Engine |
Fallback Engines |
Example Code |
| 2D |
@dimforge/rapier2d |
planck-js, matter-js |
GitHub |
| 3D |
@dimforge/rapier3d |
cannon-es, ammo.js |
GitHub |
Spatial Indexing
For non-physics spatial queries, use a dedicated index instead of naive O(n^2) checks:
| Index Type |
Recommendation |
| AABB index |
For AOI, visibility, and non-collider entities, use rbush for dynamic sets or flatbush for static-ish sets. |
| Point index |
For nearest-neighbor or within-radius queries, use d3-quadtree. |
Networking & State Sync
Netcode
| Model |
When To Use |
Implementation |
| Hybrid (client movement, server combat) |
Shooters, action sports, ranked duels |
Client owns movement and sends capped-rate position updates. Server validates for anti-cheat. Combat (projectiles, hits, damage) is fully server-authoritative. |
| Server-authoritative with interpolation |
IO Style, persistent worlds |
Client sends input commands. Server simulates on fixed ticks and publishes authoritative snapshots. Client interpolates between snapshots. |
| Server-authoritative (basic logic) |
Turn-based, event-driven |
Server validates and applies discrete actions (turns, phase transitions, votes). Client displays confirmed state. |
Realtime Data Model
- Snapshots and diffs: Publish state as events. Send a full snapshot on join/resync, then per-tick diffs for regular updates.
- Batch per tick: Keep events small and typed. Batch high-frequency updates per tick.
- Avoid UI framework state for game updates: Use
requestAnimationFrame or a Canvas/Three.js loop for simulation, not React state. Reserve UI framework state for menus, HUD, and forms.
- Broadcast vs per-connection: Use
c.broadcast(...) for shared updates and conn.send(...) for private/per-player data.
Shared Simulation Logic
Shared simulation logic runs on both the client and the server. For example, an applyInput(state, input, dt) function that integrates velocity and clamps to world bounds can run on the client for prediction and on the server for validation.
- Hybrid modes: Client runs shared movement as primary authority, server runs it for anti-cheat validation.
- Server-authoritative modes: Client uses shared logic for interpolation and prediction only.
- Keep it pure: Movement integration, input transforms, collision helpers, and constants only.
- Put shared code in
src/shared/: Keep deterministic helpers in src/shared/sim/* with no side effects.
Interest Management
Control what each client receives to reduce bandwidth and prevent information leaks.
Per-Player Replication Filters
- Filter by relevance: Send each client only state relevant to that player (proximity, line-of-sight, team, or game phase).
- Shooters and action games: Limit replication by proximity and optional field-of-view checks.
- Server-side only: Clients should never receive data they should not see.
Sharded Worlds
- Partition large worlds: Use chunk actors keyed by
worldId:chunkX:chunkY.
- Subscribe to nearby chunks: Clients connect only to nearby partitions (for example a 3x3 chunk window).
- Use sparingly: Only when the world is large and state-heavy (sandbox builders, MMOs), not as a default for small matches.
Backend Infrastructure
Persistence
- In-memory state: Best for realtime game state that changes every tick (player positions, inputs, match phase, scores).
- SQLite (
rivetkit/db): Better for large or table-like state that needs queries, indexes, or long-term persistence (tiles, inventory, matchmaking pools). Serialize DB work through a queue since multiple actions can hit the same actor concurrently.
Matchmaking Patterns
Common building blocks used across the architecture patterns below.
Actor Topology
| Primitive |
Use When |
Typical Ownership |
matchmaker["main"] + match[matchId] |
Session-based multiplayer (battle royale, arena, ranked, party, turn-based) |
Matchmaker owns discovery/assignment. Match owns lifecycle and gameplay state. |
chunk[worldId,chunkX,chunkY] |
Large continuous worlds that need sharding |
Each chunk owns local players, chunk state, and local simulation. |
world[playerId] |
Per-player progression loops (idle/solo world state) |
Per-player resources, buildings, timers, and progression. |
player[username] |
Canonical profile/rating reused across matches |
Durable player stats (for example rating and win/loss). |
leaderboard["main"] |
Shared rankings across many matches/players |
Global ordered score rows and top lists. |
Queueing Strategy
- Multiple players can hit the matchmaker at the same time, so actions like find/create, queue/unqueue, and close need to be serialized through actor queues to avoid races.
- Match-local actions (gameplay, scoring) do not need queueing unless they write back to the matchmaker.
Security And Anti-Cheat
Start with this baseline, then harden further for competitive or high-risk environments.
Baseline Checklist
- Identity: Use
c.conn.id as the authoritative transport identity. Treat playerId/username in params as untrusted input and bind through server-issued assignment/join tickets.
- Authorization: Validate the caller is allowed to mutate the target entity (room membership, turn ownership, host-only actions).
- Input validation: Clamp sizes/lengths, validate enums, and validate usernames (length, allowed chars, avoid unbounded Unicode).
- Rate limiting: Per-connection rate limits for spammy actions (chat, join/leave, fire, movement updates).
- State integrity: Server recomputes derived state (scores, win conditions, placements). Never allow client-authoritative changes to inventory/currency/leaderboard totals.
Movement Validation
For any mode with client-authoritative movement (hybrid flows), clients may send position/rotation updates for smoothness, but the server must:
- Enforce max delta per update (speed cap) based on elapsed time.
- Reject or clamp teleports.
- Enforce world bounds (and basic collision if applicable).
- Rate limit update frequency (for example 20Hz max).
Architecture Patterns
Each game type below starts with a quick summary table, then details actors and lifecycle.
Battle Royale
| Topic |
Summary |
| Matchmaking |
Immediate routing to the fullest non-started lobby (oldest tie-break); players wait in lobby until capacity, then the match starts. |
| Netcode |
Hybrid. Client owns movement, camera, and local prediction. Server owns zone state, projectiles, hit resolution, eliminations, loot, and final placement. |
| Tick Rate |
10 ticks/sec (100ms) with a fixed loop for zone progression and lifecycle checks. |
| Physics |
Client owns movement with server anti-cheat validation; projectiles, hits, and damage are server-authoritative. Use @dimforge/rapier3d for 3D or @dimforge/rapier2d for top-down 2D. |
Actors
Key: matchmaker["main"]
Responsibility: Finds or creates lobbies, tracks pending reservations, and maintains occupancy.
Actions
findMatch
pendingPlayerConnected
updateMatch
closeMatch
Queues
findMatch
pendingPlayerConnected
updateMatch
closeMatch
State
- SQLite
matches
pending_players
player_count includes connected and pending players
Key: match[matchId]
Responsibility: Runs lobby/live/finished phases, owns player state, zone progression, and eliminations.
Actions
connect
- Movement and combat actions
Queues
State
- JSON
phase
players
zone
eliminations
snapshot data
Lifecycle
sequenceDiagram
participant C as Client
participant MM as matchmaker
participant M as match
C->>MM: findMatch()
alt no open lobby
MM->>M: create(matchId)
end
MM-->>C: {matchId, playerId}
C->>M: connect(playerId)
M->>MM: pendingPlayerConnected(matchId, playerId)
MM-->>M: accepted
Note over M: lobby countdown -> live
M-->>C: snapshot + shoot events
M->>MM: closeMatch(matchId)
Arena
| Topic |
Summary |
| Matchmaking |
Mode-based fixed-capacity queues (duo, squad, ffa) that build only full matches and pre-assign teams (except FFA). |
| Netcode |
Hybrid. Client owns movement plus prediction and smoothing. Server owns team or FFA assignment, projectiles, hit resolution, phase transitions, and scoring. |
| Tick Rate |
20 ticks/sec (50ms) with a tighter loop for live team and FFA snapshots. |
| Physics |
Medium to high intensity; client movement with server validation and server-authoritative combat/entities. |
Actors
Key: matchmaker["main"]
Responsibility: Runs mode queues, builds full matches, assigns teams, and publishes assignments.
Actions
queueForMatch
unqueueForMatch
matchCompleted
Queues
queueForMatch
unqueueForMatch
matchCompleted
State
- SQLite
player_pool
matches
assignments keyed by connection and player
Key: match[matchId]
Responsibility: Runs match phases and in-match player/team state for score and win conditions.
Actions
Queues
State
- JSON
phase
players
team assignments
score and win state
Lifecycle
sequenceDiagram
participant C as Client
participant MM as matchmaker
participant M as match
C->>MM: queueForMatch(mode)
Note over MM: enqueue in player_pool
Note over MM: fill when capacity reached
MM->>M: create(matchId, assignments)
Note over MM: persist assignments
MM-->>C: assignmentReady
C->>M: connect(playerId)
Note over M: waiting -> live when all players connect
M->>MM: matchCompleted(matchId)
IO Style
| Topic |
Summary |
| Matchmaking |
Open-lobby routing to the fullest room below capacity; room counts are heartbeated and new lobbies are auto-created when needed. |
| Netcode |
Server-authoritative with interpolation. Client sends input intents and interpolates. Server owns movement, bounds, room membership, and canonical snapshots. |
| Tick Rate |
10 ticks/sec (100ms) with lightweight periodic room snapshots. |
| Physics |
Low to medium intensity; server-authoritative kinematic movement, escalating to a physics engine only when collisions get complex. |
Actors
Lifecycle
sequenceDiagram
participant C as Client
participant MM as matchmaker
participant M as match
C->>MM: findLobby()
alt no open lobby
MM->>M: create(matchId)
end
MM-->>C: {matchId, playerId}
C->>M: connect(playerId)
M->>MM: pendingPlayerConnected(matchId, playerId)
MM-->>M: accepted
Note over M: fixed tick simulation
M-->>C: snapshot events
M->>MM: closeMatch(matchId)
Open World
| Topic |
Summary |
| Matchmaking |
Client-driven chunk routing from world coordinates, with nearby chunk windows preloaded via adjacent chunk connections. |
| Netcode |
Hybrid for sandbox (client movement with validation) or server-authoritative for MMO-like flows. Server owns chunk routing, persistence, and canonical world state. |
| Tick Rate |
10 ticks/sec per chunk actor (100ms), so load scales with active chunks. |
| Physics |
Medium to high at scale; chunk-local simulation can be server-authoritative (MMO-like) or client movement with server validation (sandbox-like). |
Actors
- Key:
chunk[worldId,chunkX,chunkY]
- Responsibility: Owns chunk-local players, blocks, movement tick, and chunk membership.
- Actions
connect
enterChunk
addPlayer
setInput
leaveChunk
removePlayer
- Queues
- State
- JSON
connections
players
blocks scoped to one chunk key
Lifecycle
sequenceDiagram
participant C as Client
participant CH as chunk
Note over C: resolve chunk keys from world position
loop each visible chunk
C->>CH: connect(worldId, chunkX, chunkY, playerId)
Note over CH: store connection metadata
end
C->>CH: enterChunk/addPlayer
loop movement updates
C->>CH: setInput(...)
CH-->>C: snapshot
end
C->>CH: leaveChunk/removePlayer or disconnect
Note over CH: remove membership and metadata
Party
| Topic |
Summary |
| Matchmaking |
Host-created private party flow using party codes and explicit joins. |
| Netcode |
Server-authoritative (basic logic). Server owns membership, host permissions, and phase transitions. |
| Tick Rate |
No continuous tick; updates are event-driven (join, start, finish). |
| Physics |
Low intensity for lobby-first flows; usually no dedicated physics or indexing unless you add realtime mini-games. |
Actors
Key: matchmaker["main"]
Responsibility: Handles party create/join flow, validates join tickets, and tracks party size.
Actions
createParty
joinParty
verifyJoin
updatePartySize
closeParty
Queues
createParty
joinParty
verifyJoin
updatePartySize
closeParty
State
- SQLite
parties
join_tickets for party lookup and join validation
Key: match[matchId]
Responsibility: Owns party members, host role, ready flags, and phase transitions.
Actions
connect
startGame
finishGame
Queues
State
- JSON
members
host
ready state
phase
party events
Lifecycle
Host Flow
sequenceDiagram
participant H as Host Client
participant MM as matchmaker
participant M as match
H->>MM: createParty()
MM-->>H: {matchId, partyCode, playerId, joinToken}
H->>M: connect(playerId, joinToken)
M->>MM: verifyJoin(...)
MM-->>M: allowed
M->>MM: updatePartySize(playerCount)
H->>M: startGame() / finishGame()
M->>MM: closeParty(matchId)
Joiner Flow
sequenceDiagram
participant J as Joiner Client
participant MM as matchmaker
participant M as match
J->>MM: joinParty(partyCode)
MM-->>J: {matchId, playerId, joinToken}
J->>M: connect(playerId, joinToken)
M->>MM: verifyJoin(...)
MM-->>M: allowed / denied
M->>MM: updatePartySize(playerCount)
Ranked
| Topic |
Summary |
| Matchmaking |
ELO-based queue pairing with a widening search window as wait time increases. |
| Netcode |
Hybrid. Client owns movement with local prediction and interpolation. Server owns projectiles, hit resolution, match results, and rating updates. |
| Tick Rate |
20 ticks/sec (50ms) with fixed live ticks for deterministic pacing and broadcast cadence. |
| Physics |
Medium to high intensity; client movement with server validation and server-authoritative combat/hit resolution. |
Actors
Key: matchmaker["main"]
Responsibility: Runs rating-based queueing, pairing, assignment persistence, and completion fanout.
Actions
queueForMatch
unqueueForMatch
matchCompleted
Queues
queueForMatch
unqueueForMatch
matchCompleted
State
- SQLite
player_pool
matches
assignments with rating window and connection scoping
Key: match[matchId]
Responsibility: Runs ranked match phase, score, and winner reporting.
Actions
Queues
State
- JSON
phase
players
score
winner
completion payload
Key: player[username]
Responsibility: Stores canonical player MMR and win/loss profile.
Actions
initialize
getRating
applyMatchResult
Queues
State
- JSON
rating
wins
losses
match counters
Key: leaderboard["main"]
Responsibility: Stores and serves top-ranked players.
Actions
Queues
State
- SQLite
- Leaderboard score rows
- Top-list ordering
Lifecycle
sequenceDiagram
participant C as Client
participant MM as matchmaker
participant P as player
participant M as match
participant LB as leaderboard
C->>MM: queueForMatch(username)
MM->>P: initialize/getRating
P-->>MM: rating
Note over MM: store queue row + retry pairing
MM->>M: create(matchId, assigned players)
MM-->>C: assignmentReady
C->>M: connect(username)
M->>MM: matchCompleted(...)
MM->>P: applyMatchResult(...)
MM->>LB: updatePlayer(...)
Note over MM: remove matches + assignments rows
Turn-Based
| Topic |
Summary |
| Matchmaking |
Async private-invite and public-queue pairing in the same pattern. |
| Netcode |
Server-authoritative (basic logic). Client can draft moves before submit. Server owns turn ownership, committed move log, turn order, and completion state. |
| Tick Rate |
No continuous tick; move submission and turn transitions drive updates. |
| Physics |
Very low intensity; no realtime physics loop, just discrete rules validation. Indexing is optional and mostly for board or query convenience at scale. |
Actors
Key: matchmaker["main"]
Responsibility: Handles private invite and public queue pairing for async matches.
Actions
createGame
joinByCode
queueForMatch
unqueueForMatch
closeMatch
Queues
createGame
joinByCode
queueForMatch
unqueueForMatch
closeMatch
State
- SQLite
matches
player_pool
assignments for invite and queue mapping
Key: match[matchId]
Responsibility: Owns board state, turn order, move validation, and final result.
Actions
Queues
State
- JSON
board
turns
players
connection presence
result
Lifecycle
Public Queue
sequenceDiagram
participant A as Client A
participant B as Client B
participant MM as matchmaker
participant M as match
A->>MM: queueForMatch()
B->>MM: queueForMatch()
Note over MM: pair first two queued players
MM->>M: create(matchId) + seed X/O players
MM-->>A: assignment/match info
MM-->>B: assignment/match info
A->>M: connect(playerId)
B->>M: connect(playerId)
A->>M: makeMove()
B->>M: makeMove()
opt all players disconnected for timeout
Note over M: destroy after idle timeout
end
M->>MM: closeMatch(matchId)
Private Invite
sequenceDiagram
participant A as Client A
participant B as Client B
participant MM as matchmaker
participant M as match
A->>MM: createGame()
MM-->>A: {matchId, playerId, inviteCode}
B->>MM: joinByCode(inviteCode)
MM->>M: create(matchId) + seed X/O players
MM-->>A: assignment/match info
MM-->>B: assignment/match info
A->>M: connect(playerId)
B->>M: connect(playerId)
A->>M: makeMove()
B->>M: makeMove()
M->>MM: closeMatch(matchId)
Idle
| Topic |
Summary |
| Matchmaking |
No matchmaker; each player uses a direct per-player actor and a shared leaderboard actor. |
| Netcode |
Server-authoritative (basic logic). Client owns UI and build intent. Server owns resources, production rates, building validation, and leaderboard totals. |
| Tick Rate |
No continuous tick; use c.schedule.after(...) for coarse intervals and compute offline catch-up from elapsed wall time. |
| Physics |
None for standard idle loops; transitions are discrete (build, collect, upgrade) and do not need spatial indexing. |
Actors
Key: world[playerId]
Responsibility: Owns one player's progression, buildings, production scheduling, and state updates.
Actions
initialize
build
collectProduction
Queues
State
- JSON
- Per-player buildings
resources
timers
progression state
Key: leaderboard["main"]
Responsibility: Stores global scores and serves leaderboard updates.
Actions
Queues
State
- SQLite
scores table keyed by player
- Current leaderboard totals
Lifecycle
sequenceDiagram
participant C as Client
participant W as world
participant LB as leaderboard
C->>W: getOrCreate(playerId) + initialize()
Note over W: seed state + schedule collection
W-->>C: stateUpdate
loop gameplay loop
C->>W: build() / collectProduction()
W->>LB: updateScore(...)
Note over LB: upsert scores
LB-->>C: leaderboardUpdate
W-->>C: stateUpdate
end
Reference Map
Actors
- Access Control
- Actions
- Actor Keys
- Actor Scheduling
- Actor Statuses
- Authentication
- Cloudflare Workers Quickstart
- Communicating Between Actors
- Connections
- Custom Inspector Tabs
- Debugging
- Design Patterns
- Destroying Actors
- Effect.ts Quickstart (Beta)
- Errors
- Fetch and WebSocket Handler
- Helper Types
- Icons & Names
- In-Memory State
- Input Parameters
- Lifecycle
- Limits
- Low-Level HTTP Request Handler
- Low-Level KV Storage
- Low-Level WebSocket Handler
- Metadata
- Next.js Quickstart
- Node.js & Bun Quickstart
- Queues & Run Loops
- React Quickstart
- Realtime
- Rust Quickstart (Beta)
- Scaling & Concurrency
- Sharing and Joining State
- SQLite
- SQLite + Drizzle
- Supabase Functions Quickstart
- Testing
- Troubleshooting
- Types
- Vanilla HTTP API
- Versions & Upgrades
- Workflows
Cli
Clients
- Node.js & Bun
- React
- Rust (Beta)
- Swift
- SwiftUI
Cookbook
- AI Agent
- Chat Room
- Collaborative Text Editor
- Cron Jobs and Scheduled Tasks
- Database per Tenant
- Deploying Rivet in a VPC or Air-Gapped Network
- Live Cursors and Presence
- Multiplayer Game
Deploy
- Container Runner
- Deploy To Amazon Web Services Lambda
- Deploying to AWS ECS
- Deploying to Cloudflare Workers
- Deploying to Freestyle
- Deploying to Google Cloud Run
- Deploying to Hetzner
- Deploying to Kubernetes
- Deploying to Railway
- Deploying to Rivet Compute
- Deploying to Supabase Functions
- Deploying to Vercel
- Deploying to VMs & Bare Metal
General
- Actor Configuration
- Architecture
- Cross-Origin Resource Sharing
- Documentation for LLMs & AI
- Edge Networking
- Endpoints
- Environment Variables
- HTTP Server
- Logging
- Pool Configuration
- Production Checklist
- Registry Configuration
- Runtime Modes
- WASM vs Native SDK
Self Hosting
- Configuration
- Docker Compose
- Docker Container
- File System
- FoundationDB (Enterprise)
- Installing Rivet Engine
- Kubernetes
- Multi-Region
- PostgreSQL
- Production Checklist
- Railway Deployment
- Render Deployment
- TLS & Certificates
1---
2name: "multiplayer-game"
3description: "Pragmatic patterns for building multiplayer games: matchmaking, tick loops, realtime state, interest management, and validation."
4metadata:
5 source: https://skillmd.com/skills/om-scogo/multiplayer-game
6---
7
8# Multiplayer Game
9
10**IMPORTANT: Before doing anything, you MUST read `BASE_SKILL.md` in this skill's directory. It contains essential guidance on debugging, error handling, state management, deployment, and project setup. Those rules and patterns apply to all RivetKit work. Everything below assumes you have already read and understood it.**
11
12## Working Examples
13
14If you need a reference implementation, read the raw working example code in these templates:
15
16- [multiplayer-game-patterns](https://github.com/rivet-dev/rivet/tree/main/examples/multiplayer-game-patterns)
17
18
19Patterns for building multiplayer games with RivetKit, intended as a practical checklist you can adapt per genre.
20
21## Starter Code
22
23Start with one of the working examples on [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/multiplayer-game-patterns/src/actors/) and adapt it to your game. Do not start from scratch for matchmaking and lifecycle flows.
24
25| Game Classification | Starter Code | Common Examples |
26| --- | --- | --- |
27| Battle Royale | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/multiplayer-game-patterns/src/actors/battle-royale/) | Fortnite, Apex Legends, PUBG, Warzone |
28| Arena | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/multiplayer-game-patterns/src/actors/arena/) | Call of Duty TDM/FFA, Halo Slayer, Counter-Strike casual, VALORANT unrated, Overwatch Quick Play, Rocket League |
29| IO Style | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/multiplayer-game-patterns/src/actors/io-style/) | Agar.io, Slither.io, surviv.io |
30| Open World | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/multiplayer-game-patterns/src/actors/open-world/) | Minecraft survival servers, Rust-like worlds, MMO zone/chunk worlds |
31| Party | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/multiplayer-game-patterns/src/actors/party/) | Fall Guys private lobbies, custom game rooms, social party sessions |
32| Physics 2D | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/multiplayer-game-patterns/src/actors/physics-2d/) | Top-down physics brawlers, 2D arena games, platform fighters |
33| Physics 3D | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/multiplayer-game-patterns/src/actors/physics-3d/) | Physics sandbox sessions, 3D arena games, movement playgrounds |
34| Ranked | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/multiplayer-game-patterns/src/actors/ranked/) | Chess ladders, competitive card games, duel arena ranked queues |
35| Turn-Based | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/multiplayer-game-patterns/src/actors/turn-based/) | Chess correspondence, Words With Friends, async board games |
36| Idle | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/multiplayer-game-patterns/src/actors/idle/) | Cookie Clicker, Idle Miner Tycoon, Adventure Capitalist |
37
38## Server Simulation
39
40### Game Loop And Tick Rates
41
42| Pattern | Use When | Implementation Guidance |
43| --- | --- | --- |
44| Fixed realtime loop | Battle Royale, Arena, IO Style, Open World, Ranked | Run in `run` with `sleep(tickMs)` and exit on `c.aborted`. |
45| Action-driven updates | Party, Turn-Based | Mutate and broadcast only on actions/events rather than scheduled ticks. |
46| Coarse offline progression | Any mode with idle progression | Use `c.schedule.after(...)` with coarse windows (for example 5 to 15 minutes) and apply catch-up from elapsed wall clock time. |
47
48### Physics
49
50Start with custom kinematic logic for simple games. Switch to a full physics engine when you need joints, stacked bodies, high collision density, or complex shapes (rotated polygons, capsules, convex hulls, triangle meshes).
51
52Pick one engine per simulation. Keep frontend-only libs out of backend simulation paths and treat server state as authoritative.
53
54| Dimension | Primary Engine | Fallback Engines | Example Code |
55| --- | --- | --- | --- |
56| 2D | `@dimforge/rapier2d` | `planck-js`, `matter-js` | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/multiplayer-game-patterns/src/actors/physics-2d/) |
57| 3D | `@dimforge/rapier3d` | `cannon-es`, `ammo.js` | [GitHub](https://github.com/rivet-dev/rivet/tree/main/examples/multiplayer-game-patterns/src/actors/physics-3d/) |
58
59### Spatial Indexing
60
61For non-physics spatial queries, use a dedicated index instead of naive `O(n^2)` checks:
62
63| Index Type | Recommendation |
64| --- | --- |
65| AABB index | For AOI, visibility, and non-collider entities, use `rbush` for dynamic sets or `flatbush` for static-ish sets. |
66| Point index | For nearest-neighbor or within-radius queries, use `d3-quadtree`. |
67
68## Networking & State Sync
69
70### Netcode
71
72| Model | When To Use | Implementation |
73| --- | --- | --- |
74| Hybrid (client movement, server combat) | Shooters, action sports, ranked duels | Client owns movement and sends capped-rate position updates. Server validates for anti-cheat. Combat (projectiles, hits, damage) is fully server-authoritative. |
75| Server-authoritative with interpolation | IO Style, persistent worlds | Client sends input commands. Server simulates on fixed ticks and publishes authoritative snapshots. Client interpolates between snapshots. |
76| Server-authoritative (basic logic) | Turn-based, event-driven | Server validates and applies discrete actions (turns, phase transitions, votes). Client displays confirmed state. |
77
78### Realtime Data Model
79
80- **Snapshots and diffs**: Publish state as events. Send a full snapshot on join/resync, then per-tick diffs for regular updates.
81- **Batch per tick**: Keep events small and typed. Batch high-frequency updates per tick.
82- **Avoid UI framework state for game updates**: Use `requestAnimationFrame` or a Canvas/Three.js loop for simulation, not React state. Reserve UI framework state for menus, HUD, and forms.
83- **Broadcast vs per-connection**: Use `c.broadcast(...)` for shared updates and `conn.send(...)` for private/per-player data.
84
85### Shared Simulation Logic
86
87Shared simulation logic runs on both the client and the server. For example, an `applyInput(state, input, dt)` function that integrates velocity and clamps to world bounds can run on the client for prediction and on the server for validation.
88
89- **Hybrid modes**: Client runs shared movement as primary authority, server runs it for anti-cheat validation.
90- **Server-authoritative modes**: Client uses shared logic for interpolation and prediction only.
91- **Keep it pure**: Movement integration, input transforms, collision helpers, and constants only.
92- **Put shared code in `src/shared/`**: Keep deterministic helpers in `src/shared/sim/*` with no side effects.
93
94### Interest Management
95
96Control what each client receives to reduce bandwidth and prevent information leaks.
97
98#### Per-Player Replication Filters
99
100- **Filter by relevance**: Send each client only state relevant to that player (proximity, line-of-sight, team, or game phase).
101- **Shooters and action games**: Limit replication by proximity and optional field-of-view checks.
102- **Server-side only**: Clients should never receive data they should not see.
103
104#### Sharded Worlds
105
106- **Partition large worlds**: Use chunk actors keyed by `worldId:chunkX:chunkY`.
107- **Subscribe to nearby chunks**: Clients connect only to nearby partitions (for example a 3x3 chunk window).
108- **Use sparingly**: Only when the world is large and state-heavy (sandbox builders, MMOs), not as a default for small matches.
109
110## Backend Infrastructure
111
112### Persistence
113
114- **In-memory state**: Best for realtime game state that changes every tick (player positions, inputs, match phase, scores).
115- **SQLite (`rivetkit/db`)**: Better for large or table-like state that needs queries, indexes, or long-term persistence (tiles, inventory, matchmaking pools). Serialize DB work through a queue since multiple actions can hit the same actor concurrently.
116
117### Matchmaking Patterns
118
119Common building blocks used across the architecture patterns below.
120
121#### Actor Topology
122
123| Primitive | Use When | Typical Ownership |
124| --- | --- | --- |
125| `matchmaker["main"]` + `match[matchId]` | Session-based multiplayer (battle royale, arena, ranked, party, turn-based) | Matchmaker owns discovery/assignment. Match owns lifecycle and gameplay state. |
126| `chunk[worldId,chunkX,chunkY]` | Large continuous worlds that need sharding | Each chunk owns local players, chunk state, and local simulation. |
127| `world[playerId]` | Per-player progression loops (idle/solo world state) | Per-player resources, buildings, timers, and progression. |
128| `player[username]` | Canonical profile/rating reused across matches | Durable player stats (for example rating and win/loss). |
129| `leaderboard["main"]` | Shared rankings across many matches/players | Global ordered score rows and top lists. |
130
131#### Queueing Strategy
132
133- Multiple players can hit the matchmaker at the same time, so actions like find/create, queue/unqueue, and close need to be serialized through actor queues to avoid races.
134- Match-local actions (gameplay, scoring) do not need queueing unless they write back to the matchmaker.
135
136## Security And Anti-Cheat
137
138Start with this baseline, then harden further for competitive or high-risk environments.
139
140### Baseline Checklist
141
142- **Identity**: Use `c.conn.id` as the authoritative transport identity. Treat `playerId`/`username` in params as untrusted input and bind through server-issued assignment/join tickets.
143- **Authorization**: Validate the caller is allowed to mutate the target entity (room membership, turn ownership, host-only actions).
144- **Input validation**: Clamp sizes/lengths, validate enums, and validate usernames (length, allowed chars, avoid unbounded Unicode).
145- **Rate limiting**: Per-connection rate limits for spammy actions (chat, join/leave, fire, movement updates).
146- **State integrity**: Server recomputes derived state (scores, win conditions, placements). Never allow client-authoritative changes to inventory/currency/leaderboard totals.
147
148### Movement Validation
149
150For any mode with client-authoritative movement (hybrid flows), clients may send position/rotation updates for smoothness, but the server must:
151
152- Enforce max delta per update (speed cap) based on elapsed time.
153- Reject or clamp teleports.
154- Enforce world bounds (and basic collision if applicable).
155- Rate limit update frequency (for example 20Hz max).
156
157## Architecture Patterns
158
159Each game type below starts with a quick summary table, then details actors and lifecycle.
160
161### Battle Royale
162
163| Topic | Summary |
164| --- | --- |
165| Matchmaking | Immediate routing to the fullest non-started lobby (oldest tie-break); players wait in lobby until capacity, then the match starts. |
166| Netcode | Hybrid. Client owns movement, camera, and local prediction. Server owns zone state, projectiles, hit resolution, eliminations, loot, and final placement. |
167| Tick Rate | 10 ticks/sec (`100ms`) with a fixed loop for zone progression and lifecycle checks. |
168| Physics | Client owns movement with server anti-cheat validation; projectiles, hits, and damage are server-authoritative. Use `@dimforge/rapier3d` for 3D or `@dimforge/rapier2d` for top-down 2D. |
169
170**Actors**
171
172- **Key**: `matchmaker["main"]`
173- **Responsibility**: Finds or creates lobbies, tracks pending reservations, and maintains occupancy.
174- **Actions**
175 - `findMatch`
176 - `pendingPlayerConnected`
177 - `updateMatch`
178 - `closeMatch`
179- **Queues**
180 - `findMatch`
181 - `pendingPlayerConnected`
182 - `updateMatch`
183 - `closeMatch`
184- **State**
185 - SQLite
186 - `matches`
187 - `pending_players`
188 - `player_count` includes connected and pending players
189
190- **Key**: `match[matchId]`
191- **Responsibility**: Runs lobby/live/finished phases, owns player state, zone progression, and eliminations.
192- **Actions**
193 - `connect`
194 - Movement and combat actions
195- **Queues**
196 - None
197- **State**
198 - JSON
199 - `phase`
200 - `players`
201 - `zone`
202 - `eliminations`
203 - `snapshot data`
204
205**Lifecycle**
206
207```mermaid
208sequenceDiagram
209 participant C as Client
210 participant MM as matchmaker
211 participant M as match
212
213 C->>MM: findMatch()
214 alt no open lobby
215 MM->>M: create(matchId)
216 end
217 MM-->>C: {matchId, playerId}
218 C->>M: connect(playerId)
219 M->>MM: pendingPlayerConnected(matchId, playerId)
220 MM-->>M: accepted
221 Note over M: lobby countdown -> live
222 M-->>C: snapshot + shoot events
223 M->>MM: closeMatch(matchId)
224```
225
226### Arena
227
228| Topic | Summary |
229| --- | --- |
230| Matchmaking | Mode-based fixed-capacity queues (`duo`, `squad`, `ffa`) that build only full matches and pre-assign teams (except FFA). |
231| Netcode | Hybrid. Client owns movement plus prediction and smoothing. Server owns team or FFA assignment, projectiles, hit resolution, phase transitions, and scoring. |
232| Tick Rate | 20 ticks/sec (`50ms`) with a tighter loop for live team and FFA snapshots. |
233| Physics | Medium to high intensity; client movement with server validation and server-authoritative combat/entities. |
234
235**Actors**
236
237- **Key**: `matchmaker["main"]`
238- **Responsibility**: Runs mode queues, builds full matches, assigns teams, and publishes assignments.
239- **Actions**
240 - `queueForMatch`
241 - `unqueueForMatch`
242 - `matchCompleted`
243- **Queues**
244 - `queueForMatch`
245 - `unqueueForMatch`
246 - `matchCompleted`
247- **State**
248 - SQLite
249 - `player_pool`
250 - `matches`
251 - `assignments` keyed by connection and player
252
253- **Key**: `match[matchId]`
254- **Responsibility**: Runs match phases and in-match player/team state for score and win conditions.
255- **Actions**
256 - `connect`
257 - Gameplay actions
258- **Queues**
259 - None
260- **State**
261 - JSON
262 - `phase`
263 - `players`
264 - `team assignments`
265 - `score and win state`
266
267**Lifecycle**
268
269```mermaid
270sequenceDiagram
271 participant C as Client
272 participant MM as matchmaker
273 participant M as match
274
275 C->>MM: queueForMatch(mode)
276 Note over MM: enqueue in player_pool
277 Note over MM: fill when capacity reached
278 MM->>M: create(matchId, assignments)
279 Note over MM: persist assignments
280 MM-->>C: assignmentReady
281 C->>M: connect(playerId)
282 Note over M: waiting -> live when all players connect
283 M->>MM: matchCompleted(matchId)
284```
285
286### IO Style
287
288| Topic | Summary |
289| --- | --- |
290| Matchmaking | Open-lobby routing to the fullest room below capacity; room counts are heartbeated and new lobbies are auto-created when needed. |
291| Netcode | Server-authoritative with interpolation. Client sends input intents and interpolates. Server owns movement, bounds, room membership, and canonical snapshots. |
292| Tick Rate | 10 ticks/sec (`100ms`) with lightweight periodic room snapshots. |
293| Physics | Low to medium intensity; server-authoritative kinematic movement, escalating to a physics engine only when collisions get complex. |
294
295**Actors**
296
297- **Key**: `matchmaker["main"]`
298- **Responsibility**: Routes players into the fullest open lobby and tracks reservations and occupancy.
299- **Actions**
300 - `findLobby`
301 - `pendingPlayerConnected`
302 - `updateMatch`
303 - `closeMatch`
304- **Queues**
305 - `findLobby`
306 - `pendingPlayerConnected`
307 - `updateMatch`
308 - `closeMatch`
309- **State**
310 - SQLite
311 - `matches`
312 - `pending_players`
313 - Occupancy includes pending reservations
314
315- **Key**: `match[matchId]`
316- **Responsibility**: Runs per-match movement simulation and broadcasts snapshots.
317- **Actions**
318 - `connect`
319 - `setInput`
320- **Queues**
321 - None
322- **State**
323 - JSON
324 - `players`
325 - `inputs`
326 - `movement state`
327 - `snapshot cache`
328
329**Lifecycle**
330
331```mermaid
332sequenceDiagram
333 participant C as Client
334 participant MM as matchmaker
335 participant M as match
336
337 C->>MM: findLobby()
338 alt no open lobby
339 MM->>M: create(matchId)
340 end
341 MM-->>C: {matchId, playerId}
342 C->>M: connect(playerId)
343 M->>MM: pendingPlayerConnected(matchId, playerId)
344 MM-->>M: accepted
345 Note over M: fixed tick simulation
346 M-->>C: snapshot events
347 M->>MM: closeMatch(matchId)
348```
349
350### Open World
351
352| Topic | Summary |
353| --- | --- |
354| Matchmaking | Client-driven chunk routing from world coordinates, with nearby chunk windows preloaded via adjacent chunk connections. |
355| Netcode | Hybrid for sandbox (client movement with validation) or server-authoritative for MMO-like flows. Server owns chunk routing, persistence, and canonical world state. |
356| Tick Rate | 10 ticks/sec per chunk actor (`100ms`), so load scales with active chunks. |
357| Physics | Medium to high at scale; chunk-local simulation can be server-authoritative (MMO-like) or client movement with server validation (sandbox-like). |
358
359**Actors**
360
361- **Key**: `chunk[worldId,chunkX,chunkY]`
362- **Responsibility**: Owns chunk-local players, blocks, movement tick, and chunk membership.
363- **Actions**
364 - `connect`
365 - `enterChunk`
366 - `addPlayer`
367 - `setInput`
368 - `leaveChunk`
369 - `removePlayer`
370- **Queues**
371 - None
372- **State**
373 - JSON
374 - `connections`
375 - `players`
376 - `blocks` scoped to one chunk key
377
378**Lifecycle**
379
380```mermaid
381sequenceDiagram
382 participant C as Client
383 participant CH as chunk
384
385 Note over C: resolve chunk keys from world position
386 loop each visible chunk
387 C->>CH: connect(worldId, chunkX, chunkY, playerId)
388 Note over CH: store connection metadata
389 end
390 C->>CH: enterChunk/addPlayer
391 loop movement updates
392 C->>CH: setInput(...)
393 CH-->>C: snapshot
394 end
395 C->>CH: leaveChunk/removePlayer or disconnect
396 Note over CH: remove membership and metadata
397```
398
399### Party
400
401| Topic | Summary |
402| --- | --- |
403| Matchmaking | Host-created private party flow using party codes and explicit joins. |
404| Netcode | Server-authoritative (basic logic). Server owns membership, host permissions, and phase transitions. |
405| Tick Rate | No continuous tick; updates are event-driven (`join`, `start`, `finish`). |
406| Physics | Low intensity for lobby-first flows; usually no dedicated physics or indexing unless you add realtime mini-games. |
407
408**Actors**
409
410- **Key**: `matchmaker["main"]`
411- **Responsibility**: Handles party create/join flow, validates join tickets, and tracks party size.
412- **Actions**
413 - `createParty`
414 - `joinParty`
415 - `verifyJoin`
416 - `updatePartySize`
417 - `closeParty`
418- **Queues**
419 - `createParty`
420 - `joinParty`
421 - `verifyJoin`
422 - `updatePartySize`
423 - `closeParty`
424- **State**
425 - SQLite
426 - `parties`
427 - `join_tickets` for party lookup and join validation
428
429- **Key**: `match[matchId]`
430- **Responsibility**: Owns party members, host role, ready flags, and phase transitions.
431- **Actions**
432 - `connect`
433 - `startGame`
434 - `finishGame`
435- **Queues**
436 - None
437- **State**
438 - JSON
439 - `members`
440 - `host`
441 - `ready state`
442 - `phase`
443 - `party events`
444
445**Lifecycle**
446
447### Host Flow
448
449```mermaid
450sequenceDiagram
451 participant H as Host Client
452 participant MM as matchmaker
453 participant M as match
454
455 H->>MM: createParty()
456 MM-->>H: {matchId, partyCode, playerId, joinToken}
457 H->>M: connect(playerId, joinToken)
458 M->>MM: verifyJoin(...)
459 MM-->>M: allowed
460 M->>MM: updatePartySize(playerCount)
461 H->>M: startGame() / finishGame()
462 M->>MM: closeParty(matchId)
463```
464
465### Joiner Flow
466
467```mermaid
468sequenceDiagram
469 participant J as Joiner Client
470 participant MM as matchmaker
471 participant M as match
472
473 J->>MM: joinParty(partyCode)
474 MM-->>J: {matchId, playerId, joinToken}
475 J->>M: connect(playerId, joinToken)
476 M->>MM: verifyJoin(...)
477 MM-->>M: allowed / denied
478 M->>MM: updatePartySize(playerCount)
479```
480
481### Ranked
482
483| Topic | Summary |
484| --- | --- |
485| Matchmaking | ELO-based queue pairing with a widening search window as wait time increases. |
486| Netcode | Hybrid. Client owns movement with local prediction and interpolation. Server owns projectiles, hit resolution, match results, and rating updates. |
487| Tick Rate | 20 ticks/sec (`50ms`) with fixed live ticks for deterministic pacing and broadcast cadence. |
488| Physics | Medium to high intensity; client movement with server validation and server-authoritative combat/hit resolution. |
489
490**Actors**
491
492- **Key**: `matchmaker["main"]`
493- **Responsibility**: Runs rating-based queueing, pairing, assignment persistence, and completion fanout.
494- **Actions**
495 - `queueForMatch`
496 - `unqueueForMatch`
497 - `matchCompleted`
498- **Queues**
499 - `queueForMatch`
500 - `unqueueForMatch`
501 - `matchCompleted`
502- **State**
503 - SQLite
504 - `player_pool`
505 - `matches`
506 - `assignments` with rating window and connection scoping
507
508- **Key**: `match[matchId]`
509- **Responsibility**: Runs ranked match phase, score, and winner reporting.
510- **Actions**
511 - `connect`
512 - Gameplay actions
513- **Queues**
514 - None
515- **State**
516 - JSON
517 - `phase`
518 - `players`
519 - `score`
520 - `winner`
521 - `completion payload`
522
523- **Key**: `player[username]`
524- **Responsibility**: Stores canonical player MMR and win/loss profile.
525- **Actions**
526 - `initialize`
527 - `getRating`
528 - `applyMatchResult`
529- **Queues**
530 - None
531- **State**
532 - JSON
533 - `rating`
534 - `wins`
535 - `losses`
536 - `match counters`
537
538- **Key**: `leaderboard["main"]`
539- **Responsibility**: Stores and serves top-ranked players.
540- **Actions**
541 - `updatePlayer`
542- **Queues**
543 - None
544- **State**
545 - SQLite
546 - Leaderboard score rows
547 - Top-list ordering
548
549**Lifecycle**
550
551```mermaid
552sequenceDiagram
553 participant C as Client
554 participant MM as matchmaker
555 participant P as player
556 participant M as match
557 participant LB as leaderboard
558
559 C->>MM: queueForMatch(username)
560 MM->>P: initialize/getRating
561 P-->>MM: rating
562 Note over MM: store queue row + retry pairing
563 MM->>M: create(matchId, assigned players)
564 MM-->>C: assignmentReady
565 C->>M: connect(username)
566 M->>MM: matchCompleted(...)
567 MM->>P: applyMatchResult(...)
568 MM->>LB: updatePlayer(...)
569 Note over MM: remove matches + assignments rows
570```
571
572### Turn-Based
573
574| Topic | Summary |
575| --- | --- |
576| Matchmaking | Async private-invite and public-queue pairing in the same pattern. |
577| Netcode | Server-authoritative (basic logic). Client can draft moves before submit. Server owns turn ownership, committed move log, turn order, and completion state. |
578| Tick Rate | No continuous tick; move submission and turn transitions drive updates. |
579| Physics | Very low intensity; no realtime physics loop, just discrete rules validation. Indexing is optional and mostly for board or query convenience at scale. |
580
581**Actors**
582
583- **Key**: `matchmaker["main"]`
584- **Responsibility**: Handles private invite and public queue pairing for async matches.
585- **Actions**
586 - `createGame`
587 - `joinByCode`
588 - `queueForMatch`
589 - `unqueueForMatch`
590 - `closeMatch`
591- **Queues**
592 - `createGame`
593 - `joinByCode`
594 - `queueForMatch`
595 - `unqueueForMatch`
596 - `closeMatch`
597- **State**
598 - SQLite
599 - `matches`
600 - `player_pool`
601 - `assignments` for invite and queue mapping
602
603- **Key**: `match[matchId]`
604- **Responsibility**: Owns board state, turn order, move validation, and final result.
605- **Actions**
606 - `connect`
607 - `makeMove`
608- **Queues**
609 - None
610- **State**
611 - JSON
612 - `board`
613 - `turns`
614 - `players`
615 - `connection presence`
616 - `result`
617
618**Lifecycle**
619
620### Public Queue
621
622```mermaid
623sequenceDiagram
624 participant A as Client A
625 participant B as Client B
626 participant MM as matchmaker
627 participant M as match
628
629 A->>MM: queueForMatch()
630 B->>MM: queueForMatch()
631 Note over MM: pair first two queued players
632 MM->>M: create(matchId) + seed X/O players
633 MM-->>A: assignment/match info
634 MM-->>B: assignment/match info
635 A->>M: connect(playerId)
636 B->>M: connect(playerId)
637 A->>M: makeMove()
638 B->>M: makeMove()
639 opt all players disconnected for timeout
640 Note over M: destroy after idle timeout
641 end
642 M->>MM: closeMatch(matchId)
643```
644
645### Private Invite
646
647```mermaid
648sequenceDiagram
649 participant A as Client A
650 participant B as Client B
651 participant MM as matchmaker
652 participant M as match
653
654 A->>MM: createGame()
655 MM-->>A: {matchId, playerId, inviteCode}
656 B->>MM: joinByCode(inviteCode)
657 MM->>M: create(matchId) + seed X/O players
658 MM-->>A: assignment/match info
659 MM-->>B: assignment/match info
660 A->>M: connect(playerId)
661 B->>M: connect(playerId)
662 A->>M: makeMove()
663 B->>M: makeMove()
664 M->>MM: closeMatch(matchId)
665```
666
667### Idle
668
669| Topic | Summary |
670| --- | --- |
671| Matchmaking | No matchmaker; each player uses a direct per-player actor and a shared leaderboard actor. |
672| Netcode | Server-authoritative (basic logic). Client owns UI and build intent. Server owns resources, production rates, building validation, and leaderboard totals. |
673| Tick Rate | No continuous tick; use `c.schedule.after(...)` for coarse intervals and compute offline catch-up from elapsed wall time. |
674| Physics | None for standard idle loops; transitions are discrete (`build`, `collect`, `upgrade`) and do not need spatial indexing. |
675
676**Actors**
677
678- **Key**: `world[playerId]`
679- **Responsibility**: Owns one player's progression, buildings, production scheduling, and state updates.
680- **Actions**
681 - `initialize`
682 - `build`
683 - `collectProduction`
684- **Queues**
685 - None
686- **State**
687 - JSON
688 - Per-player buildings
689 - `resources`
690 - `timers`
691 - `progression state`
692
693- **Key**: `leaderboard["main"]`
694- **Responsibility**: Stores global scores and serves leaderboard updates.
695- **Actions**
696 - `updateScore`
697- **Queues**
698 - `updateScore`
699- **State**
700 - SQLite
701 - `scores` table keyed by player
702 - Current leaderboard totals
703
704**Lifecycle**
705
706```mermaid
707sequenceDiagram
708 participant C as Client
709 participant W as world
710 participant LB as leaderboard
711
712 C->>W: getOrCreate(playerId) + initialize()
713 Note over W: seed state + schedule collection
714 W-->>C: stateUpdate
715 loop gameplay loop
716 C->>W: build() / collectProduction()
717 W->>LB: updateScore(...)
718 Note over LB: upsert scores
719 LB-->>C: leaderboardUpdate
720 W-->>C: stateUpdate
721 end
722```
723
724## Reference Map
725
726### Actors
727
728- [Access Control](reference/actors/access-control.md)
729- [Actions](reference/actors/actions.md)
730- [Actor Keys](reference/actors/keys.md)
731- [Actor Scheduling](reference/actors/schedule.md)
732- [Actor Statuses](reference/actors/statuses.md)
733- [Authentication](reference/actors/authentication.md)
734- [Cloudflare Workers Quickstart](reference/actors/quickstart/cloudflare.md)
735- [Communicating Between Actors](reference/actors/communicating-between-actors.md)
736- [Connections](reference/actors/connections.md)
737- [Custom Inspector Tabs](reference/actors/inspector-tabs.md)
738- [Debugging](reference/actors/debugging.md)
739- [Design Patterns](reference/actors/design-patterns.md)
740- [Destroying Actors](reference/actors/destroy.md)
741- [Effect.ts Quickstart (Beta)](reference/actors/quickstart/effect.md)
742- [Errors](reference/actors/errors.md)
743- [Fetch and WebSocket Handler](reference/actors/fetch-and-websocket-handler.md)
744- [Helper Types](reference/actors/helper-types.md)
745- [Icons & Names](reference/actors/appearance.md)
746- [In-Memory State](reference/actors/state.md)
747- [Input Parameters](reference/actors/input.md)
748- [Lifecycle](reference/actors/lifecycle.md)
749- [Limits](reference/actors/limits.md)
750- [Low-Level HTTP Request Handler](reference/actors/request-handler.md)
751- [Low-Level KV Storage](reference/actors/kv.md)
752- [Low-Level WebSocket Handler](reference/actors/websocket-handler.md)
753- [Metadata](reference/actors/metadata.md)
754- [Next.js Quickstart](reference/actors/quickstart/next-js.md)
755- [Node.js & Bun Quickstart](reference/actors/quickstart/backend.md)
756- [Queues & Run Loops](reference/actors/queues.md)
757- [React Quickstart](reference/actors/quickstart/react.md)
758- [Realtime](reference/actors/events.md)
759- [Rust Quickstart (Beta)](reference/actors/quickstart/rust.md)
760- [Scaling & Concurrency](reference/actors/scaling.md)
761- [Sharing and Joining State](reference/actors/sharing-and-joining-state.md)
762- [SQLite](reference/actors/sqlite.md)
763- [SQLite + Drizzle](reference/actors/sqlite-drizzle.md)
764- [Supabase Functions Quickstart](reference/actors/quickstart/supabase.md)
765- [Testing](reference/actors/testing.md)
766- [Troubleshooting](reference/actors/troubleshooting.md)
767- [Types](reference/actors/types.md)
768- [Vanilla HTTP API](reference/actors/http-api.md)
769- [Versions & Upgrades](reference/actors/versions.md)
770- [Workflows](reference/actors/workflows.md)
771
772### Cli
773
774- [CLI](reference/cli.md)
775
776### Clients
777
778- [Node.js & Bun](reference/clients/javascript.md)
779- [React](reference/clients/react.md)
780- [Rust (Beta)](reference/clients/rust.md)
781- [Swift](reference/clients/swift.md)
782- [SwiftUI](reference/clients/swiftui.md)
783
784### Cookbook
785
786- [AI Agent](reference/cookbook/ai-agent.md)
787- [Chat Room](reference/cookbook/chat-room.md)
788- [Collaborative Text Editor](reference/cookbook/collaborative-text-editor.md)
789- [Cron Jobs and Scheduled Tasks](reference/cookbook/cron-jobs.md)
790- [Database per Tenant](reference/cookbook/per-tenant-database.md)
791- [Deploying Rivet in a VPC or Air-Gapped Network](reference/cookbook/vpc-air-gapped.md)
792- [Live Cursors and Presence](reference/cookbook/live-cursors.md)
793- [Multiplayer Game](reference/cookbook/multiplayer-game.md)
794
795### Deploy
796
797- [Container Runner](reference/deploy/container-runner.md)
798- [Deploy To Amazon Web Services Lambda](reference/deploy/aws-lambda.md)
799- [Deploying to AWS ECS](reference/deploy/aws-ecs.md)
800- [Deploying to Cloudflare Workers](reference/deploy/cloudflare.md)
801- [Deploying to Freestyle](reference/deploy/freestyle.md)
802- [Deploying to Google Cloud Run](reference/deploy/gcp-cloud-run.md)
803- [Deploying to Hetzner](reference/deploy/hetzner.md)
804- [Deploying to Kubernetes](reference/deploy/kubernetes.md)
805- [Deploying to Railway](reference/deploy/railway.md)
806- [Deploying to Rivet Compute](reference/deploy/rivet-compute.md)
807- [Deploying to Supabase Functions](reference/deploy/supabase.md)
808- [Deploying to Vercel](reference/deploy/vercel.md)
809- [Deploying to VMs & Bare Metal](reference/deploy/vm-and-bare-metal.md)
810
811### General
812
813- [Actor Configuration](reference/general/actor-configuration.md)
814- [Architecture](reference/general/architecture.md)
815- [Cross-Origin Resource Sharing](reference/general/cors.md)
816- [Documentation for LLMs & AI](reference/general/docs-for-llms.md)
817- [Edge Networking](reference/general/edge.md)
818- [Endpoints](reference/general/endpoints.md)
819- [Environment Variables](reference/general/environment-variables.md)
820- [HTTP Server](reference/general/http-server.md)
821- [Logging](reference/general/logging.md)
822- [Pool Configuration](reference/general/pool-configuration.md)
823- [Production Checklist](reference/general/production-checklist.md)
824- [Registry Configuration](reference/general/registry-configuration.md)
825- [Runtime Modes](reference/general/runtime-modes.md)
826- [WASM vs Native SDK](reference/general/wasm-vs-native-sdk.md)
827
828### Self Hosting
829
830- [Configuration](reference/self-hosting/configuration.md)
831- [Docker Compose](reference/self-hosting/docker-compose.md)
832- [Docker Container](reference/self-hosting/docker-container.md)
833- [File System](reference/self-hosting/filesystem.md)
834- [FoundationDB (Enterprise)](reference/self-hosting/foundationdb.md)
835- [Installing Rivet Engine](reference/self-hosting/install.md)
836- [Kubernetes](reference/self-hosting/kubernetes.md)
837- [Multi-Region](reference/self-hosting/multi-region.md)
838- [PostgreSQL](reference/self-hosting/postgres.md)
839- [Production Checklist](reference/self-hosting/production-checklist.md)
840- [Railway Deployment](reference/self-hosting/railway.md)
841- [Render Deployment](reference/self-hosting/render.md)
842- [TLS & Certificates](reference/self-hosting/tls.md)
843