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