DEV Community

Cover image for Deterministic 60 Hz Replay Verification for a No-Login Browser Game Leaderboard
Dev32
Dev32

Posted on

Deterministic 60 Hz Replay Verification for a No-Login Browser Game Leaderboard

When you build a browser game leaderboard without user accounts, you immediately hit an awkward constraint: you cannot rely on account reputation, and you obviously cannot trust POST /score { score: 9999 }.

For our ZigZag Country Challenge — a Three.js one-tap endless runner adapted from Michael Kolesidis's open-source ZigZag (AGPL-3.0-or-later) — we wanted players to open the page, play immediately, and compete for their country's all-time single-run record with zero signup and zero nickname prompt. Cloudflare gives us the player's region via request.cf.country; the hard part was verifying that a submitted score actually happened under the game's rules.

I wrote a higher-level product and design walkthrough of the scoring overhaul in our ZigZag Country Challenge devlog. In this post, I want to focus strictly on the engineering mechanics: how we share a deterministic 60 Hz integer simulation between Three.js and Cloudflare Durable Objects, how we avoid burning server CPU on non-record runs, how we handle offline retries idempotently, and the Cloudflare browser cache bug that surprised us on launch day.


1. Zero Floats in the Simulation Core

The first rule of server-side replay verification is that the browser and the server must execute the exact same simulation — regardless of whether the player is on a 30 FPS mobile battery-saver screen, a 60 Hz laptop, or a 144 Hz desktop monitor.

Instead of running physics inside requestAnimationFrame with variable deltaTime floats, we split the game into two strict layers:

  1. core/rules.mjs: pure simulation logic with zero DOM, audio, clock, or localStorage access.
  2. game/scene.mjs + game/main.mjs: Three.js rendering and a fixed-timestep accumulator that steps core/rules.mjs at exactly HZ = 60.

To eliminate floating-point drift across engines and platforms, every position, tile width, and velocity in core/rules.mjs is scaled into safe JavaScript integers:

export const RULE_VERSION = 'zigzag-country-v1';
export const HZ = 60;
export const SCALE = 3_600_000;
export const TILE = 4_860_000;
export const HALF = TILE / 2;
export const START_SPEED = 345_000;
export const MAX_TICKS = HZ * 60 * 120; // 2-hour hard cap
export const MAX_TURNS = 60_000;

function random(s) {
  s.rng = (s.rng + 0x6d2b79f5) >>> 0;
  let t = s.rng;
  t = Math.imul(t ^ (t >>> 15), t | 1);
  t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
  return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
}
Enter fullscreen mode Exit fullscreen mode

When a player starts a ranked run, the server issues a runId (UUID) and a random 32-bit seed via crypto.getRandomValues(new Uint32Array(1))[0]. Both browser and server initialize createGame(seed) with the same Mulberry32-based generator, producing the exact same path tiles and gem placements.

Each tick is deterministic integer arithmetic:

export function step(s, turn = false) {
  if (!s.alive) throw Error('run_already_ended');
  if (s.tick >= MAX_TICKS) throw Error('run_limit');
  if (turn) s.direction ^= 1;
  if (s.direction) s.x += s.speed;
  else s.z -= s.speed;

  s.speed = Math.min(600_000, s.speed + 12);
  generateAhead(s);
  // ... check tile support, mark newly visited tiles (+1), check gem pickup (+1)
  s.tick++;
  s.alive = support;
  return s;
}
Enter fullscreen mode Exit fullscreen mode

On the client side, main.mjs feeds display frames into a capped fixed-timestep loop (delta = Math.min(0.25, ...)):

function frame(time) {
  const delta = Math.min(0.25, (time - previous) / 1000);
  previous = time;
  if (phase === 'playing') {
    accumulator += delta;
    while (accumulator >= 1 / HZ && phase === 'playing') {
      if (queuedTurn) {
        turns.push(game.tick);
        playSound('tap');
      }
      step(game, queuedTurn);
      queuedTurn = false;
      accumulator -= 1 / HZ;
      if (!game.alive || game.tick === MAX_TICKS) finish();
    }
  }
  scene.render(game, fallSeconds);
  requestAnimationFrame(frame);
}
Enter fullscreen mode Exit fullscreen mode

A 30 FPS screen steps twice per rendered frame; a 144 Hz screen renders interpolated frames and steps when the accumulator crosses 1 / 60 s. Both produce the exact same turns tick indices for the same run.


2. Compressing an Entire Run Into an Integer Array

Because ZigZag is a one-tap game (every input toggles direction 0 ↔ 1), we never stream positions or open WebSockets. The browser only talks to the API twice per run: POST /api/country/runs/start and POST /api/country/runs/finish.

The finish payload is just five fields:

{
  "runId": "f47ac10b-58cc-4372-a567-0e02b2c3d479",
  "version": "zigzag-country-v1",
  "score": 142,
  "ticks": 2814,
  "turns": [112, 168, 205, 241]
}
Enter fullscreen mode Exit fullscreen mode

Before replaying a single tick, validateTrace() rejects malformed shapes, wrong rule versions, out-of-range scores/ticks, and non-monotonic turn arrays:

export function replay(seed, trace) {
  validateTrace(trace);
  const s = createGame(seed);
  let cursor = 0;
  for (let tick = 0; tick < trace.ticks; tick++) {
    const turn = trace.turns[cursor] === tick;
    if (turn) cursor++;
    step(s, turn);
    if (!s.alive && s.tick !== trace.ticks) throw Error('continued_after_death');
  }
  if (s.alive && s.tick !== MAX_TICKS) throw Error('unfinished_run');
  if (s.score !== trace.score) throw Error('score_mismatch');
  return { score: s.score, ticks: s.tick, tiles: s.tiles, gems: s.gems, capped: s.alive };
}
Enter fullscreen mode Exit fullscreen mode

If someone edits their score in DevTools, truncates the trace before falling off, or appends taps after death, replay() throws immediately.


3. Keeping Verification Cheap Inside a Cloudflare Durable Object

Running replay verification on Cloudflare Workers has two operational constraints: CPU budgets and abuse surface. To keep both under control without requiring login, the Worker mints an HttpOnly; SameSite=Strict HMAC-SHA256 session cookie (sgb_run), enforces IP rate limits and a daily admission counter, and routes each anonymous session to its own SQLite-backed RunSession Durable Object.

Inside RunSession.finish(), four guards run before replay():

  1. Wall-clock fast-forward check: A player can pause or run slow, so wall time can exceed game time, but a 60-second run cannot finish in 5 seconds:
   if (Date.now() - row.issued + 500 < (trace.ticks * 1000) / HZ) {
     throw new ApiError('run_too_fast');
   }
Enter fullscreen mode Exit fullscreen mode
  1. Threshold short-circuit: We fetch the country's current best from the database. If trace.score <= best, we do not run replay() at all — we store and return { status: 'not_improved', verified: false }. That skips simulation work on the vast majority of casual runs without ever claiming an unverified score was verified.
  2. One verification attempt per runId: If replay() throws, we persist { status: 'rejected', reason } against that runId. An attacker cannot keep tweaking inputs against the same issued seed to probe edge cases.
  3. Payload hash lock: Every finish call hashes the normalized trace. Resending the same runId with altered turns or score returns 409 run_payload_conflict.

4. Two-Phase Idempotency for Flaky Connections

Mobile connections drop right at game over. The nastiest edge case is when the server verifies and commits a new country record, but the HTTP response never reaches the browser. From the browser's perspective, the submission failed; if the player hits "Retry", the server must return the original confirmation rather than rejecting the runId as already used or inserting a duplicate receipt.

In RunSession, verification and database settlement are split into two persisted checkpoints in Durable Object SQLite:

if (!row.proof) {
  // 1. Verify once and persist proof inside DO SQLite
  const proof = replay(row.seed, trace);
  this.ctx.storage.sql.exec(
    'UPDATE runs SET hash=?, proof=? WHERE id=?',
    hash, JSON.stringify(proof), row.id
  );
}

// 2. Settle atomically in PostgreSQL (idempotent by run_id)
try {
  receipt = await settle(this.env, row.id, hash, row.country, trace.score);
} catch (error) {
  this.ctx.storage.sql.exec('UPDATE runs SET retry_at=? WHERE id=?', Date.now() + 2000, row.id);
  throw error;
}

const result = { status: 'confirmed', verified: true, ...receipt };
this.ctx.storage.sql.exec('UPDATE runs SET result=? WHERE id=?', JSON.stringify(result), row.id);
return result;
Enter fullscreen mode Exit fullscreen mode
  • If row.result already exists on retry, the Durable Object returns the exact stored JSON immediately.
  • If row.proof exists but settle() failed on a transient database timeout, retry skips replay() and only re-runs the idempotent PostgreSQL RPC after a 2-second backoff (retry_at).
  • On the browser side, finished traces sit in a localStorage queue (capped at 8 pending runs) and automatically retry on page reload or the online event. A Durable Object alarm() purges expired run rows after 24 hours so storage stays bounded.

5. The Launch-Day Bug: Cloudflare's 4-Hour Browser Cache TTL

Everything passed automated concurrency, idempotency, and RLS tests. Then during launch verification, we posted a temporary test record, rolled the database back, and loaded the homepage — and the old test leader was still sitting there.

The database was clean and our Worker cache was only 60 seconds. The culprit was our domain-level Cloudflare Browser Cache TTL (4 hours): because our Worker cached the leaderboard response with Cache-Control: public, max-age=60 and returned it directly, the browser was allowed to hold onto stale JSON far longer than the Worker itself.

The fix was a tiny wrapper in server/worker.ts that separates Worker edge caching from browser caching:

function browserBoard(response: Response) {
  // Keep the 60s cache inside Worker caches.default,
  // but never let the browser store leaderboard JSON.
  const headers = new Headers(response.headers);
  headers.set('Cache-Control', 'no-store');
  return new Response(response.body, { status: response.status, headers });
}
Enter fullscreen mode Exit fullscreen mode

Inside fetch(), the Worker stores the public, max-age=60 clone in caches.default (and invalidates it via caches.default.delete() whenever a finish call succeeds), while every client receives Cache-Control: no-store.


Honest Limitations

Server-side replay verification is a strong upgrade over trusting client scores, but it is worth being explicit about what it does not solve:

  • It proves that a sequence of turn ticks produces the claimed score under the issued seed and rule version, within plausible wall-clock time.
  • It does not prove a human pressed the button — a bot that reads the path and plays strictly within the rules still generates a valid trace.
  • Because we deliberately avoided accounts and relied on request.cf.country, a VPN user can play under another country's flag.

For a lightweight, zero-friction browser arcade challenge, that tradeoff felt right: casual memory editing and forged curl requests are eliminated without adding login walls or heavyweight anti-cheat SDKs.

If you want to inspect the complete core/rules.mjs, Durable Object session.ts, SQL migrations, and test suite, the full AGPL-3.0 source bundle is downloadable from our ZigZag source & license page, and you can test a run directly on ZigZag Country Challenge.

Top comments (0)