Skill-Based 1v1 Pairing Backend for a Board Game Platform
System DesignModel answerLast updated
Design a scalable, fault-tolerant service that pairs two players of similar rating, loosens its criteria as waiting grows, supports cancellation, and discourages opponent dodging.
Build a Pairing Service for a Two-Player Board Game
You are designing the backend that connects two players for a head-to-head chess game. The platform has millions of people online at once. Players should get into a game quickly, and the opponents should be reasonably evenly matched.
What the service must do
- A player can enter a waiting pool. Their skill rating (Elo) is associated with the request.
- The service tries to find an opponent whose rating is close.
- The acceptable rating gap grows the longer a player waits.
- A player can withdraw from the pool at any time.
Qualities the system must have
- Speed: games should start as soon as a suitable opponent exists.
- Availability: if a single pairing node dies, the service keeps working.
- Elasticity: it must absorb bursts, for example during large events.
- Fairness: players should not be able to repeatedly avoid certain opponents without consequence.
What to deliver in your answer
- API: the main endpoints for entering and leaving the pool.
- Architecture: the components, how the pool is split across machines, and where state lives.
- Pairing logic: how the widening acceptable gap works in practice.
- Storage: how you keep player state and active search requests.
Behaviors to cover
- A player rated 1500 who has waited 10 seconds might only be paired with ratings from 1480 to 1520. After 30 seconds, the range might be 1400 to 1600.
- If a player's connection drops, their request must be cleaned up from the pool without manual action.
State your assumptions and back them with rough numbers. Discuss trade-offs and failure cases.
Hints
Hint 1
Do a quick capacity estimate with Little's law (arrival rate x average wait). The number of players waiting at any moment is probably small enough to fit comfortably in memory, so the real difficulty is coordination, not storage.
Hint 2
Treat the acceptable rating gap as a pure function of elapsed wait time that is recomputed each pairing cycle, rather than a value you store and update. Think about whether both players must accept each other's gap.
Hint 3
Ask what happens when a cancel request and a pairing decision happen at the same moment, and when a worker dies mid-cycle. Single ownership per partition plus an atomic claim step solves most of it.
Hint 4
For fairness, consider hiding the opponent's identity until the game is committed, escalating cooldowns for aborts right after a match, and avoiding immediate rematches of the same pair.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Clarify and size the problem
Questions to settle first:
- Are pools separated by time control (bullet, blitz, rapid) and region? Yes, and this gives natural partitions because players in different pools never meet.
- Is the rating supplied by the client? No. The server reads it from a rating service, which stops spoofing.
- Is there a confirmation step? Assume the game starts as soon as a pair is found.
Rough numbers:
| Quantity | Estimate |
|---|---|
| Concurrent users | ~5M |
| Average game length | ~10 min |
| Join rate | 5M / 600 s, about 8k/s (about 40k/s in bursts) |
| Target median wait | 3 to 5 s |
| Waiting tickets (Little's law) | about 40k typical, about 200k at peak |
| Ticket size | ~200 bytes |
| Total pool state | well under 50 MB |
Conclusion: data volume is tiny. The challenges are low-latency pairing cycles, avoiding double-assignment, failover, and cancel races. Pool state can be treated as soft state that is rebuildable.
2. API
POST /v1/pool/tickets
{ timeControl, region, idempotencyKey }
-> 202 { ticketId, status: "SEARCHING" }
DELETE /v1/pool/tickets/{ticketId}
-> 200 { status: "CANCELLED" }
-> 409 { status: "MATCHED", matchId }
GET /v1/pool/tickets/{ticketId}
-> { status, waitedMs, currentTolerance }
WebSocket: server pushes MatchFound; client sends heartbeat every ~5 s
Notes:
- Rating is never in the request body.
- One active ticket per player, enforced by a
player -> ticketindex and the idempotency key. - Cancel can lose the race against a pairing, so the 409 response returns the match so the client can proceed to the game.
3. Architecture
Client -WS-> Gateway (stateless) -> Ticket API -> Redis (per-partition pool)
^
Coordinator (leases) -> assigns -> Pairing workers
| MatchCreated
v
Event log -> Game allocator -> Game servers
\-> Gateway pushes to both players
Partitioning. Key by (timeControl, region). With roughly 20 such partitions, 200k peak tickets is easily handled. If one partition is too hot, split it into rating bands, but this is an escape hatch, not the default. Band borders are a problem: a 1590 player and a 1610 player should still be pairable. Solve it with a small border pool for tickets whose window crosses an edge, or with overlapping bands plus atomic claims.
Single writer per partition. Each partition is owned by exactly one worker through a lease (etcd or ZooKeeper, TTL about 5 s) carrying a monotonically increasing fencing token. Workers hold no durable state. If one dies, the lease expires and another takes over within seconds, with no tickets lost. The fencing token lets Redis reject writes from a stale owner.
4. Pairing logic
The tolerance is computed from wait time and never stored:
tol(t) = 20 for t <= 10 s
= min(20 + 4*(t - 10), 400) for t > 10 s
At 10 s a 1500 player accepts 1480 to 1520; at 30 s the window is 1400 to 1600; it is capped at +/-400. Sparse rating extremes can use a steeper ramp.
Every 100 to 200 ms each partition runs a cycle:
- Take waiting tickets ordered by join time, oldest first, to prevent starvation.
- For ticket A, query a sorted set by rating over
[A.elo - tol(A), A.elo + tol(A)], costing O(log n + k). - Filter candidates B:
- Mutual acceptance:
|A.elo - B.elo| <= tol(B), so a fresh joiner is not forced into a big gap because A is desperate. Optionally relax tomax(tol)once someone has waited more than about 45 s. - Exclude recent opponents of A.
- Mutual acceptance:
- Choose the best B by smallest rating difference, breaking ties by longer wait.
- Atomically claim both tickets and emit a match event.
Greedy oldest-first is close to optimal at this scale. Global min-cost matching adds latency for little gain.
Atomic claim. A Lua script (all keys sharing a hash tag so they live in one slot) checks both tickets are still SEARCHING, flips them to MATCHED, and removes them from the sorted set. If either check fails, the cycle skips that pair. This is also what resolves cancel-versus-match races: whichever operation runs first wins, and the loser gets a clear answer.
5. Storage
Redis (replicated, append-only persistence):
| Key | Type | Content |
|---|---|---|
pool:{tc:region} | sorted set | score = rating, member = ticketId |
ticket:{id} | hash | player, rating, joinedAt, status, version, leaseExpiresAt |
player:{pid}:ticket | string with TTL | active ticket |
dodge:{pid} | counter with TTL | abort strikes |
Durable stores: a relational or wide-column database for profiles, ratings, game history, and penalties; an event log for match events and analytics. Losing Redis is survivable: clients get an error and auto-rejoin.
Disconnects. Each heartbeat extends leaseExpiresAt. A WebSocket close triggers an immediate cancel. Both a sweeper and the pairing cycle ignore tickets whose lease is more than about 15 s stale, so a dead client is never matched.
6. Fairness
- Hide the opponent until committed. Reveal identity only after the game exists, so dodging means aborting a real game.
- Escalating cooldowns. Aborting before the first move or leaving right after a match increments a strike counter, leading to 1, 5, then 30 minute cooldowns, and rating penalties for chronic cases.
- No immediate rematches of the same pair, which also hinders collusion and queue sniping.
- Monitor for anomalies such as pairs repeatedly hitting the pool together.
7. Trade-offs and common mistakes
- Wider tolerance means faster games but worse quality; tune against median wait and rating-gap metrics.
- A pure Redis sorted-set answer misses the real issues: double matching, failover, and cancel races.
- Storing tolerance as mutable state creates update load and stale values; compute it.
- Ignoring band borders, trusting client ratings, and omitting heartbeats are frequent gaps.
- Scaling for bursts: pre-scale workers on schedule for known events, and shed or queue joins with a clear "searching" status rather than failing.