Skip to Content
Examples

Doom

Play Doom in the browser, record it as a stream of inputs, then watch, rewind and fork the game. Streamsy projections replay the same inputs to publish a live scoreboard and the snapshots that make rewind cheap.

Streamsy Doom title in metallic red-orange lettering over a hellish landscape. Three glowing streams branch apart at the bottom.

This example runs Doom in your browser and records every game as a durable stream of key presses. Spectators can watch live, scrub backward to rewind, or fork any moment into a new timeline and play a different ending. Behind the scenes, server-side Streamsy projections replay those inputs to power a live HUD, build rewind snapshots, and keep the lobby up to date with Durable State.

Play it at doom.streamsy.dev. The streamsy-doom repository contains the full source under GPL-2.0-or-later.

I'm too young to die: Doom on streams

The idea comes from Electric's Doom on Durable Streams. Read their article for the gory details. This example rebuilds the demo from source on Streamsy, with no shared code, and extends it with Streamsy projections for live stats, server snapshots, and the lobby.

Concept diagram. The player's browser runs the Doom engine and appends each tic's input to an input stream. A watcher's browser reads the same stream and steps its own engine. The server replays the input stream and saves a snapshot of engine memory every ten minutes of play, which a watcher restores to rewind. A fork creates a new stream that shares history up to a chosen tic, and another player appends new inputs to it.

The game is its inputs

Doom runs in your browser as WebAssembly. The engine advances in fixed steps called tics, 35 per second. On each tic, it reads one small command from the player: move, turn, fire, and use.

Doom is deterministic. Start two copies of the engine from the same state, feed them the same commands in the same order, and both play out the same game. Monsters make the same choices, and shots land in the same places.

Because of that determinism, the player's browser sends neither video nor game state. Instead, it appends each tic's command to a Durable Stream, an append-only log that browsers read and write over HTTP. Each recorded frame takes nine bytes, so ten minutes of play takes about 190 KB.

Watching is replaying

A spectator's browser loads the same Doom engine and reads the same stream. It feeds each command into its own engine and plays out the exact same game. To watch live, the browser keeps reading as the player appends new batches. To watch a finished game, it reads from the start.

Every nine-byte frame includes one extra byte from the engine's random-number generator. Any replaying engine compares that byte against its own on every tic. If the two ever disagree, the replay has drifted from the original recording and the UI flags the game as unverified.

Rewind

Replaying from the first tic gets slower as a game grows longer. A snapshot of the engine's memory lets a watcher skip most of that replay. To jump to a moment in the game, the watcher's browser downloads the latest snapshot at or before that tic, loads it into the engine, and replays only the frames that came after it.

The original demo uploaded snapshots from the player's browser. In this example, the server creates every snapshot. A Streamsy projection follows the input stream, steps a headless WebAssembly copy of Doom on the server, and saves compressed engine memory every ten minutes of play. The player's browser only ever sends inputs.

A game shorter than ten minutes has no snapshot yet. Without a snapshot, rewind replays from tic 0.

Fork

Because a game is an append-only log, any tic in its history can start a new game. Forks are a first-class feature in Durable Streams and Streamsy. Creating a fork opens a new stream that shares the parent's stored bytes up to your chosen tic. The server copies nothing.

When you click Fork while watching, your browser loads the engine at that tic and starts appending your own commands to the forked stream. The original game continues untouched, and anyone can fork your fork later.

Hey, not too rough: Streamsy projections

In the original demo, the backend stores only raw bytes. It has no idea a game is happening inside them.

Streamsy adds projections. A projection is server code that follows a stream, runs work on each new batch, and writes the result. Streamsy saves the projection's progress as a checkpoint, so a restarted projection picks up where it left off.

The server plays along

This example runs a third copy of Doom on the server, with no screen and no audio. A projection follows each game's input stream and steps that headless engine through every recorded frame. After each tic, the projection reads live stats from engine memory: health, armor, ammo, kills, deaths, items, secrets, and the current map. It writes those updates to a per-game Durable State stream.

That same replay loop produces the rewind snapshots. Every 21,000 tics (ten minutes of play), it compresses the engine's memory and stores the snapshot in SQLite.

Both the stats and the snapshots are derived purely from the recorded inputs. The server does not trust the browser to report scores or upload snapshots, and the snapshot endpoints are read-only. That guarantee covers only the recording itself. The demo has no user accounts, so anyone can append to an active stream, and Verified checks only that the server's random-number bytes matched the player's on every tic for that engine build. It is not authentication, proof of human play, or a general anti-cheat guarantee.

Live HUD and lobby

Each game owns a Durable State stream that holds keyed rows for three collections: server-written session metadata, live stats, and presence. A reader loads a State snapshot first and then follows updates from that offset over a WebSocket when available. It folds those updates into local tables without querying the server database directly.

That per-game State stream powers two live views:

  • Per-game HUD. Both the Play page and the Watch page follow the game's State stream to render server-computed health, armor, ammo, level progress, verification, and replay lag in real time.
  • The lobby. A second projection folds each game's State stream into compact summaries and sends them to a private lobby stream. A third projection turns those summaries into the public lobby list. It keeps the 50 newest games ordered by server start time rather than skill. Deleting a game removes its row without backfilling an older game into the list.

In both views, Verified means the server's random-number byte matched the player's on every tic so far. Live turns on when frames arrive and switches off 30 seconds after the last input. Recordings and their snapshots expire 24 hours after creation.

Hurt me plenty: Cloudflare

The hosted demo runs on Cloudflare Workers and Durable Objects. A Durable Object is a single-threaded server with its own SQLite database. Cloudflare limits memory to 128 MB per isolate.

Putting every game and every headless Doom engine inside one Durable Object would exhaust that memory immediately. Instead, the example splits the work across three Durable Object classes:

ObjectOne for eachHoldsWhy it is split this way
DoomGamesFamily, meaning a game and all its forksBinary Sessions input streams and Batches manifestsA native fork shares stored bytes with its parent, so both must live in one object
DoomReplayGame or forkThe headless Doom engine, ReplayWake, the Game State stream, and snapshotsEach replay owns its engine and can recover it independently
DoomLobbyWhole sitePrivate Entries stream and public Leaderboard streamOne subscription serves the 50-game lobby list to every visitor

Browsers talk only to the Cloudflare Worker in front. The Worker uses a shared placement table to route stream requests to the right object, forwards snapshot and State-snapshot reads to DoomReplay or DoomLobby, and returns 404 for internal links and the private Entries stream.

Durable Objects do not call each other's TypeScript methods directly here. They talk through streams and internal links:

  1. When a player appends frames to DoomGames, a small wake projection appends a signal to that game's ReplayWake stream in DoomReplay.
  2. That wake triggers an alarm in DoomReplay. The replay projection reads the new frames from DoomGames, steps its headless engine, updates the local Game State stream, and writes a memory snapshot to its own SQLite database every ten minutes of play.
  3. A second projection in DoomReplay reads Game and sends compact summaries to Entries in DoomLobby.
  4. DoomLobby folds Entries into the public Leaderboard stream, which browsers follow over hibernatable WebSockets.

The same application also runs locally on Bun. On Bun, every projection attaches in one process with no cross-object wakes, browsers use long polling instead of WebSockets, and server snapshots live in a separate sibling SQLite file rather than inside the stream database.

Ultra-Violence: implementation details

Snippet paths are relative to the streamsy-doom repository. // ... marks omitted lines, and a snippet labelled "simplified" is rewritten to show the Streamsy calls without the surrounding bookkeeping.

1. Recording inputs and batch boundaries

Each session is a binary stream declared with Streamsy.bytes. It opens with a single JSON header line naming the engine build, WAD hash, and game settings. Nine-byte frames follow with no wrapper.

src/streams/declarations.ts
export class Sessions extends Streamsy.bytes<Sessions>()(
  "DoomV2/Sessions",
  "doom/v2/sessions/:id",
  { params },
) {}

During play, the browser flushes batches of five frames. It passes its last confirmed offset in Stream-Expected-Offset, so a stale or competing writer fails instead of interleaving frames.

src/streams/session-writer.ts
// SessionWriter.append (simplified)
const before = this.offset;
const response = await this.client.append(sessionPath(id), concat(frames), BINARY, {
  "Stream-Expected-Offset": before,
});
this.offset = offsetOf(response);

const batch = {
  startTic: this.tic,
  endTic: this.tic + frames.length,
  before,
  after: this.offset,
};
await this.client.append(batchPath(id), JSON.stringify([{ batch }]), JSON_CONTENT);

Stream offsets are opaque strings, and binary HTTP reads concatenate stored messages. A browser cannot calculate a mid-stream offset from a tic count. After each frame append, SessionWriter records { startTic, endTic, before, after } in a companion JSON stream called Batches.

Frame appends and manifest appends are separate HTTP requests, not one transaction. If a browser disconnects between them, the last frames remain playable, but the manifest lacks that final boundary.

2. Native forks inside a batch

To fork a game, the browser reads the parent's Batches manifest and finds the boundary at or just before the chosen tic. If the tic falls inside a five-frame batch, the browser sends the offset before that batch and asks the server to keep (tic - batch.startTic) * 9 bytes from inside it.

src/streams/session-fork.ts
// forkSession (simplified)
const batchContainingTic = batches.find((b) => b.startTic < tic && tic < b.endTic);
const forkOffset = batchContainingTic?.before ?? offsetAtBatchBoundary;

const headers: Record<string, string> = {
  "Stream-Forked-From": `/${sessionPath(parentId)}`,
  "Stream-Fork-Offset": forkOffset,
};
if (batchContainingTic) {
  headers["Stream-Fork-Sub-Offset"] = String((tic - batchContainingTic.startTic) * FRAME_BYTES);
}

const row = await bootstrapOnServer(client, id, {
  ...parent,
  playerName,
  forkedFrom: parentId,
  forkTic: tic,
});
const created = await client.create(sessionPath(id), "", { headers });

The server shares the parent's stored bytes up to that point without copying them. Because a protocol fork inherits the parent's binary header line verbatim, the server-written Game session row created by bootstrapOnServer is the authoritative record of forkedFrom and forkTic.

Snapshots are not shared across forks. The child's DoomReplay object replays the inherited prefix and writes its own snapshots in its own SQLite table.

3. Routing streams and linking Durable Objects

Placement.byRoute maps every stream path to its owner name. Native forks require the parent and child in the same owner, so every session in a family shares game:<family> while each replay gets replay:<id>.

apps/host-cloudflare/topology.ts
export const placement = Placement.byRoute([
  rule({ stream: Sessions, owner: gameObjectOf }),
  rule({ stream: Batches, owner: gameObjectOf }),
  rule({ stream: ReplayWake, owner: replayObjectOf }),
  rule({ stream: Game, owner: replayObjectOf }),
  rule({ stream: Leaderboard, owner: lobbyObject }),
  rule({ stream: Entries, owner: lobbyObject }),
]);

The Worker in apps/host-cloudflare/edge.ts and the internal links both use this table, so public requests and projections always agree on where a stream lives.

Three ObjectLink definitions grant narrow cross-object permissions:

apps/host-cloudflare/topology.ts
export const framesLink = ObjectLink.make({
  group: Streamsy.group(Sessions),
  prefix: "/__frames",
  placement,
  access: "read",
});
export const wakeLink = ObjectLink.make({
  group: Streamsy.group(ReplayWake),
  prefix: "/__wake",
  placement,
  access: "append",
});
export const entriesLink = ObjectLink.make({
  group: Streamsy.group(Entries),
  prefix: "/__entries",
  placement,
  access: "append",
});

Every internal link uses a /__ prefix. The Worker rejects any public request to /__* with 404, so only Durable Object stubs can reach them.

A commit in DoomGames cannot wake a projection in DoomReplay directly. Instead, DoomGames attaches frameWake (Projection.wake in src/projection/frame-wake.ts) with concurrency 8. Up to eight sibling forks in the same family can wake their replay objects in parallel.

apps/host-cloudflare/games-object.ts
export const gamesHost = (concurrency = SIBLING_REPLAYS_WOKEN_CONCURRENTLY) =>
  StreamsyObject.make<Env, Layer.Success<ReturnType<typeof gamesLayer>>, ReplayWake>({
    app: Layer.merge(publicFrameAndManifestStreams, framesLink.routes),
    layer: gamesLayer,
    links: (env) => [wakeLink.client(env.REPLAYS)],
    wakeups: [ProjectionWakeup.attach(frameWake, { concurrency })],
  });

On the receiving side, DoomReplay (apps/host-cloudflare/replay-object.ts and apps/host-cloudflare/replay-host.ts) stores its session ID during bootstrap so it can rebuild its local wake trigger after eviction. It reads frames over framesLink, writes summaries over entriesLink, and attaches replayStats, replayIdle, and lobbyEntry.

4. Transactional replay, snapshots, and cold recovery

The replay projection (doom-v2-replay, built by makeReplayStats) reads pages of bytes from Sessions, steps the headless Doom engine, writes snapshots every 21,000 tics, and upserts rows into the local Game State stream.

src/projection/replay/projection.ts
// makeReplayStats (simplified)
export function makeReplayStats({ snapshotInterval = SNAPSHOT_INTERVAL } = {}) {
  return Projection.mapAccumBatch({
    id: "doom-v2-replay",
    params: { id: SessionId },
    inputs: { frames: Sessions },
    outputs: { game: Game },
    commit: Commit.transaction,
    state: { schema: ReplayState, initial: initialReplayState },
    mapAccumBatch: (state, batch, unit) =>
      Effect.gen(function* () {
        // ...
        const engine = yield* engineAtCheckpoint(id, { ...state, header: decoded.header });
        // ...
        const replayed = yield* Effect.promise(() =>
          replayDecoded(state, decoded, engine, id, {
            intervalTics: snapshotInterval,
            writeAfter: writeSnapshotWithResumePoint,
          }),
        );
        const statsRows = replayed.rows.map((row) => DurableState.upsert("stats", row));
        return [replayed.state, { game: statsRows }] as const;
      }),
  });
}

The projection uses Commit.transaction instead of Commit.producer, because its output stream (Game) lives in the same DoomReplay object as its checkpoint. On Cloudflare, server_snapshots lives in that same Durable Object SQLite database too. The snapshot write, the Game stats append, and the projection checkpoint commit inside one SQLite transaction, so a failure rolls all three back together.

On Bun (apps/host-bun/runtime.ts), snapshot writes do not share that transaction. Bun stores snapshots in a separate sibling .snapshots.sqlite file keyed by (id, tic) to avoid write-lock contention on the stream database, and INSERT OR IGNORE keeps retries idempotent.

Each snapshot is a gzipped envelope with a JSON identity line followed by the engine's 16 MiB heap XORed against its memory just after start-up. compressSnapshot in engine/src/snapshot.ts streams that XOR in 64 KiB chunks into CompressionStream("gzip") so it never allocates a second full delta buffer. A shareware snapshot compresses to about 600 KB. If a snapshot exceeds the 2,000,000-byte limit (MAX_SNAPSHOT_BYTES in src/storage/snapshot-table.ts), the projection skips that snapshot so stats and checkpoints keep moving.

Along with the compressed bytes, each snapshot row stores resume_offset and resume_frames for the unread tail of the input page. When DoomReplay starts cold or loses its cached engine, engineAtCheckpoint restores the newest unexpired snapshot at or before the checkpoint tic and resumes from that cursor instead of replaying from tic 0.

src/projection/replay/engine-recovery.ts
// engineAtCheckpoint (simplified)
const snapshot = (yield * SnapshotTable).latest(id, state.tic);
if (snapshot) yield * Effect.sync(() => restoreSnapshot(engine, snapshot));

const replay = replayerUpTo(state.tic, engine, header, snapshot);
if (snapshot?.resume) replay([snapshot.resume.frames]);
if (engine.tic < state.tic) {
  const readFrom = snapshot?.resume ? { offset: snapshot.resume.offset } : undefined;
  yield *
    (yield * Sessions).read({ id }, readFrom).pipe(
      Stream.takeUntil(() => engine.tic >= state.tic),
      Stream.runForEach((batch) => Effect.sync(() => replay(batch.items))),
    );
}

A companion projection, replayIdle (src/projection/replay/idle.ts), keeps wall-clock time out of the deterministic replay loop. When new frames arrive, replayIdle marks live: true in Game and schedules Projection.wakeAt for 30 seconds later. Once 30 seconds pass with no new frames and doom-v2-replay has settled on the same input offset, replayIdle writes live: false and releases the cached engine from memory. If Sessions expires, replayIdle deletes the game's snapshot rows.

Browsers read snapshots through two read-only endpoints handled by src/server/snapshot-routes.ts (any method other than GET or HEAD returns 405):

RouteReturns
/doom/v2/server-snapshots/:idUncached JSON [{ tic, size }] listing unexpired snapshots
/doom/v2/server-snapshots/:id/:ticGzip snapshot bytes, cached as immutable until row expiry

When a watcher seeks, SessionReader.seek (src/streams/session-reader.ts) fetches the latest snapshot at or before the target tic, validates its size, tic, and engine identity, restores it, and steps the remaining frames.

5. Per-game state, the bounded leaderboard, and live reading

Session metadata, per-game stats, and lobby entries live in three Durable State streams:

src/streams/declarations.ts
export class Game extends Streamsy.state<Game>()("DoomV2/Game", "doom/v2/games/:id", {
  params,
  collections: {
    stats: { schema: StatsRowSchema, key: "id" },
    presence: { schema: PresenceRowSchema, key: "id" },
    session: { schema: SessionRowSchema, key: "id" },
  },
}) {}

export class Entries extends Streamsy.state<Entries>()("DoomV2/Entries", "doom/v2/entries", {
  params: {},
  collections: { entry: { schema: EntryRowSchema, key: "id" } },
}) {}

export class Leaderboard extends Streamsy.state<Leaderboard>()(
  "DoomV2/Leaderboard",
  "doom/v2/leaderboard",
  {
    params: {},
    collections: { game: { schema: EntryRowSchema, key: "id" } },
  },
) {}

Game and Leaderboard are publicly read-only, and Entries is hidden from public routes. Only the server writes to Game (through replay projections and the POST /doom/v2/bootstrap/:id, end, and delete endpoints), so browsers cannot write these rows directly. Because routes are unauthenticated, any caller with a session ID can still call end or delete.

Two projections connect per-game state to the lobby:

  1. lobbyEntry (src/projection/lobby-entry.ts) runs inside DoomReplay with Commit.producer and exponential backoff capped at 30 seconds. It folds Game events into one summary row and appends it to Entries over entriesLink. Session changes, presence changes, and the first score publish immediately. Routine score updates coalesce to five-second (175-tic) intervals so busy games do not flood DoomLobby. When Game expires, lobbyEntry removes the entry.
  2. leaderboard (src/projection/leaderboard.ts) runs inside DoomLobby with Commit.transaction. It syncs EntriesTable and LeaderboardTable, sorts candidates by server createdAt descending and then by id, and writes only the changes needed to keep the newest 50 rows in Leaderboard. Deleted entries are removed without scanning older games to backfill.

Browsers never fold a State stream from the beginning of time. Both followLeaderboard (apps/web/lobby-screen.ts) and GameHud (apps/web/hud.ts) call followState (src/streams/live.ts):

apps/web/lobby-screen.ts
// followLeaderboard (simplified)
const entries = new StateRows<EntryRow>("game");
void followState<StateEvent<EntryRow>>(client, {
  snapshot: leaderboardStateSnapshotPath,
  stream: leaderboardStatePath,
  signal,
  onBatch: (events) => {
    entries.apply(events);
    renderLeaderboard([...entries.rows.values()]);
  },
});

followState first calls a GET snapshot route (/doom/v2/state-snapshot/leaderboard or /doom/v2/state-snapshot/games/:id). The server reads the synced State table in one transaction and returns the current rows alongside Stream-Next-Offset. followState then passes that offset to followJson, which opens a hibernatable WebSocket to DoomLobby or DoomReplay (live: { websocket: true }) and falls back to long polling if WebSockets are unavailable.

Stream expiry

Sessions, Batches, ReplayWake, and Game expire at a fixed deadline 24 hours after creation. Reads do not extend that deadline. A fork receives its own 24-hour clock when created, and snapshot rows copy ReplayWake's deadline so snapshots expire with the game.

Entries and Leaderboard have no expiry. When a game expires, lobbyEntry removes its row, while the underlying State logs continue to grow until Streamsy adds State log trimming.

On this page