Real-Time Multiplayer Typing Race Backend with Penalty Freezes
System DesignModel answerLast updated
Design a backend for a multiplayer typing race where a mistyped key freezes input for 1.5 seconds, covering match servers, matchmaking, ratings, latency fairness and failure recovery.
You are designing the backend for SprintType, an online game in which several people race to type the same text. Typing is penalized for sloppiness: whenever a player presses a wrong key, their input is frozen for 1.5 seconds and every keypress during that window is discarded. The first player to complete the text wins. Others are ranked by completion time, or by how far they got if the clock runs out.
Product behavior
- Finding a game. A quick-play button places a player in a public match of 3 to 6 players of comparable skill. Friends can instead create a private room via an invite code (2 to 6 players).
- Phases of a match. Lobby, then a 5-second countdown, then the race (hard limit 120 s), then a results screen. A text of 150 to 400 characters is picked when the countdown begins and shown to everyone at the same moment.
- Freeze rule. After a wrong key, the cursor stays on the character that was missed. Input is dead for 1.5 s. The first correct key pressed once the freeze is over moves the cursor forward.
- Live view. Each participant sees all opponents' progress and frozen/unfrozen status, updated at least 10 times per second.
- Scoring and ratings. Store WPM, accuracy and placement for each match. Keep a long-lived skill rating that drives matchmaking, along with all-time and weekly leaderboards.
- Dropped connections. A player who disconnects may come back within 10 s and pick up where they were. After that they are recorded as DNF (did not finish).
Non-functional targets
- Scale: 1.5M daily active users, up to 120k simultaneous players (about 25k matches running at once).
- Latency: a keypress should show up on opponents' screens in under 150 ms at p95 inside a region. Players are spread over North America, Europe and Asia-Pacific.
- Fairness: a player with 180 ms of latency should not lose to an equally skilled player with 20 ms purely because of the network.
- Integrity: the server is the source of truth. Bots and macro tools should be detectable.
- Queue time: p90 under 15 s at peak, widening the allowed skill gap as waiting time grows.
What you should produce
- A high-level architecture: components and the protocols used between client and server.
- The match session design: where match state is kept, how each keystroke is checked, and precisely how the freeze is applied and ended.
- The matchmaking algorithm and its service.
- The ranking design: a per-match score, a persistent rating, and how leaderboards are stored.
- Your approach to latency fairness and its trade-offs.
- Failure handling: match server crash, client reconnect, whole-region outage.
State clearly any assumptions you make about text generation, scoring formulas and regions.
Hints
Hint 1
Keep each match entirely on one stateful server and think about how the gateway finds that server. Then ask whether the freeze really needs a timer at all, or whether a stored deadline compared against the current time is enough.
Hint 2
Separate what must be low-latency (progress broadcasts) from what can be asynchronous (ratings, leaderboards). Batching snapshots on a fixed tick is much cheaper than fanning out every keystroke.
Hint 3
For fairness, decide what quantity determines the winner: arrival time at the server or elapsed typing time on the client. Think about how to align start times across clients, how to bound client-reported times, and what that opens up for cheaters.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Assumptions
- Texts come from a curated, pre-validated pool, tagged by difficulty and length. The text is chosen by the server at countdown start, so clients cannot influence it.
- Three regions (NA, EU, APAC). Matches run inside one region. Ratings and leaderboards are global but written asynchronously.
- Per-match score = net WPM x accuracy^2. Placement is by finish time, then by progress for those who did not finish.
1. Architecture
Client --WebSocket--> Regional gateway (routes by match_id)
|
+-------------------+---------------------+
Matchmaker Match servers Profile/Rating svc
(Redis queues) (stateful, in-memory) (Postgres + Redis ZSETs)
| | results event
+--> Match allocator --> Kafka "match-results" --> rating worker, analytics
- WebSocket for gameplay (bidirectional, low overhead). Plain HTTPS for login, profile and leaderboard reads.
- Match servers are stateful processes, each holding on the order of 2k matches in memory. A match never spans two servers. A registry in Redis (
match_id -> server, kept alive by heartbeats with a TTL) lets the gateway route every socket of a match to the same process. - The allocator picks the region near the median RTT of the players and places the match on a server with spare capacity.
2. Match session and the freeze
Per player: cursor, locked_until (server monotonic clock), errors, keystrokes, finished_at. Per match: text, start_at, players, phase.
Keystroke handling. The client sends {seq, char, client_ts}. The server:
- Discards the key if
now < locked_until(the client also blocks locally for responsiveness, but the server decides). - If
char == text[cursor], advances the cursor. Reaching the end setsfinished_at. - Otherwise increments
errorsand setslocked_until = now + 1500.
The freeze needs no timer. It is a stored deadline, and the first key after that deadline is simply processed normally. This avoids per-player timers and race conditions between "unlock" and "keypress". The server also pushes a locked {until} event so the UI can show a countdown.
Broadcast. Each match has a 10 Hz tick that sends a compact snapshot ([player, cursor, locked], ~40 bytes per player). Batching bounds fan-out regardless of typing speed.
Client prediction. The client advances its own cursor immediately and reconciles with server acks by seq. Because the text is deterministic, corrections are rare.
Capacity. 120k players x ~6 keys/s is roughly 720k keystroke messages/s globally. Each is a cheap array lookup, so a few dozen match servers per region cover peak with headroom. Memory per match is a few KB.
3. Matchmaking
- Queue key:
(region, mode, rating bucket of 100). Redis sorted sets, scored by enqueue time. - A worker per region runs every 500 ms. For each bucket it tries to form a group of up to 6. If fewer than 3 players are present and the oldest has waited more than 5 s, it widens to neighboring buckets (+/-100, +/-200, ...). Past ~12 s it accepts 2-player matches or adds clearly labeled practice bots. This keeps p90 wait under 15 s.
- Players with high rating uncertainty (rating deviation) get a wider band from the start.
- Cross-region groups are allowed only when every member has RTT under ~150 ms to the chosen region.
- Private rooms bypass the queue. The allocator creates the match directly and stores an invite code in Redis with a 10-minute TTL.
4. Ranking
- Match score: net WPM x accuracy^2 rewards speed and precision together, so spamming keys or typing slowly and perfectly are both suboptimal.
- Persistent rating: Glicko-2 (or TrueSkill), treating an N-player match as N(N-1)/2 pairwise results. The rating deviation lets new players converge fast.
- Storage: Postgres tables
player_ratings(player_id, rating, rd, updated_at),matches, and append-onlymatch_players. Leaderboards in Redis sorted sets:lb:globalandlb:weekly:{iso_week}(with expiry). A rating worker consumesmatch-resultsfrom Kafka and is idempotent permatch_id, so replays never double-count.
5. Latency fairness
The winner should be decided by typing time, not by whose packet arrives first.
- Synchronized start. During the countdown, NTP-style pings estimate each client's clock offset. The server sends
start_atin server time and each client reveals the text at its local equivalent, so all players start within a few ms. - Finish time from client elapsed time, bounded by the server. Use
client_finish_ts - client_start_ts, accepted only if it lies within[server_elapsed - rtt - eps, server_elapsed + eps]. A laggy player's last packet arrives late but is not penalized. - Freeze measured in client time, so high-latency players do not effectively serve longer freezes. The server enforces a lower bound so a client cannot shorten its own freeze.
- Opponent bars may lag by up to one RTT. This is cosmetic only.
Trade-offs. Trusting client timestamps creates a cheating surface. Mitigate with the bounds check, keystroke-interval analysis (humans have variance, macros are too regular or too fast), and replay review of top-ranked players. Pure server time is simpler and harder to cheat but systematically favors players near the server.
6. Failure handling
- Client drop: the client reconnects, the gateway finds the match server through the registry, and the server resumes the session. The freeze deadline keeps running. After 10 s the player becomes DNF.
- Match server crash: state is lost. Matches last at most 2 minutes, so void them, put players back in the queue with priority, and skip rating updates. Persisting every keystroke to an external store would add cost and latency for little benefit.
- Region outage: route new matches to the nearest healthy region and void in-flight matches. Ratings and leaderboards are replicated asynchronously, so they survive.
- Deploys: put a server in drain mode (no new matches, let current ones finish).
Common mistakes
- Running the freeze with timers instead of a stored deadline.
- Broadcasting every keystroke to every opponent rather than batching on a tick.
- Deciding the winner by server arrival time, which penalizes distant players.
- Persisting live match state externally on every key, which adds latency for a 2-minute game.
- Updating ratings non-idempotently, so a retried event counts twice.