A multiplayer race needs a scoreboard that updates every second. The obvious way to build that is a game server with a tick loop, presence heartbeats, and per-keystroke streaming. NinjaType's multiplayer typing race has none of that. It runs on Cloudflare Workers Free, in front of a fully static Astro site, with no accounts and no keystroke uploads — and the standings still update about once a second.

This post is about the pieces that made that possible: WebSocket hibernation with state in socket attachments, report-driven broadcasts instead of a server tick, an admissions pipeline built on Turnstile receipts, and a room directory that fits in ~480 KV writes a day. The whole backend lives in workers/multiplayer/ — about 1,200 lines including tests.

The shape of the system

The Astro site stays static on Cloudflare Pages. A service binding points Pages at the Worker; a Pages Function forwards only /api/multiplayer/*, and _routes.json keeps every other request on static asset serving — practice traffic never touches dynamic compute. (Custom-domain requests use Worker routes directly and skip the forward hop.)

Inside the Worker there are exactly two Durable Objects, both on the SQLite storage class:

  • Room — one object per room. Owns race state, the WebSocket server end, and the alarm that fires deadlines.
  • Directory — one global object for room discovery: a SQLite table plus one batched KV snapshot.
Browser ──WS──▶ Room DO (per room) ──▶ Directory DO (global) │ ▲ storage: SQLite ▲ SQL rows + KV snapshot (3 min) └── progress ────┘ └──▶ KV (public room list) 

Hibernation instead of a game loop

Room sockets use hibernation: ctx.acceptWebSocket(server) and the runtime wakes the DO only when a message arrives, a socket closes, or the alarm fires. Between messages, the object doesn't bill duration or hold memory. Everything "live" lives in socket attachments — small per-connection objects that the runtime persists across hibernation:

interface Attachment { id: string; epoch: string; window: number; commands: number; syncs: number; controls?: number; chats?: number; progress?: { roundId: string; correctChars: number; updatedAt: number }; standingsBroadcast?: { roundId: string; at: number }; } 

That interface is the whole trick. Live typing progress and broadcast timestamps sit in attachments, never in room state and never in storage or KV. Authoritative state is written once per real transition (join, start, finish), and a single storage alarm covers every future deadline — countdown end, score collection, rematch window, room expiry. There is no interval running anywhere.

Report-driven broadcasts

Clients don't stream keystrokes. Each racer uploads exactly one number — the current correct-character count — and even that is throttled to once per aligned one-second window, computed from round start:

const window = Math.floor((now - round.startAt) / PROGRESS_MS); // PROGRESS_MS = 1_000 if (a.progress?.roundId === round.id && Math.floor((a.progress.updatedAt - round.startAt) / PROGRESS_MS) >= window) return; 

Unchanged counts are included on purpose, so pauses show up in each player's WPM trend instead of the curve silently flattening.

And instead of a timer fanning out standings every second per room, an incoming report is the trigger. When a report lands in a window that hasn't been published yet, the room sends one compact standings broadcast to everyone:

const lastBroadcast = Math.max(0, ...this.ctx.getWebSockets().map(socket => { const attached = socket.deserializeAttachment() as Attachment; return attached.standingsBroadcast?.roundId === round.id ? attached.standingsBroadcast.at : 0; })); a.progress = { roundId: round.id, correctChars: command.correctChars, updatedAt: now }; const publish = lastBroadcast === 0 || Math.floor((lastBroadcast - round.startAt) / PROGRESS_MS) < window; ws.serializeAttachment(a); if (publish) { /* one standings message to every socket */ } 

The cost of that design: the first broadcast in a window can carry slightly older reports from other players, so the live panel is approximate — final scores replace estimates when the race ends. Worst case is a handful of messages per second per room, with zero scheduled work keeping rooms alive.

What the server will — and won't — trust

No keystroke streaming means the server can't prove human typing, so it doesn't pretend to. The trust model is drawn explicitly:

  • Progress reports are bounded (0 ≤ correctChars ≤ text.length, safe integers) but never select a winner or populate final metrics.
  • Time mode races end at the deadline; the server recomputes displayed metrics from one final text/count payload, bounded at 16,384 characters.
  • Words mode ends on the first server-accepted completion.
  • Tie-breaks use accuracy, then a stable participant ID; zero input produces no winner.

Server-side passage generation closes the "the text ran out" loophole. Time mode generates one shared passage sized above the accepted 1,000-WPM pace:

const target = Math.ceil(duration / 60 * 5000) + 20; // chars at 1,000 WPM + buffer 

It's sent once in the round snapshot — no mid-race text fetches — and the client renders at most 60 nearby words as the cursor advances, so a 25,000-character passage costs nothing to display.

Admissions: Turnstile plus single-use receipts

Room creation and every socket entry — creator included, reconnects included — require a fresh Turnstile challenge. Siteverify gets an idempotency key derived from the operation, so a cached verification can't be replayed into a different room:

const digest = await hash(`${action}:${name}:${token}`); const key = `${digest.slice(0, 8)}-${digest.slice(8, 12)}-4${digest.slice(13, 16)}-a${digest.slice(17, 20)}-${digest.slice(20, 32)}`; 

A successful check returns a receipt { hash, kind, until, epoch, fingerprint }, persisted with the room and valid for five minutes. Replaying the same challenge hash returns 409 token_reused instead of a second room or connection — which also neutralizes cached Siteverify retries. The timestamp from Cloudflare must be fresh (−30s to +300s), the hostname must equal the origin's hostname, and the action must match. Cloudflare's public test keys are only accepted when both the request URL and browser origin are loopback and the exact test keys are configured — so "always-pass" keys can never admit production rooms.

One detail I like: closed rooms keep only their receipts until the five-minute retry window expires, then deleteAll() clears storage. The tombstone deliberately preserves replay protection even after everything else is gone.

Rate limiting without a rate limiter

Per-socket limits also live in attachments, on a rolling ten-second window: hard cap of 30 messages (exceeding it closes the socket), 10 control commands, 2 syncs, 2 chat messages. Progress has its own aligned-window throttle on top. No shared rate-limiter service, no KV counters — the attachment resets itself whenever the window rolls.

The directory: SQL rows, one KV snapshot

Discovery is a single global DO with a SQLite table, plus one batched publication to KV every three minutes (~480 writes/day — comfortably inside Free-tier limits):

this.ctx.storage.sql.exec('DELETE FROM rooms WHERE expiresAt <= ?', Date.now()); const rooms = this.ctx.storage.sql.exec('SELECT name, epoch, createdAt, expiresAt, maxPlayers FROM rooms ORDER BY createdAt DESC').toArray(); await this.env.ROOM_DIRECTORY.put('public-v1', JSON.stringify({ publishedAt: Date.now(), rooms }), { expirationTtl: 600 }); 

Listings are hints, not truth: joining always validates live room existence, epoch, and capacity against the Room DO. Registration is an upsert guarded by createdAt, so a stale registration can't overwrite a newer epoch of the same room.

Fail closed, tell the truth

The rule I'm proudest of is in persist(): if storage or the alarm write fails, the room closes every socket with 1011 Multiplayer unavailable and stops acknowledging anything — it will never confirm an in-memory transition it couldn't save:

catch (error) { // Never acknowledge an in-memory transition after storage/alarm failure. this.unavailable = true; for (const ws of this.ctx.getWebSockets()) { try { ws.close(1011, 'Multiplayer unavailable; keep practicing'); } catch { /* Already closed. */ } } throw error; } 

The client-side counterpart: Quick race runs entirely in the browser with the same deterministic engine — seeded bots pacing 40–85 WPM in bursts with randomized pauses — and falls back to local practice whenever config, admission, or reconnection fails. Multiplayer being down degrades to "you can still practice," never to a broken screen.

What it can't do

Honest limits: the server can't distinguish a fast human from a script without keystroke streaming (it bounds and validates, but proof isn't on the menu); the single-directory KV snapshot needs partitioning before the room count gets large; and Free-tier request/storage quotas bound total capacity — Turnstile and throttling reduce abuse, they don't lift quotas. Reconnects also always require a fresh challenge, by design: a stale tab can't silently reattach.

Try the result at the multiplayer typing race — or race your own saved pace in Ghost Race. NinjaType is free, and the source is on GitHub, including the Room/Directory objects and the engine tests.

What would you trade for hibernation in your next real-time feature — eventual consistency in the live panel, or a challenge on every reconnect?

Disclosure: I'm NinjaType's creator.