Statecharts for a whole population of actors

XState gives you a machine and an actor in JavaScript, and leaves storing them to your code. tinyactors runs W3C SCXML charts as actors that hibernate, move to new versions and snapshot, in Node.js, Python, C and browsers. Choose XState for state in a JavaScript user interface.

Upgrade running sessionsSee when XState fits

XState machines are JavaScript; SCXML is a standard

Both describe behavior as states, events and transitions, so a reviewer, a test or an agent can read the whole flow. The difference is the material.

XState machines are JavaScript objects

Stately calls XState a state management and orchestration solution for JavaScript and TypeScript apps. A machine is made with createMachine.

XState v6, in beta, reads SCXML through an experimental @xstate/scxml. Its tests are "regression coverage, not a claim of full SCXML conformance".

Source:Stately, "XState"Stately, "Actors"Stately, "SCXML" (XState v6)

tinyactors runs SCXML documents themselves

Each chart is a W3C SCXML document, and the C core passes all 191 automatic tests of the W3C conformance suite. Every package runs the same suite.

The core decides what each state and transition does. A chart's ECMAScript runs in your own engine in Node.js, Bun and browsers, or in the bundled QuickJS sandbox; Python and C run it in QuickJS.

Source:Memory, capacity and performance, "Correct by the standard"W3C, "State Chart XML (SCXML)"@tinyactors/node, "Before you use it"tinyactors for Python, README

A document is data, so tools other than your program read it. The command line checks, lints and diffs a chart in CI, and draws it.

One chart in four languages

XState runs, in Stately's words, "in the frontend, backend, or wherever JavaScript runs" (Stately, "XState"). tinyactors runs one C core behind each package.

This order retries a failed charge on its own. The same order.scxml runs in Node.js, a browser, Python and C, and each prints the same lines:

import { readFileSync } from 'node:fs';
import { compileCharts, Host } from '@tinyactors/node';

let charges = 0;
const payments = {
  receive(send) {                   // the chart's <send type="payments">
    console.log('charge', JSON.stringify(send.data));
    if (++charges === 1) send.fail(); // down for the first charge: the order gets error.communication
    else send.answer('charged');    // an event back to the order
  },
};
const compiled = compileCharts([{ name: 'order.scxml', text: readFileSync('order.scxml', 'utf8') }]);
const host = new Host(compiled, {
  system: 'shop',
  ioProcessors: { payments },
  log: (entry) => console.log('log', entry.text),
});
compiled.close();

const order = host.spawn('order');
order.send('add', { item: 'notebook', price: 30 });
order.send('add', { item: 'pen', price: 12 });
order.send('checkout');
console.log('paid', await order.done); // the order retried on its own
host.close();
output
charge {"amount":42,"items":["notebook","pen"]}
log payment service unreachable, attempt 1: retrying in 1 s
charge {"amount":42,"items":["notebook","pen"]}
paid 42

XState persists one actor; the host, thousands

Ten thousand chat sessions, most of them idle, must survive until their users return. Something must pick which stay in memory.

XState hands you a snapshot to store

actor.getPersistedSnapshot() returns an actor's state, with its children, and createActor(logic, {snapshot}) restores it.

Storing it is your application's work, in localStorage or a database, and it must be JSON-serializable.

Source:Stately, "Persistence"

An actor in memory takes about 530 bytes of a Node.js process holding a million, measured with a counter chart of one variable (Capacity and memory).

Both test the chart without the world

XState is stronger in one place. It generates test paths from a machine, where tinyactors leaves generated runs to your test.

XState mocks effects and generates paths

Stately's docs say to mock a machine's effects, through setup(), to keep tests deterministic.

getShortestPaths returns a path to every reachable state, and Stately Studio generates tests from them for Playwright and Vitest.

Delays need no real time either: XState v6's testing guide passes a SimulatedClock to createActor and moves it with clock.increment().

Source:Stately, "Testing"Stately, "Graph and paths"Stately, "Test XState logic" (XState v6)

A tinyactors chart's effects are events

A chart reaches the world only through sends to objects you give the host, so a test gives it stand-ins. A simulated clock jumps to each timeout.

Properties over generated runs are a pattern your test writes, not a library call.

Source:Testing, "Replace the chart's services and its clock"Property testing

A crash keeps what was written down

A process dies with sessions in flight. Neither library writes anything down on its own; the difference is how much your program has to write.

XState restores state, not the actions

A restored actor does not run again the actions it already executed. For those, Stately's docs recommend event sourcing.

Source:Stately, "Persistence"

Ship new rules to running sessions

You add a turn limit while thousands of sessions are mid-conversation. Each one must keep the turns it already counted.

XState's restored state may not fit new logic

Stately's docs warn that if the machine changes, a restored state may be incompatible with the new logic.

Source:Stately, "Persistence"

A migration moves running actors to a version

host.addImage() adds the new chart to the running host, and host.migrate() moves actors to it.

Each keeps its active states, queue and delayed sends. The new chart reads the old variables from one event.

Source:Migration, "Move the actors and carry their variables"

Ten thousand agent sessions answer three prompts each, with at most 100 in memory. Version 2 adds a limit of three turns, and one migration moves every session, hibernated ones included:

import { readFileSync } from 'node:fs';
import { compileCharts, Host, MemoryStore } from '@tinyactors/node';

const image = (file) => {
  const compiled = compileCharts([{ name: file, text: readFileSync(file, 'utf8') }]);
  const bytes = compiled.image;
  compiled.close();
  return bytes;
};

let completions = 0;
const model = { receive(send) { completions++; send.answer('reply'); } }; // a stand-in for the model's API
const store = new MemoryStore(); // a real program passes its database: SQLiteStore, or its own
const limited = []; // the turns of each session that ended at the limit
let migrationDone;
const migrated = new Promise((resolve) => { migrationDone = resolve; });
const host = new Host(image('session-v1.scxml'), {
  system: 'agents',
  ioProcessors: { model },
  store,
  resident: 100, // at most 100 sessions in memory, the rest in the store
  migrationDone, // called with the migration's result when it ends
  onDone: (actor, donedata) => { limited.push(donedata.turns); },
});

const sessions = Array.from({ length: 10_000 }, () => host.spawn('session'));
for (let turn = 0; turn < 3; turn++) {
  for (const session of sessions) session.send('prompt', { text: 'Summarize my inbox' });
  await host.idle();
}
console.log(`version 1: ${completions} completions, ${store.blobs.size} sessions in the store`);

host.addImage(image('session-v2.scxml')); // the new rules, added while the host runs
host.migrate({ chart: 'session', wake: true });
const result = await migrated;
console.log(`migration: ${result.migrated} sessions moved, ${result.failed.length} failed`);

completions = 0;
for (const session of sessions) session.send('prompt', { text: 'One more' });
await host.idle();
const afterThree = limited.filter((turns) => turns === 3).length;
console.log(`version 2: ${completions} completions, ${afterThree} sessions ended at the limit of 3 turns`);
host.close();
output
version 1: 30000 completions, 9900 sessions in the store
migration: 10000 sessions moved, 0 failed
version 2: 0 completions, 10000 sessions ended at the limit of 3 turns

A moved session's first event is error.platform.upgrade, and its data holds version 1's variables, so _event.data.turns is the count the session reached. SCXML reserves names starting error.platform for events the platform raises: this one reports the move, not a failure (Migration).

So every session ended at the limit instead of asking the model again.

Choose tinyactors for actors on a server

  • Many long-lived actors, most of them waitingThe host hibernates them into your store, migrates them and snapshots them all.
  • One chart in every languageOne C core runs the same chart in Node.js, Python, C and browsers.
  • A standard formatA W3C SCXML document, checked by the core against the W3C suite, outlives any one library.
  • Charts you did not writeAn uploaded chart runs in the QuickJS sandbox, where a runaway loop ends in an error.

Choose XState for logic in a JavaScript app

  • State in a React component@xstate/react gives hooks such as useMachine, which runs an actor for the component's lifetime.
  • A visual editorStately Studio models machines visually, simulates them and exports the code into your codebase.
  • Test paths from the machineThe graph utilities and Studio generate test paths from a machine; in tinyactors a generated run is code you write.
  • Typed context and eventssetup({ types }) types a machine's context and events. A tinyactors chart has no TypeScript types: index.d.ts types an event as a string and its data as any value.
  • Actors that aren't machinesXState's actors can be promises, callbacks or observables too. A tinyactors actor always runs a chart.
  • A released major versionXState v5 is current, and v6 is in beta. tinyactors is at 0.x and makes frequent breaking changes.

Write a first chartUpgrade running actorsSee when to use tinyactors