Connections, Timeouts & Reconnects
UDP has no connections, so a game protocol invents its own: a handshake to start, keep-alives to show both sides are still there, a timeout to notice when one isn't, and, often forgotten until launch week, a way to reconnect to the same match after a Wi-Fi drop without losing your character.
The handshake
A naive server creates a player as soon as a "connect" packet arrives. That has two problems: anyone can send connect packets with a forged source address (so the server allocates slots for clients that don't exist and sends traffic at innocent victims), and anyone who finds the server's IP can join without a ticket from matchmaking. A safer handshake looks like this:
client server
| -- ConnectRequest(ticket) -----------> | ticket: signed by your backend, short-lived,
| | names the player, the match and the server
| <------------ Challenge(nonce) ------- | small reply, no state stored yet
| -- ChallengeResponse(nonce, ticket) -> | proves the client really receives at that address
| <------------ Accepted(playerId) ----- | NOW allocate a slot- The challenge proves the client can receive packets at its claimed address. The server can make the nonce from an HMAC of the address and time, so it doesn't even have to remember it.
- Pad the request to at least the size of the reply, so the server can't be used to amplify an attack (a small spoofed request triggering a big reply to a victim).
- The ticket comes from your backend after sign-in and matchmaking (Accounts & Sign-In, Lobbies & Matchmaking). The game server checks its signature and expiry, so it never needs to talk to the account system during play.
Libraries such as Valve's GameNetworkingSockets, netcode.io (used by yojimbo) and the engines' transports implement this pattern; you mostly provide the ticket.
Keep-alives and timeouts
When no game traffic flows (a menu, a paused co-op game), each side still sends a tiny keep-alive packet every so often (e.g. 4–10 times per second during play, about once a second when idle). If nothing at all arrives for the timeout period (commonly 5–15 seconds), the connection is considered dead. Too short, and a two-second Wi-Fi hiccup kicks players; too long, and everyone stares at a frozen opponent.
Keep-alives also keep NAT mappings open: home routers forget a UDP "connection" after some idle time (often 30 seconds or more, sometimes less), after which the server's packets no longer reach the client.
Disconnect is not the end of the match
Players drop for reasons that aren't their fault: a phone switching from Wi-Fi to 4G (its address changes!), a router restart, a crash. A good game keeps their slot for a grace period:
- On timeout, the server marks the player disconnected but keeps their entity (frozen, hidden, or controlled by a bot) and their state (score, inventory, team).
- At connect time the server gave the client a reconnect token (random, unguessable, bound to player and match).
- A new connection presenting a valid token within the grace period takes over the old slot, gets a full snapshot (it has no valid baseline for deltas), and plays on.
- After the grace period the slot is freed, and the match result records an abandon.
type Slot = { player: string; token: string; state: 'connected' | 'disconnected'; lastHeard: number; droppedAt?: number; score: number };
const TIMEOUT = 5, GRACE = 30;
const slots = new Map<string, Slot>();
const log = (t: number, msg: string) => console.log(`t=${String(t).padStart(2)}s ${msg}`);
function connect(t: number, player: string, token?: string) {
const old = [...slots.values()].find((s) => s.player === player);
if (old && token === old.token && old.state === 'disconnected') {
old.state = 'connected'; old.lastHeard = t;
return log(t, `${player} RECONNECTED after ${t - old.droppedAt!}s, score kept: ${old.score} (sending full snapshot)`);
}
if (old && token !== old.token) return log(t, `${player} rejected: bad reconnect token`);
const fresh = `tok-${player}-${t}`; // a real server uses crypto-random bytes
slots.set(player, { player, token: fresh, state: 'connected', lastHeard: t, score: 0 });
log(t, `${player} connected, reconnect token issued`);
}
function tick(t: number, heardFrom: string[]) {
for (const s of slots.values()) {
if (heardFrom.includes(s.player)) { s.lastHeard = t; if (s.state === 'connected') s.score += 1; }
if (s.state === 'connected' && t - s.lastHeard >= TIMEOUT) {
s.state = 'disconnected'; s.droppedAt = t;
log(t, `${s.player} timed out (silent for ${TIMEOUT}s), slot kept for ${GRACE}s`);
}
if (s.state === 'disconnected' && t - s.droppedAt! >= GRACE) {
slots.delete(s.player);
log(t, `${s.player} grace period over: slot freed, counted as abandon`);
}
}
}
connect(0, 'ana'); connect(0, 'ben');
const anaToken = slots.get('ana')!.token;
for (let t = 1; t <= 50; t++) {
const heard = ['ben'];
if (t <= 3 || t >= 13) heard.push('ana'); // ana's Wi-Fi drops from t=4 to t=12
if (t > 6) heard.splice(heard.indexOf('ben'), 1); // ben quits the game for good at t=7
if (t === 12) connect(t, 'ana', 'tok-guess'); // someone tries to steal ana's slot
if (t === 13) connect(t, 'ana', anaToken);
tick(t, heard);
}
console.log([...slots.values()].map((s) => `${s.player}: ${s.state}, score ${s.score}`).join(' | '));t= 0s ana connected, reconnect token issued
t= 0s ben connected, reconnect token issued
t= 8s ana timed out (silent for 5s), slot kept for 30s
t=11s ben timed out (silent for 5s), slot kept for 30s
t=12s ana rejected: bad reconnect token
t=13s ana RECONNECTED after 5s, score kept: 3 (sending full snapshot)
t=41s ben grace period over: slot freed, counted as abandon
ana: connected, score 41
Practical details
- Send a reason with a deliberate disconnect ("kicked: too many invalid inputs", "server shutting down", "version mismatch") so the client can show a real message instead of "Connection lost".
- Tell everyone else: show "Ana is reconnecting…" above her frozen character. Players are far more patient with a visible reason.
- Mobile apps get suspended in the background. Treat returning from the background like a reconnect: request a full snapshot and resync the clock.
- Rejoin from the main menu: if the game crashed, the next launch should ask the backend "am I in a match?" and offer to rejoin, using the same flow.
- Host migration (choosing a new host when a peer-hosted game's host leaves) is the peer-to-peer version of this problem and much harder; dedicated servers avoid it (Peer-to-Peer vs Client-Server).
Test yourself
Why does a server send a challenge before allocating a player slot?
- To measure the client's FPS
- To prove the client really receives packets at its claimed address, defeating spoofed connection floods
- To encrypt the ticket
- To pick a tick rate
A player's connection times out mid-match. What should a well-designed server do first?
- Delete the player and their score immediately
- Keep the slot and state for a grace period and accept a reconnect with the player's token
- End the match for everyone
- Ban the player
What must a reconnecting client receive first?
- A delta against its last snapshot
- A full snapshot, because it has no acknowledged baseline any more
- Only the chat history
- Nothing; it continues where it was