Design a Real-Time Multiplayer Matchmaking Service
System DesignModel answerLast updated
Design a scalable, low-latency matchmaking architecture capable of handling millions of players across diverse modes while keeping matches balanced, fast, and crash-resilient.
Design a real-time game matchmaking service for a large-scale online multiplayer platform.
Requirements & Scope
-
Functional:
- Queue Management: Solo players or pre-made parties can join, leave, or ping heartbeats in a queue for specific game modes and experiences.
- Match Generation: Form balanced matches based on player skill (e.g., ELO / TrueSkill), ping to target regions, party size, and queue wait times.
- Backfilling: Game instances with empty seats (e.g., due to player disconnections) can request backfill matches mid-game.
- Long-tail vs. Popular Titles: Support both mega-popular titles (hundreds of thousands of concurrent queueing players) and a long tail of niche game modes with tiny player pools.
-
Non-Functional Targets:
- Latency: API response times (Join/Leave/Heartbeat) $p99 < 50\text{ ms}$. Match waiting time targets $p50 < 5\text{ s}$, $p95 < 30\text{ s}$, with hard timeouts around $120\text{ s}$.
- Network Quality: Match players to region servers where average round-trip time (RTT) is $< 80\text{ ms}$ (hard ceiling $< 150\text{ ms}$).
- Correctness: Under no circumstances should a player be assigned to two active matches simultaneously.
- Availability: $99.95%$ uptime for API ingestion.
In your design, cover:
- High-level architecture and system components.
- Data models, APIs, and state machine transitions for tickets.
- Capacity planning (throughput, network, memory).
- Detailed algorithm for match formation and relaxation windows.
- Partitioning, sharding, consistency guarantees, and failure handling.
Hints
Hint 1
Think about who owns the state: handling concurrent state mutations across distributed matchers is tricky. Can single-writer sharding simplify concurrency control?
Hint 2
Consider how skill bounds should behave over time. A static skill filter causes starvation for extreme high-skill or low-skill players.
Hint 3
Calculate memory footprint versus CPU bound work: matchmaking for 10 million online users is surprisingly CPU/IO bound rather than RAM bound.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Requirement Clarifications & Traffic Estimation
Non-Functional Targets & Trade-Offs
- Time-to-Match: $p50 < 5\text{s}$, $p95 < 30\text{s}$, max $120\text{s}$. If no valid match forms within $120\text{s}$, the system falls back to bot filling or suggests alternative regions/modes.
- Network Latency: Target RTT $< 80\text{ms}$; absolute maximum threshold $< 150\text{ms}$.
- Consistency Guarantee: Exactly-once match assignment per player ticket. A player must never enter two simultaneous game instances.
- Fairness Window: Balanced win probability (typically targeted between 45% and 55% per team).
Capacity Estimation
- Peak Concurrent Online Users (CCU): 10 Million.
- Active Queueing Users: ~5% of CCU at any moment $\approx 500,000$ active queue tickets across all games/modes.
- Ticket Join Rate: Assuming average game duration is 10 minutes (600s), $\frac{10\text{M players}}{600\text{s}} \approx 16,666\text{ joins/s}$. We design for a peak burst of $50,000\text{ joins/s}$.
- Heartbeat Rate: Heartbeats sent every $5\text{s}$. Total ping load $\approx \frac{500,000}{5} = \mathbf{100,000\text{ req/s}}$.
- Ticket Payload Size: ~500 Bytes (Ticket ID, Player/Party IDs, Skill Rating $\mu/\sigma$, Latency matrix across 8 regions, Queue timestamp).
- Memory Footprint: $500,000 \times 500\text{ B} \approx 250\text{ MB}$.
- Takeaway: Queue storage easily fits in memory. Memory is not the bottleneck; CPU scheduling, lock contention, and network I/O are the core scaling bottlenecks.
2. API Design
Player / Party Facing APIs
POST /v1/matchmaking/tickets
Header: Authorization: Bearer <token>
Request:
{
"idempotency_key": "uuid-v4",
"party_members": ["usr_101", "usr_102"],
"game_id": "exp_fps_01",
"mode": "ranked_5v5",
"region_latencies": {
"us-east": 24,
"us-west": 72,
"eu-central": 140
}
}
Response: 201 Created
{
"ticket_id": "tkt_8839201",
"status": "QUEUED",
"heartbeat_interval_s": 5
}
DELETE /v1/matchmaking/tickets/{ticket_id}
Response: 200 OK
POST /v1/matchmaking/tickets/{ticket_id}/heartbeat
Response: 200 OK
{
"status": "QUEUED", // QUEUED | PROPOSED | MATCHED | EXPIRED
"estimated_wait_s": 12
}
GET /v1/matchmaking/tickets/{ticket_id}/ws
(WebSocket connection stream for real-time MATCHED push updates)
Game Server / Backfill API
POST /v1/matchmaking/backfill
Request:
{
"server_id": "srv_east_9910",
"game_id": "exp_fps_01",
"mode": "ranked_5v5",
"region": "us-east",
"needed_slots": 2,
"existing_team_skills": [1450, 1520, 1480]
}
Response: 202 Accepted
3. Data Model & Ticket Lifecycle
State Machine Architecture
┌─────────────┐
│ QUEUED │
└──────┬──────┘
│ Matcher proposes group
▼
┌─────────────┐
┌─────┤ PROPOSED ├─────┐
│ └──────┬──────┘ │ Allocation Timeout /
│ │ Fleet │ Server Failure
│ │ Confirmed │ (Return to Queue)
│ ▼ │
Cancel │ ┌─────────────┐ │
/Expire │ │ MATCHED │ │
│ └─────────────┘ │
▼ ▼
┌───────────┐ ┌───────────┐
│ CANCELLED │ │ QUEUED │
└───────────┘ └───────────┘
- Player Active Index (
Redis Hash/DynamoDB): Key:player_id$\rightarrow$ Value:ticket_id(Enforces 1 active queue entry per player). - Ticket Record (Redis / In-Memory State):
{ "ticket_id": "tkt_8839201", "game_id": "exp_fps_01", "mode": "ranked_5v5", "party_size": 2, "members": ["usr_101", "usr_102"], "rating_mean": 1500.0, "rating_stddev": 50.0, "latencies": {"us-east": 24, "us-west": 72}, "enqueued_at": 1718000000, "last_heartbeat": 1718000005, "version": 3, "state": "QUEUED" } - Match Event Log (Kafka / DynamoDB):
Stores immutable historical record of completed matches (
match_id,ticket_ids,server_id,assigned_region,skill_variance,timestamp).
4. High-Level Architecture
┌───────────────────────────────┐
│ API Gateway / Edge │
└──────────────┬────────────────┘
│
▼
┌───────────────────────────────┐
│ Matchmaking Frontend Services │
│ (Stateless Auth/Sanitization) │
└──────────────┬────────────────┘
│
▼
┌───────────────────────────────┐
│ Partition Router │
└──────────────┬────────────────┘
│
┌───────────────────────────────┼───────────────────────────────┐
▼ ▼ ▼
┌──────────────────────┐ ┌──────────────────────┐ ┌──────────────────────┐
│ Matcher Engine Pool │ │ Matcher Engine Pool │ │ Matcher Engine Pool │
│ Partition: FPS_Ranked│ │ Partition: BR_Solo │ │ Partition: Long-Tail │
│ (Primary Node via │ │ (Primary Node via │ │ (Worker Pool / Hash)│
│ etcd Leasing) │ │ etcd Leasing) │ │ │
└───────────┬──────────┘ └───────────┬──────────┘ └───────────┬──────────┘
│ │ │
└──────────────────────┬────────┴───────────────────────────────┘
│ (Match Proposed)
▼
┌──────────────────────────────┐
│ Game Fleet Allocator │
└──────────────┬───────────────┘
│ Assign Server Token
▼
┌──────────────────────────────┐
│ Push Notification (Websocket)│
└──────────────────────────────┘
Key Components
- Matchmaking Frontend: Stateless microservice handling authentication, ticket validation, fetching ELO/Skill scores from the Player Rating Service, and writing ticket entries.
- Partition Router: Routes incoming tickets to specific Matcher worker nodes based on a partition key:
(game_id, mode, primary_region). - Matcher Engine Workers:
- Runs single-threaded or exclusive lock worker logic per partition to process tickets completely in memory without global distributed locking.
- Node leadership per queue partition is governed by etcd or Zookeeper leases.
- Game Fleet Allocator: Intermediary service communicating with cloud provider game instances (Agones / Kubernetes / Dedicated Baremetal). It allocates a game server IP and join token upon receiving a
PROPOSEDmatch event.
5. Match Formation Algorithm
The engine executes a periodic matching cycle (every $100\text{ms} - 250\text{ms}$) per queue partition.
Algorithm Steps
┌─────────────────────────────────────────────────────────┐
│ 1. Purge Stale Tickets (Heartbeat > 15s) │
└────────────────────────────┬────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────┐
│ 2. Priority Injection (Backfill Requests Processed) │
└────────────────────────────┬────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────┐
│ 3. Sort Pool by Effective Rating (Skill μ) │
└────────────────────────────┬────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────┐
│ 4. Sliding Window Expansion based on Wait Time (Δt) │
│ Skill Margin: ±(Base_Skill + α * Δt) │
│ Latency Ceiling: Min_RTT + β * Δt │
└────────────────────────────┬────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────┐
│ 5. Greedy Search & Bin Packing (Snake Draft Teams) │
└────────────────────────────┬────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────┐
│ 6. Evaluate Quality Function Score │
│ If Score > Threshold: Issue PROPOSED State │
└─────────────────────────────────────────────────────────┘
Step 1: Dynamic Window Relaxation
For a ticket in queue for $\Delta t$ seconds, the allowed rating variance $\Delta R$ and ping penalty relax dynamically:
$$\Delta R(\Delta t) = R_{\text{initial}} + \alpha \cdot \Delta t$$ $$\text{Max Ping}(\Delta t) = \text{RTT}_{\text{best}} + \beta \cdot \Delta t$$
Example: Base rating window starts at $\pm 50$ rating points. Every 5 seconds, $\Delta R$ increases by 25 points up to a hard ceiling of 400. This guarantees high-skill and low-skill outliers find a match eventually instead of queueing indefinitely.
Step 2: Bin-Packing and Team Balancing
- Pick the oldest ticket in the sorted pool as the Anchor Ticket to guarantee anti-starvation ($FIFO$-fairness for long-waiting players).
- Scan neighboring tickets within the Anchor's relaxed rating and latency bounds.
- Apply a Greedy Bin-Packing step to accommodate pre-made parties (e.g., combining a party of 3 and two solo players for a 5v5 mode).
- Balance the two teams using a Snake Draft based on rating:
- Rank candidates 1 to 10 by ELO:
- Team A: [1, 4, 5, 8, 9]
- Team B: [2, 3, 6, 7, 10]
Step 3: Candidate Scoring Function
Before finalizing, score the candidate match $M$:
$$S(M) = w_1 \cdot (100 - |\bar{R}_A - \bar{R}B|) + w_2 \cdot (150 - \text{Avg Ping}) + w_3 \cdot (\text{Wait Time}{\text{anchor}})$$
If $S(M) > Threshold(\Delta t)$, accept the candidate match, update state to PROPOSED, and forward to the Fleet Allocator.
6. Partitioning, Sharding, and Consistency
Eliminating Distributed Lock Contention
Running distributed locks across thousands of candidate tickets per second creates extreme database contention and latency spikes.
Solution: Single-Writer Queue Sharding
- Queue partitions are keyed by
(game_id, mode, region_group). - Exactly one active primary Matcher Engine node owns a given partition at any time, maintaining an in-memory queue representation.
- Ingestion nodes route join requests directly to the assigned partition instance.
Partition Key = Hash(game_id + ":" + mode + ":" + primary_region) % Total_Partitions
Handling the "Long-Tail" Problem
- Popular Titles: Dedicated Matcher Engine instances assigned to single partitions.
- Long-Tail Games: Thousands of obscure games with low queue volume are co-located onto a shared cluster of workers using Consistent Hashing with Virtual Nodes.
- Long-tail queues skip complex team scoring when pool size $< 50$; they default to a First-Come, First-Served (FCFS) fill strategy to minimize wait times.
Atomicity and Consistency Guarantee
To guarantee a player is never matched into two games concurrently (e.g., if a backfill match and a standard queue match select the same player simultaneously):
- Matcher issues a Compare-And-Swap (CAS) operation in the distributed data store:
UPDATE player_tickets SET state = 'PROPOSED', version = version + 1 WHERE ticket_id = 'tkt_8839201' AND state = 'QUEUED' AND version = 3; - If CAS fails for any member of a candidate match, the entire proposed match is aborted. The remaining valid members are safely returned to the top of the in-memory matching pool.
7. Fault Tolerance & Edge Cases
Matcher Worker Crash Recovery
- Matcher engines write state snapshots and incremental operations to an in-memory replicated log (e.g., Redis Stream or Redis Sentinel cluster).
- If a Matcher instance loses its leader lease in
etcd, a standby replica takes over the partition key, reads the uncommitted state log, and resumes matching ticks within $< 1\text{ second}$.
Allocation Failures & Two-Phase Handshake
If the Game Fleet Allocator fails to spawn a server instance (e.g., cloud capacity limits reached):
- The allocation attempt times out after 10 seconds.
- The match proposal is invalidated.
- The tickets transition back from
PROPOSEDtoQUEUED, preserving their originalenqueued_attimestamps so they maintain top priority in the next matching tick.
Heartbeat Timeouts & Silent Disconnects
- If a client app crashes or drops network connection without sending a
DELETE /ticketscall, its last heartbeat timestamp ages out. - During the first step of the tick loop, tickets with
now() - last_heartbeat > 15sare swept intoEXPIREDstate and removed from memory, keeping queue pools clean.
Mid-Game Backfilling
- Active game server detects player exit and sends
POST /v1/matchmaking/backfill. - The backfill request creates a specialized high-priority "Inverse Ticket" containing current game state and target skill score.
- The Matcher Engine prioritizes inverse tickets at the head of the tick loop, fetching matching solo candidates to fill open slots instantly.
8. Summary Architecture Comparison
| Scenario | Strategy / Technique | Key Benefit |
|---|---|---|
| High Queue Volume (Popular Game) | Isolated single-writer partition per mode/region | Zero distributed lock contention; fast in-memory matching |
| Low Queue Volume (Long Tail) | Multi-tenant worker pools via Consistent Hashing | Efficient resource usage without wasting idle nodes |
| Skill vs. Wait Time Balancing | Dynamic window expansion: $\Delta R(\Delta t)$ | Anti-starvation; maintains high fairness early while guaranteeing matches late |
| Race Conditions / Double Match | Versioned Compare-And-Swap (CAS) on state transition | Prevents assigning a player to multiple games concurrently |