Run your actors in a Durable Object

One Durable Object can hold a tinyactors host with thousands of actors, on @tinyactors/wasm. Idle actors hibernate into the object's SQLite storage, and a snapshot brings every actor back after an eviction.

Import the module, then compile the chart

A Worker cannot compile WebAssembly from bytes at run time, so it imports tinyactors.wasm and hands the module to init(). Then it compiles the chart once and sends every order's request to the shop's one object:

worker.mjsjavascript
// The Worker: compiles the order chart once per isolate and sends every
// request under /orders/ to the shop's one Durable Object.
import wasm from '@tinyactors/wasm/tinyactors.wasm';
import { init, compileCharts } from '@tinyactors/wasm/init';
import order from './order.scxml';
import { shop } from './shop.mjs';

await init(wasm); // workerd compiles a module it imports, never bytes at run time
const compiled = compileCharts([{ name: 'order.scxml', text: order }]);
const image = compiled.image;
compiled.close();

export const Shop = shop(image, { resident: 1000 });

export default {
  async fetch(request, env) {
    if (!new URL(request.url).pathname.startsWith('/orders/')) return new Response('not found', { status: 404 });
    return env.SHOP.get(env.SHOP.idFromName('shop')).fetch(request);
  },
};

The config binds the object with SQLite storage and imports .scxml files as text:

wrangler.jsoncjson
{
  "name": "shop",
  "main": "worker.mjs",
  "compatibility_date": "2026-09-01",
  // @tinyactors/wasm 0.4.0 reads import.meta.url when it is imported,
  // which a Worker's bundle leaves undefined
  "define": { "import.meta.url": "\"https://worker.invalid/\"" },
  "rules": [{ "type": "Text", "globs": ["**/*.scxml"], "fallthrough": true }],
  "durable_objects": { "bindings": [{ "name": "SHOP", "class_name": "Shop" }] },
  "migrations": [{ "tag": "v1", "new_sqlite_classes": ["Shop"] }]
}
  • init(wasm)takes the module wrangler compiled from the import, in place of fetching it. Compiling the bytes in the Worker fails with "Wasm code generation disallowed by embedder".
  • The definegives import.meta.url a value. @tinyactors/wasm 0.4.0 reads it when it is imported, and without it the Worker stops at start with "TypeError: Invalid URL string."
  • datamodel: 'quickjs'in shop.mjs, below. A Worker refuses to evaluate strings, which the native ECMAScript datamodel needs, so the charts run in quickjs, which is inside the same module.

Keep every order in one object

One object per shop, not per order, keeps the shop's actors in one host, where they send each other events with no request between objects.

Each order of the shop is an actor of this chart. After checkout it waits 15 minutes for the payment, then expires. Nothing else in it knows about Cloudflare:

order.scxml
<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
       datamodel="ecmascript" name="order" initial="cart">
  <datamodel>
    <data id="items" expr="[]"/>
  </datamodel>
  <state id="cart">
    <transition event="add">
      <assign location="items" expr="items.concat([_event.data])"/>
    </transition>
    <transition event="checkout" cond="items.length &gt; 0" target="awaiting_payment"/>
  </state>
  <state id="awaiting_payment">
    <onentry><send id="timeout" event="expire" delay="900s"/></onentry>
    <transition event="paid" target="paid"/>
    <transition event="expire" target="expired"/>
  </state>
  <state id="paid"/>
  <state id="expired"/>
</scxml>

The object holds one host, finds an order by its name and spawns it on its first event. After each request it writes the host to its storage:

shop.mjsjavascript
// A Durable Object that holds one tinyactors host: each order of the shop
// is an actor in it, found by its name. Orders past `resident` hibernate
// into the object's SQLite storage. After each request the host's
// snapshot and the blobs written since the last one are committed in one
// transaction, so the next instance of the object, after an eviction or
// a deploy, goes on where this one stopped. Timers run on the object's
// alarm.
import { Host, SimulatedClock, StaleError } from '@tinyactors/wasm/init';

const PART = 1 << 20; // a row of an object's SQLite holds at most 8 MB: the snapshot goes in parts of 1 MiB

export function shop(charts, { resident }) {
  return class Shop {
    constructor(ctx) {
      this.ctx = ctx;
      this.sql = ctx.storage.sql;
      this.pending = new Map(); // session -> blob, or null for a delete, until the commit
      this.queue = Promise.resolve();
      ctx.blockConcurrencyWhile(async () => this.open());
    }

    // The host from the last commit, or a new one.
    open() {
      this.sql.exec('CREATE TABLE IF NOT EXISTS blobs (session TEXT PRIMARY KEY, blob BLOB)');
      this.sql.exec('CREATE TABLE IF NOT EXISTS snapshot (part INTEGER PRIMARY KEY, bytes BLOB)');
      this.sql.exec('CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value)');
      // The host's clock moves while the object runs: serially() steps it
      // to the wall clock at each request and alarm.
      this.clock = new SimulatedClock();
      const options = { system: 'shop', datamodel: 'quickjs', clock: this.clock, store: this.store(), resident };
      const parts = this.sql.exec('SELECT bytes FROM snapshot ORDER BY part').toArray();
      if (parts.length === 0) {
        this.host = new Host(charts, options);
        this.wall = Date.now();
      } else {
        this.host = Host.restore(join(parts.map((row) => new Uint8Array(row.bytes))), charts, options);
        this.wall = this.sql.exec("SELECT value FROM meta WHERE key = 'wall'").one().value;
      }
    }

    // The host's store: writes wait in `pending` for the commit, so the
    // blobs and the snapshot that names them land together.
    store() {
      const { sql, pending } = this;
      return {
        save: (session, blob) => { pending.set(String(session), blob.slice()); },
        load: (session) => {
          const key = String(session);
          if (pending.has(key)) return pending.get(key);
          return new Uint8Array(sql.exec('SELECT blob FROM blobs WHERE session = ?', key).one().blob);
        },
        delete: (session) => { pending.set(String(session), null); },
      };
    }

    // POST /orders/<name>/<event> with JSON data sends the event, spawning
    // the order on its first event; GET /orders/<name> reads it.
    async fetch(request) {
      return this.serially(async () => {
        const [, , name, event] = new URL(request.url).pathname.split('/');
        let order;
        try {
          order = this.host.actor(name);
        } catch (error) {
          if (!(error instanceof StaleError)) throw error;
          if (request.method !== 'POST') return Response.json({ error: `no order ${name}` }, { status: 404 });
          order = this.host.spawn('order', { name });
        }
        if (event) {
          const body = await request.text();
          order.send(event, body === '' ? undefined : JSON.parse(body));
        }
        await this.host.idle();
        const state = await this.read(order);
        await this.commit();
        return Response.json({ order: name, ...state });
      });
    }

    async alarm() {
      await this.serially(async () => {
        await this.host.idle();
        await this.commit();
      });
    }

    // One request at a time, with the host's clock stepped to now.
    serially(work) {
      const run = this.queue.then(() => {
        const now = Date.now();
        this.clock.increment(Math.max(0, now - this.wall));
        this.wall = now;
        return work();
      });
      this.queue = run.catch(() => {});
      return run;
    }

    // The order's state and items; a hibernated order is woken to be read.
    async read(order) {
      try {
        return await this.inspect(order);
      } catch (error) {
        if (error.reason !== 'state') throw error;
        const store = this.store();
        this.host.wake(order, store.load(order.id));
        store.delete(order.id);
        await this.host.idle();
        return this.inspect(order);
      }
    }

    async inspect(order) {
      const { value } = await order.state();
      const { variables } = await order.context();
      return { state: value, items: variables.items };
    }

    // The blobs since the last commit, the snapshot and the wall clock in
    // one transaction, then the alarm at the host's next deadline.
    async commit() {
      const snapshot = this.host.snapshot();
      const deadline = this.host.nextDeadline;
      this.ctx.storage.transactionSync(() => {
        for (const [session, blob] of this.pending) {
          if (blob === null) this.sql.exec('DELETE FROM blobs WHERE session = ?', session);
          else this.sql.exec('INSERT OR REPLACE INTO blobs VALUES (?, ?)', session, blob);
        }
        this.sql.exec('DELETE FROM snapshot');
        for (let part = 0; part * PART < snapshot.length; part++) {
          this.sql.exec('INSERT INTO snapshot VALUES (?, ?)', part, snapshot.subarray(part * PART, (part + 1) * PART));
        }
        this.sql.exec("INSERT OR REPLACE INTO meta VALUES ('wall', ?)", this.wall);
      });
      this.pending.clear();
      if (deadline === undefined) await this.ctx.storage.deleteAlarm();
      else await this.ctx.storage.setAlarm(this.wall + deadline);
    }
  };
}

function join(parts) {
  const bytes = new Uint8Array(parts.reduce((sum, part) => sum + part.length, 0));
  let at = 0;
  for (const part of parts) {
    bytes.set(part, at);
    at += part.length;
  }
  return bytes;
}
  • store and residentpast 1000 orders in memory, the host hibernates the ones that have not run lately into the blobs table.
  • commit()writes the snapshot, the blobs saved since the last commit and the time in one transactionSync, so the storage never holds a blob the snapshot does not expect.
  • Host.restoreruns in a new instance of the object, after an eviction or a deploy. It brings back the last snapshot, and the hibernated orders load from the same table.
  • The clockis a SimulatedClock stepped to the wall clock at each request and alarm, so the 15 minutes count while the object is out of memory.
  • setAlarmwakes the object at the host's next deadline, and alarm() runs what is due. An object has one alarm at a time.
  • serially()runs one request at a time, so no snapshot is taken while another request's events run.

Restart the object and keep the orders

npx wrangler dev runs the Worker in workerd on your machine, with no Cloudflare account. Stopping it and starting it again makes a new instance of the object, as an eviction does:

shell
$ curl -X POST localhost:8787/orders/order-1/add -d '"book"'
{"order":"order-1","state":"cart","items":["book"]}
$ curl -X POST localhost:8787/orders/order-1/checkout
{"order":"order-1","state":"awaiting_payment","items":["book"]}
# Ctrl-C, then npx wrangler dev again
$ curl localhost:8787/orders/order-1
{"order":"order-1","state":"awaiting_payment","items":["book"]}

The object also runs in Node.js over a stand-in for its ctx, which tests it without workerd. Here it keeps one order in memory, loses its instance, then gets its alarm 15 minutes later:

main.mjsjavascript
// shop.mjs in Node.js, without workerd: a stand-in for the object's ctx
// over node:sqlite, the requests a client would make, an eviction (a new
// instance of the object over the same database) and the alarm 15
// minutes later.
import { readFileSync } from 'node:fs';
import { init, compileCharts } from '@tinyactors/wasm/init';
import { shop } from './shop.mjs';

process.removeAllListeners('warning'); // node:sqlite says it is experimental
const { DatabaseSync } = await import('node:sqlite');

await init();
const compiled = compileCharts([{ name: 'order.scxml', text: readFileSync(new URL('order.scxml', import.meta.url), 'utf8') }]);
const Shop = shop(compiled.image, { resident: 1 }); // one order in memory, the rest in SQLite
compiled.close();

// The stand-in's wall clock, which the alarm moves on.
const wall = Date.now;
let skew = 0;
Date.now = () => wall() + skew;

const db = new DatabaseSync(':memory:');
let alarm = null;
const ctx = {
  storage: {
    sql: {
      exec(query, ...bindings) {
        const statement = db.prepare(query);
        const rows = statement.columns().length > 0 ? statement.all(...bindings) : (statement.run(...bindings), []);
        return { toArray: () => rows, one: () => rows[0] };
      },
    },
    transactionSync(work) {
      db.exec('BEGIN');
      try { work(); db.exec('COMMIT'); } catch (error) { db.exec('ROLLBACK'); throw error; }
    },
    async setAlarm(at) { alarm = at; },
    async deleteAlarm() { alarm = null; },
  },
  blockConcurrencyWhile: (work) => work(),
};

async function request(object, method, path, data) {
  const body = data === undefined ? undefined : JSON.stringify(data);
  const response = await object.fetch(new Request(`https://shop.example${path}`, { method, body }));
  console.log(method, path, JSON.stringify(await response.json()));
}

let object = new Shop(ctx);
await request(object, 'POST', '/orders/order-1/add', 'book');
await request(object, 'POST', '/orders/order-1/add', 'pen');
await request(object, 'POST', '/orders/order-1/checkout');
await request(object, 'POST', '/orders/order-2/add', 'lamp');
const blobs = db.prepare('SELECT session FROM blobs').all().map((row) => row.session);
console.log('hibernated in SQLite:', blobs.join(', '));
console.log('alarm in', Math.round((alarm - Date.now()) / 1000), 's');

object = new Shop(ctx); // evicted: a new instance reads the snapshot back
console.log('-- a new instance of the object');
await request(object, 'GET', '/orders/order-1');

skew += 15 * 60_000;
await object.alarm();
console.log('-- the alarm, 15 minutes later');
await request(object, 'GET', '/orders/order-1');
await request(object, 'GET', '/orders/order-2');
output
POST /orders/order-1/add {"order":"order-1","state":"cart","items":["book"]}
POST /orders/order-1/add {"order":"order-1","state":"cart","items":["book","pen"]}
POST /orders/order-1/checkout {"order":"order-1","state":"awaiting_payment","items":["book","pen"]}
POST /orders/order-2/add {"order":"order-2","state":"cart","items":["lamp"]}
hibernated in SQLite: 1
alarm in 900 s
-- a new instance of the object
GET /orders/order-1 {"order":"order-1","state":"awaiting_payment","items":["book","pen"]}
-- the alarm, 15 minutes later
GET /orders/order-1 {"order":"order-1","state":"expired","items":["book","pen"]}
GET /orders/order-2 {"order":"order-2","state":"cart","items":["lamp"]}

Order 1 was in SQLite when the instance went, and the new one restored it waiting for payment. The alarm then expired it. Order 2 stayed in its cart.

Each request writes the whole host

A snapshot is the host's memory, so every commit rewrites all of it. With 10,000 orders and 100 of them in memory it was 4.3 MB, and one event took 41 to 52 ms in local workerd (measured on one machine). Size, not traffic, sets the cost.

So keep each object to one shop or one tenant: thousands of actors, not millions. For millions in one process, run the host in Node.js with a store.

What a production version adds

  • A pinned packagea snapshot restores only into a build of @tinyactors/wasm with the same memory layout, and Host.restore refuses another with TA_ERROR_INVALID. Before deploying a new version, restore a copy of a live object's snapshot with it.
  • Answers from outsidea payment provider's webhook is a request like any other: POST /orders/order-1/paid.
  • Effectsa chart's sends to your code go to an I/O processor. The host waits for the promise it returns, so a fetch it makes finishes before the commit.
  • Several objectseach object is a host of its own, so an actor reaches another object's actor through a transport you write (Other systems).