Stateful sessions in the backend you already run

A Durable Object gives each agent session its own state and one order of events, on Cloudflare's network. tinyactors runs that session as a statechart inside your own process. Choose Durable Objects when sessions must be reachable from anywhere in the world.

Upgrade running sessionsSee Durable Objects' strengths

Cloudflare runs the object; you run the host

Your backend already runs somewhere you chose. In a Durable Object, a session's logic runs on Cloudflare's network, apart from the rest of your backend.

A Durable Object is a Worker with storage

Cloudflare defines it as a special kind of Worker that combines compute with storage. It is placed close to where it is first requested.

Each object has a globally unique name, so a request reaches that one object from anywhere in the world.

Source:Cloudflare, "Durable Objects"Cloudflare, "What are Durable Objects?"

The cost is on your side. Your program decides where each host runs and carries a message to another host's actor (Other systems). On Cloudflare, that's the platform's work.

Idle sessions wait in your database

Most sessions sit idle between a user's messages. Their state must survive until the next one, without holding memory meanwhile.

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).

Test a thousand timeouts in one program

A session's bugs hide in what happens when an answer is late. This payment charges a card, charges again after 30 seconds without an answer and gives up after three charges:

payment.scxml
<state id="charging">
  <onentry>
    <assign location="attempts" expr="attempts + 1"/>
    <send type="urn:payments" event="charge" target="card">
      <param name="attempt" expr="attempts"/>
      <param name="key" expr="_sessionid"/>
    </send>
    <send event="timeout" delay="30s" id="timer"/>
  </onentry>
  <transition event="charged" target="paid"><cancel sendid="timer"/></transition>
  <transition event="timeout" cond="attempts &lt; 3" target="charging"/>
  <transition event="timeout" target="failed"/>
</state>

The test's stand-in provider answers at once, 45 seconds late or never. A simulated clock jumps to each timeout, so a thousand payments run in one Node.js process:

simulate.mjsjavascript
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { compileCharts, Host, SimulatedClock } from '@tinyactors/node';

const compiled = compileCharts([{ name: 'payment.scxml', text: readFileSync('payment.scxml', 'utf8') }]);
let paidLate = 0;
let answeredAfterGivingUp = 0;

for (let seed = 1; seed <= 1000; seed++) {
  const random = mulberry32(seed);
  const clock = new SimulatedClock();
  const requests = [];
  const late = []; // answers the provider sends 45 seconds after the charge
  let outcome;
  const host = new Host(compiled, {
    system: 'simulation',
    clock,
    ioProcessors: {
      'urn:payments': {
        receive(send) {
          requests.push(send.data.key);
          const roll = random();
          if (roll < 0.3) send.answer('charged'); // at once
          else if (roll < 0.6) late.push({ at: clock.now + 45_000, actor: send.sender }); // after the next charge
        }, // otherwise it never answers
      },
    },
    onDone: (actor, donedata) => { outcome = donedata.outcome; },
  });
  host.spawn('payment');
  await host.idle();
  while (outcome === undefined || late.length > 0) {
    const nextLate = late.length > 0 ? Math.min(...late.map((answer) => answer.at)) - clock.now : Infinity;
    clock.increment(Math.min(host.nextDeadline ?? Infinity, nextLate)); // jump to what comes next: no waiting
    for (const answer of late.filter((answer) => answer.at <= clock.now)) {
      late.splice(late.indexOf(answer), 1);
      if (outcome === undefined) { answer.actor.send('charged'); paidLate++; }
      else if (outcome === 'failed') answeredAfterGivingUp++;
    }
    await host.idle();
  }
  assert.ok(requests.length <= 3, `seed ${seed}: charged ${requests.length} times`);
  assert.equal(new Set(requests).size, 1, `seed ${seed}: the attempts carry different keys`);
  assert.ok(outcome === 'paid' || requests.length === 3, `seed ${seed}: gave up early`);
  host.close();
}
console.log('1000 seeds: never more than three charges, one key for all of them, never giving up early');
console.log(`${paidLate} paid by an answer that came after the next charge`);
console.log(`${answeredAfterGivingUp} answered after the chart gave up: reconcile those with the provider`);

function mulberry32(seed) {
  return () => {
    seed = (seed + 0x6d2b79f5) | 0;
    let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
  };
}
output
1000 seeds: never more than three charges, one key for all of them, never giving up early
312 paid by an answer that came after the next charge
51 answered after the chart gave up: reconcile those with the provider

Durable Objects' tests run in the Workers runtime

Cloudflare's Vitest integration runs tests inside the Workers runtime, with the objects' bindings and storage.

runDurableObjectAlarm() fires a scheduled alarm at once instead of waiting for its timer.

Source:Cloudflare, "Testing Durable Objects"

Ship new rules to running sessions

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

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

Every session kept its count through the move. So each one ended at the limit instead of asking the model again.

A Durable Object that stores its count keeps it across a deploy too, and its new code reads it back. The difference is the rest: a migration also carries each session's states, queue and timers, with no code that reads them back.

A crash keeps what was written down

A machine dies halfway through a session. Both answers start from storage; they differ in who owns it.

An object's writes are stored all or none

If a machine fails, either all of a write's changes reached disk or none did.

Point-in-time recovery restores an object's database to any moment of the past 30 days.

Source:Cloudflare, "SQLite-backed Durable Object Storage"

Here Durable Objects keep more by default: every write an object stores survives. With tinyactors, what your program did not save or journal is lost with the process.

Choose tinyactors for sessions inside your backend

  • A backend on the cloud you choseThe host is a library in your Node.js, Bun or Python process, so the sessions deploy with the code that calls them.
  • Deploys that keep each session's placeA migration moves running sessions to new rules with their states, queues and timers.
  • Tests that reach every timeoutA simulated clock jumps to each deadline, so one program checks a thousand sessions.
  • Logic an agent can write and you can readEach session is one SCXML chart, and an uploaded chart runs in the QuickJS sandbox.

Choose Durable Objects for sessions reached from anywhere

  • Clients all over the worldEach object has a globally unique name and is placed near its first request. tinyactors leaves placement and failover between hosts to your program.
  • Storage you don't operateEach object has its own SQLite database, restorable to any point of the past 30 days.
  • Connections that outlive memoryWebSocket Hibernation keeps clients connected while the object is out of memory, and duration charges stop meanwhile.
  • An application already on WorkersA Durable Object is a Worker, so it shares the platform, bindings and deploys of the rest of the application. One object can also hold a tinyactors host, which keeps Cloudflare and adds statecharts (Run actors in a Cloudflare Worker).

Hibernate idle sessionsUpgrade running actorsSee when to use tinyactors