Never Trust the Client
Every copy of your game client runs on a machine you don't control. Players can attach a debugger, patch memory, replace the executable, or skip the game entirely and write packets with a script. So anything the client sends is a claim, not a fact. The server's job is to treat each message as a request and decide whether the game rules allow it.
This is the security half of the authoritative server: the server owns the state, clients send inputs, and the server checks every input before it changes anything.
What the client may say
| Client sends | Safe? | Why |
|---|---|---|
| "I pressed forward and right this tick" | yes | the server computes the movement itself |
| "My position is (812, 40)" | no | a teleport hack is one edited number |
| "I fired, aiming at yaw 1.2 rad" | yes, after checks | the server checks cooldown, ammo and what the shot hits |
| "I hit player 7 for 90 damage" | no | damage is a server rule |
| "I bought the sword for 0 gold" | no | prices and balances live on the server |
| "I picked up item 41" | after checks | is the item there, and is the player close enough? |
The rule of thumb: clients send intent, servers decide outcome. When a client must send a result (for example, a position in a game that uses client-authoritative movement to save server CPU), the server still checks that the result is possible.
The usual checks
- Sequence numbers only go up. An input with a sequence number the server has already processed is a duplicate or a replay. Drop it.
- Clamp analog values. A movement stick is a vector of length at most 1. A hacked client can send length 50 and move 50 times faster unless the server normalizes it.
- Speed and teleport checks. If clients report positions, compare the distance moved with
maxSpeed × elapsed timeplus a small tolerance for jitter. - Cooldowns and fire rate. The server records when each player last fired and ignores shots that come too soon. The time comes from the server's clock, never from a timestamp in the message.
- Resources. Ammo, mana, gold and inventory counts are checked and changed on the server.
- Range and line of sight. Interacting with a door 300 m away, or hitting a target through a wall, is rejected.
- Ownership. A client may only send inputs for the entity it controls, and only use items it owns.
A validator, message by message
Here is a server-side validator in C#. It receives a short scripted stream of messages from one player (some honest, some forged) and prints its decision for each. The server ticks at 20 Hz, so 1 tick = 50 ms.
using System;
using System.Collections.Generic;
class Player
{
public double X, Y;
public int LastSeq = -1;
public int LastShotTick = -100;
public int Ammo = 3;
}
record Msg(int Tick, int Seq, string Kind, double A = 0, double B = 0);
class Program
{
const double MaxSpeed = 6.0; // metres per second
const double TickSeconds = 0.05; // 20 Hz server
const int FireCooldownTicks = 4; // 200 ms between shots
const double MaxInteractRange = 3.0;
static string Validate(Player p, Msg m)
{
if (m.Seq <= p.LastSeq) return quot;REJECT replay/old seq {m.Seq} (last {p.LastSeq})";
p.LastSeq = m.Seq;
switch (m.Kind)
{
case "move":
{
double len = Math.Sqrt(m.A * m.A + m.B * m.B);
double ax = m.A, ay = m.B;
string note = "";
if (len > 1.0) { ax /= len; ay /= len; note = quot; (stick length {len:F1} clamped to 1)"; }
p.X += ax * MaxSpeed * TickSeconds;
p.Y += ay * MaxSpeed * TickSeconds;
return quot;ACCEPT move -> ({p.X:F2}, {p.Y:F2}){note}";
}
case "fire":
if (m.Tick - p.LastShotTick < FireCooldownTicks)
return quot;REJECT fire: cooldown ({m.Tick - p.LastShotTick} ticks since last shot)";
if (p.Ammo == 0) return "REJECT fire: no ammo";
p.LastShotTick = m.Tick;
p.Ammo--;
return quot;ACCEPT fire, ammo left {p.Ammo}";
case "use":
{
double dx = m.A - p.X, dy = m.B - p.Y;
double dist = Math.Sqrt(dx * dx + dy * dy);
return dist <= MaxInteractRange
? quot;ACCEPT use object at {dist:F1} m"
: quot;REJECT use: object is {dist:F1} m away";
}
default:
return quot;REJECT unknown message '{m.Kind}'";
}
}
static void Main()
{
var p = new Player();
var stream = new List<Msg>
{
new(1, 1, "move", 1, 0),
new(2, 2, "move", 30, 0), // speed hack: huge stick value
new(2, 2, "move", 1, 0), // replayed packet
new(3, 3, "fire"),
new(4, 4, "fire"), // too soon
new(8, 5, "fire"),
new(12, 6, "fire"),
new(16, 7, "fire"), // out of ammo
new(17, 8, "use", 1.5, 0.5), // a chest next to the player
new(18, 9, "use", 40, 12), // a chest across the map
new(19, 10, "setHealth", 100),
};
foreach (var m in stream)
Console.WriteLine(quot;tick {m.Tick,2} seq {m.Seq,2} {m.Kind,-9} {Validate(p, m)}");
}
}tick 1 seq 1 move ACCEPT move -> (0.30, 0.00)
tick 2 seq 2 move ACCEPT move -> (0.60, 0.00) (stick length 30.0 clamped to 1)
tick 2 seq 2 move REJECT replay/old seq 2 (last 2)
tick 3 seq 3 fire ACCEPT fire, ammo left 2
tick 4 seq 4 fire REJECT fire: cooldown (1 ticks since last shot)
tick 8 seq 5 fire ACCEPT fire, ammo left 1
tick 12 seq 6 fire ACCEPT fire, ammo left 0
tick 16 seq 7 fire REJECT fire: no ammo
tick 17 seq 8 use ACCEPT use object at 1.0 m
tick 18 seq 9 use REJECT use: object is 41.2 m away
tick 19 seq 10 setHealth REJECT unknown message 'setHealth'
Notice what the validator does not do: it never trusts a timestamp, a position or a damage number from the message. The cooldown uses the server's tick, and movement is computed on the server from a clamped stick.
Reject, correct, or flag?
Not every failed check means cheating. Packets arrive late, in bursts, or twice; a player on a bad connection can trip a naive speed check. Choose the response to fit the check:
| Situation | Response |
|---|---|
| Duplicate or old sequence number | drop silently (it happens on honest connections) |
| Movement slightly too far | correct: send the server's position, the client snaps back (reconciliation) |
| Shot during cooldown | drop the shot; maybe count it |
| Stick length 30, unknown message type, negative item count | no honest client sends this: drop and flag the account |
| Repeated impossible messages | disconnect, then review (see Cheat Types & Anti-Cheat) |
Keep a per-player suspicion counter rather than banning on the first strange packet. Ban decisions belong to a slower, reviewed process.
A tolerant speed check in TypeScript
When clients do report positions, the check must allow for jitter: two reports can arrive almost together after a delay. A naive "distance since the last packet ÷ time since the last packet" check rejects every bunched packet, and once it has rejected one, the player's next honest reports look like teleports too.
A sturdier version keeps a movement budget, like a token bucket: time refills it at the maximum speed (plus some slack), capped at half a second of movement, and every accepted report spends what it moved.
type Report = { serverMs: number; x: number };
const MAX_SPEED = 6; // m/s
const SLACK = 1.15; // 15 % for jitter and rounding
const CAP = MAX_SPEED * 0.5; // never bank more than 0.5 s of movement
let budget = 1.0, lastMs = 0, lastX = 0;
const reports: Report[] = [
{ serverMs: 100, x: 0.6 },
{ serverMs: 200, x: 1.2 },
{ serverMs: 210, x: 1.8 }, // arrived late, bunched with the previous one
{ serverMs: 400, x: 3.0 },
{ serverMs: 500, x: 9.0 }, // teleport
{ serverMs: 600, x: 3.6 },
];
for (const r of reports) {
budget = Math.min(CAP, budget + MAX_SPEED * SLACK * (r.serverMs - lastMs) / 1000);
lastMs = r.serverMs;
const moved = Math.abs(r.x - lastX);
if (moved <= budget) {
budget -= moved;
lastX = r.x;
console.log(`t=${r.serverMs}ms x=${r.x.toFixed(1)} ok moved ${moved.toFixed(2)}, budget left ${budget.toFixed(2)}`);
} else {
console.log(`t=${r.serverMs}ms x=${r.x.toFixed(1)} REJECT moved ${moved.toFixed(2)} > budget ${budget.toFixed(2)}, snap back to ${lastX.toFixed(1)}`);
}
}t=100ms x=0.6 ok moved 0.60, budget left 1.09
t=200ms x=1.2 ok moved 0.60, budget left 1.18
t=210ms x=1.8 ok moved 0.60, budget left 0.65
t=400ms x=3.0 ok moved 1.20, budget left 0.76
t=500ms x=9.0 REJECT moved 6.00 > budget 1.45, snap back to 3.0
t=600ms x=3.6 ok moved 0.60, budget left 1.54
The bunched packet at 210 ms passes because the budget saved up earlier covers it, the teleport is rejected, and the next honest report is accepted again. The cap matters: without it, a player could stand still for a minute and then "spend" a minute of movement in one jump.
Note: Validation is cheap compared with simulation, so do it for every message. The expensive anti-cheat work (statistics, replays) happens offline.
Test yourself
A client sends { "fire": true, "timestamp": 1050 }. Which clock should the server use to enforce the fire-rate cooldown?
- The timestamp in the message
- The server's own tick or clock
- The average of both
- The client's ping
Why does the validator normalize a movement stick vector whose length is greater than 1?
- To save bandwidth
- Because a hacked client could send a long vector and move faster than the maximum speed
- Because floats can't exceed 1
- To make prediction easier
An input arrives with a sequence number lower than one already processed. What is the usual response?
- Ban the player
- Drop it silently: duplicates and reordering happen on honest connections
- Process it again
- Disconnect the player