<!-- https://tinyactors.dev/compare/durable-objects/ -->
# tinyactors compared with Durable Objects

Kind: pitch. For: [Agent-platform engineer](https://tinyactors.dev/audiences/agent-platform.xml), [Tech lead who approves dependencies](https://tinyactors.dev/audiences/tech-lead.xml).
Voice: [Pitch](https://tinyactors.dev/voices/pitch.xml).

> Where a stateful session runs, what an idle one keeps, how its tests move time, what a deploy does to it, and when Cloudflare Durable Objects are the better choice.

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 sessions](https://tinyactors.dev/compare/durable-objects/index.md#deploy) · [See Durable Objects' strengths](https://tinyactors.dev/compare/durable-objects/index.md#choose-durable-objects)

<a id="where-it-runs"></a>

## 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"](https://developers.cloudflare.com/durable-objects/) · [Cloudflare, "What are Durable Objects?"](https://developers.cloudflare.com/durable-objects/concepts/what-are-durable-objects/)
- **A tinyactors host lives in your program**: `new Host(charts, options)` runs the actors inside the Node.js, Bun, Python or browser process that imports the package. A chart reaches the model's API, your database or a socket only through handlers you give the host. Source: [Architecture, "Actors run SCXML charts inside your process"](https://tinyactors.dev/architecture/index.md#what) · [I/O processors, "Ask for outside work with a send"](https://tinyactors.dev/guides/io-processors/index.md#charts-send-events)

The cost is on your side. Your program decides where each host runs and carries a message to another host's actor ([Other systems](https://tinyactors.dev/guides/other-systems/index.md)). On Cloudflare, that's the platform's work.

<a id="state"></a>

## 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 idle object discards its memory**: After 10 seconds without work an object can hibernate, and its in-memory state is discarded. Cloudflare says to persist anything important to the object's storage. That storage is SQLite, up to 10 GB per object on the paid plan. Source: [Cloudflare, "Durable Object lifecycle"](https://developers.cloudflare.com/durable-objects/concepts/durable-object-lifecycle/) · [Cloudflare, "In-memory state in a Durable Object"](https://developers.cloudflare.com/durable-objects/reference/in-memory-state/) · [Cloudflare, "Limits"](https://developers.cloudflare.com/durable-objects/platform/limits/)
- **An idle actor goes to your store whole**: Give the host a store and a bound, and it writes the actors past the bound into the store: variables, active states and all. The next event wakes one. Two million actors ran with at most 1000 in memory and the rest in SQLite. Source: [Hibernation, "Cap how many actors stay in memory"](https://tinyactors.dev/guides/hibernation/index.md#a-store-and-a-bound) · [Hibernation, "Run two million actors with 1000 in memory"](https://tinyactors.dev/guides/hibernation/index.md#at-scale)

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](https://tinyactors.dev/guides/capacity/index.md#what-an-actor-costs)).

<a id="tests"></a>

## 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:

```scxml title="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:

```javascript title="simulate.mjs"
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;
  };
}
```

```text title="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"](https://developers.cloudflare.com/durable-objects/examples/testing-with-durable-objects/)
- **A simulated clock moves when tests move it**: The test above is a host, a clock and a stand-in object. Every timer of every actor waits for `clock.increment()`. Source: [Testing, "Replace the chart's services and its clock"](https://tinyactors.dev/guides/testing-recipes/index.md#three-tools)

<a id="deploy"></a>

## 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 deploy resets an active object**: By default an active object keeps its old code until it hibernates, or for up to 300 seconds. Then it resets and adopts the new code. Hibernation discards in-memory state, so what carries over is what the object stored. Source: [Cloudflare, "Durable Objects code updates"](https://developers.cloudflare.com/durable-objects/deployments/durable-objects-code-updates/) · [Cloudflare, "Durable Object lifecycle"](https://developers.cloudflare.com/durable-objects/concepts/durable-object-lifecycle/)
- **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"](https://tinyactors.dev/guides/migration/index.md#moving-running-actors)

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:

Node.js and Bun:

```javascript title="main.mjs"
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();
```

```scxml title="session-v1.scxml"
<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
       datamodel="ecmascript" name="session" initial="waiting">
  <datamodel><data id="turns" expr="0"/></datamodel>

  <!-- An agent session waits for the user's prompt, asks the model and
       counts the turns it answered. -->
  <state id="waiting">
    <transition event="prompt" target="thinking"/>
  </state>
  <state id="thinking">
    <onentry>
      <send type="model" event="complete"><param name="text" expr="_event.data.text"/></send>
    </onentry>
    <transition event="reply" target="waiting">
      <assign location="turns" expr="turns + 1"/>
    </transition>
  </state>
</scxml>
```

```scxml title="session-v2.scxml"
<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
       datamodel="ecmascript" name="session" initial="waiting">
  <datamodel><data id="turns" expr="0"/></datamodel>

  <!-- Version 2 adds a plan limit: after three turns the session ends
       instead of asking the model. A moved session takes its turns from
       version 1. -->
  <state id="waiting">
    <transition event="error.platform.upgrade">
      <assign location="turns" expr="_event.data.turns"/>
    </transition>
    <transition event="prompt" cond="turns &gt;= 3" target="limited"/>
    <transition event="prompt" target="thinking"/>
  </state>
  <state id="thinking">
    <onentry>
      <send type="model" event="complete"><param name="text" expr="_event.data.text"/></send>
    </onentry>
    <transition event="reply" target="waiting">
      <assign location="turns" expr="turns + 1"/>
    </transition>
  </state>
  <final id="limited">
    <donedata><param name="turns" expr="turns"/></donedata>
  </final>
</scxml>
```

```text title="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 id="crash"></a>

## 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"](https://developers.cloudflare.com/durable-objects/api/sqlite-storage-api/)
- **A crash keeps what your program saved**: Actors live in your process's memory, so a crash stops them all. Hibernated actors in your store and the last snapshot come back. Inputs after that snapshot return when your program journaled them. Source: [When to use tinyactors, "A crash stops memory and keeps saved state"](https://tinyactors.dev/when-to-use/index.md#crash) · [Journal and replay](https://tinyactors.dev/guides/journal/index.md)

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.

<a id="choose-tinyactors"></a>

## Choose tinyactors for sessions inside your backend

- **A backend on the cloud you chose**: The 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 place**: A [migration](https://tinyactors.dev/guides/migration/index.md) moves running sessions to new rules with their states, queues and timers.
- **Tests that reach every timeout**: A simulated clock jumps to each deadline, so one program checks a thousand sessions.
- **Logic an agent can write and you can read**: Each session is one [SCXML chart](https://tinyactors.dev/guides/charts/index.md), and an uploaded chart runs in [the QuickJS sandbox](https://tinyactors.dev/guides/quickjs/index.md).

<a id="choose-durable-objects"></a>

## Choose Durable Objects for sessions reached from anywhere

- **Clients all over the world**: Each object has a globally unique name and is placed near its first request. tinyactors leaves [placement and failover between hosts](https://github.com/tinyactors-dev/tinyactors/blob/main/README.md#layers-and-responsibilities) to your program.
- **Storage you don't operate**: Each object has its own SQLite database, [restorable to any point of the past 30 days](https://developers.cloudflare.com/durable-objects/api/sqlite-storage-api/).
- **Connections that outlive memory**: [WebSocket Hibernation](https://developers.cloudflare.com/durable-objects/best-practices/websockets/) keeps clients connected while the object is out of memory, and duration charges stop meanwhile.
- **An application already on Workers**: A 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](https://tinyactors.dev/guides/workers/index.md)).

[Hibernate idle sessions](https://tinyactors.dev/guides/hibernation/index.md) · [Upgrade running actors](https://tinyactors.dev/guides/migration/index.md) · [See when to use tinyactors](https://tinyactors.dev/when-to-use/index.md)
