TExcelTAD
Home › Multiplayer Game Networking › Rate Limiting & Abuse

Rate Limiting & Abuse

A game server is a public service that anyone can send packets to. Even with perfect validation, a client that sends 5,000 "fire" messages a second makes the server parse, check and reject 5,000 messages a second. Chat spam, login floods and request storms from a buggy client have the same effect. Rate limiting puts a ceiling on how much work each sender can cause, before validation and before any expensive work.

Token bucket

The standard tool is the token bucket:

  • the bucket holds at most capacity tokens;
  • it refills at rate tokens per second;
  • each message costs one token (or more for expensive messages);
  • a message that finds the bucket empty is dropped (or delayed).

The capacity allows short bursts (a player mashing a button, three packets that arrived together after jitter), while the rate limits the average. Here is one bucket fed by a scripted client on a simulated clock: an honest phase, a burst, then a flood.

ts · try it yourself
class TokenBucket {
  private tokens: number;
  private lastMs = 0;
  constructor(private capacity: number, private perSecond: number) { this.tokens = capacity; }
  take(nowMs: number, cost = 1): boolean {
    this.tokens = Math.min(this.capacity, this.tokens + (nowMs - this.lastMs) / 1000 * this.perSecond);
    this.lastMs = nowMs;
    if (this.tokens >= cost) { this.tokens -= cost; return true; }
    return false;
  }
  get level() { return this.tokens; }
}

// Fire messages: 10 per second on average, bursts of up to 5.
const fire = new TokenBucket(5, 10);

// [time in ms, messages sent in that 100 ms tick]
const ticks: [number, number][] = [[100, 1], [200, 1], [300, 6], [400, 1], [500, 20], [600, 20], [700, 1], [1200, 3]];

for (const [ms, count] of ticks) {
  let ok = 0;
  for (let i = 0; i < count; i++) if (fire.take(ms)) ok++;
  console.log(`t=${String(ms).padStart(4)}ms sent ${String(count).padStart(2)}  allowed ${String(ok).padStart(2)}  dropped ${String(count - ok).padStart(2)}  tokens left ${fire.level.toFixed(1)}`);
}
t= 100ms sent  1  allowed  1  dropped  0  tokens left 4.0
t= 200ms sent  1  allowed  1  dropped  0  tokens left 4.0
t= 300ms sent  6  allowed  5  dropped  1  tokens left 0.0
t= 400ms sent  1  allowed  1  dropped  0  tokens left 0.0
t= 500ms sent 20  allowed  1  dropped 19  tokens left 0.0
t= 600ms sent 20  allowed  1  dropped 19  tokens left 0.0
t= 700ms sent  1  allowed  1  dropped  0  tokens left 0.0
t=1200ms sent  3  allowed  3  dropped  0  tokens left 2.0

The burst at 300 ms is mostly allowed thanks to the saved tokens; the flood gets one message per 100 ms (the refill rate) and nothing more; after a quiet half-second the bucket is full again.

Leaky bucket is the close cousin: messages enter a queue that drains at a fixed rate, and a full queue drops new arrivals. It smooths traffic instead of allowing bursts, which suits outgoing traffic (sending to a client at a steady rate). For incoming game messages, the token bucket's burst tolerance is usually what you want.

Budgets per message type

One bucket per connection is a start, but message types have very different costs and normal rates:

Message Normal rate Bucket (capacity / per second) Cost of abuse
input (movement) one per client tick (30–60 Hz) 10 / 70 CPU per message
fire weapon fire rate 5 / 10 hit tests, rewinds
chat a few per minute 3 / 0.5 moderation, other players' screens
emote / ping marker occasional 2 / 1 spam on other screens
matchmaking request once per queue 1 / 0.1 backend load

Inputs need a little more than the client tick rate, because jitter delivers them in clumps. Chat needs a very low rate with a small burst.

Escalation: warn, mute, kick

Dropping excess messages protects the server, but a client that keeps hitting the limit is either broken or hostile. Count strikes in a time window and escalate:

ts · try it yourself
type Action = 'ok' | 'dropped' | 'warned' | 'muted' | 'kicked';

class ChatGuard {
  private tokens = 3;
  private lastMs = 0;
  private strikes: number[] = [];        // times of recent violations
  private mutedUntil = 0;
  onMessage(ms: number): Action {
    if (ms >= this.mutedUntil) {
      this.tokens = Math.min(3, this.tokens + (ms - this.lastMs) / 1000 * 0.5);
      this.lastMs = ms;
      if (this.tokens >= 1) { this.tokens -= 1; return 'ok'; }
    }
    // Over the limit, or talking while muted: both count as a strike.
    this.strikes = this.strikes.filter((t) => ms - t < 30_000);   // strikes expire after 30 s
    this.strikes.push(ms);
    if (this.strikes.length >= 6) return 'kicked';
    if (ms < this.mutedUntil) return 'muted';
    if (this.strikes.length >= 4) { this.mutedUntil = ms + 10_000; return 'muted'; }
    if (this.strikes.length === 1) return 'warned';
    return 'dropped';
  }
}

const guard = new ChatGuard();
const times = [0, 400, 800, 1200, 1600, 2000, 2400, 2800, 6000, 13000, 13100, 13200, 13300];
for (const t of times) console.log(`t=${(t / 1000).toFixed(1).padStart(4)}s chat -> ${guard.onMessage(t)}`);
t= 0.0s chat -> ok
t= 0.4s chat -> ok
t= 0.8s chat -> ok
t= 1.2s chat -> warned
t= 1.6s chat -> dropped
t= 2.0s chat -> ok
t= 2.4s chat -> dropped
t= 2.8s chat -> muted
t= 6.0s chat -> muted
t=13.0s chat -> ok
t=13.1s chat -> ok
t=13.2s chat -> ok
t=13.3s chat -> kicked

The spammer gets three messages through, then a warning, two dropped messages, a 10-second mute (messages sent while muted count as strikes too), and a kick when they flood again right after the mute ends. One message slips through at 2.0 s because the bucket refilled a token; rate limits are about averages, not single messages. A real game would also log each step with the account id, so moderators can see the history.

Logins, APIs and 429

The backend needs the same protection, keyed differently:

  • Per account and per IP for logins: slow down password guessing (with an identity provider such as TAD, this is the provider's job; see Accounts & Sign-In).
  • Per account for API calls such as "claim reward" or "join queue".
  • Global limits that protect a database during a launch-day rush.

HTTP APIs answer an over-limit request with 429 Too Many Requests, often with a Retry-After header. Clients must back off instead of retrying immediately, or every client retries at once and the overload never ends. The standard pattern is exponential backoff with jitter: wait base × 2^attempt, capped, then pick a random time up to that value so clients spread out.

ts · try it yourself
function mulberry32(seed: number) {
  return () => {
    seed = (seed + 0x6d2b79f5) | 0;
    let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
  };
}

function backoffMs(attempt: number, rnd: () => number, retryAfterS?: number): number {
  if (retryAfterS !== undefined) return retryAfterS * 1000;      // the server knows best
  const ceiling = Math.min(30_000, 500 * 2 ** attempt);            // 0.5 s, 1 s, 2 s, ... capped at 30 s
  return Math.round(rnd() * ceiling);                              // "full jitter"
}

for (const client of [1, 2, 3]) {
  const rnd = mulberry32(client);
  const waits = [0, 1, 2, 3, 4, 5].map((a) => backoffMs(a, rnd));
  console.log(`client ${client}: ${waits.map((w) => `${w}ms`).join(', ')}`);
}
console.log(`with Retry-After: 120 -> ${backoffMs(0, mulberry32(9), 120)}ms`);
client 1: 314ms, 3ms, 1055ms, 3924ms, 7747ms, 4498ms
client 2: 367ms, 325ms, 571ms, 2152ms, 7002ms, 10093ms
client 3: 360ms, 39ms, 912ms, 300ms, 6104ms, 7699ms
with Retry-After: 120 -> 120000ms

Three clients that failed at the same moment retry at different times, and the delays grow with every failure.

Tip: Put rate limits in front of the expensive work. A dropped message should cost a few nanoseconds of bucket arithmetic, not a parse, a database read and a log line each. Log aggregated counts ("player 42 dropped 1,830 fire messages in 10 s"), not one line per drop.

Test yourself

A token bucket has capacity 5 and refills 10 tokens per second. It is full, and a client sends 8 messages at the same instant. How many are allowed?

  1. 8
  2. 5
  3. 10
  4. 1

Why do retry delays after a 429 include random jitter?

  1. To make the code harder to read
  2. So clients that failed together don't all retry at the same moment and overload the server again
  3. Because HTTP requires it
  4. To measure ping

Why should rate limiting run before validation and simulation?

  1. Validation is optional
  2. So excess messages are dropped cheaply, before they cost parsing, checks or database work
  3. Rate limiting needs the parsed message
  4. It doesn't matter where it runs