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.
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.
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.
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.
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:
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.
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();
<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 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 >= 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>
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.
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.
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.
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).