<!-- https://tinyactors.dev/compare/rivet/ -->
# tinyactors compared with Rivet

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

> Who places an actor, what a sleeping one keeps, how its tests move time, what a deploy does to running actors, and when Rivet Actors are the better choice.

Rivet runs actors in your Node.js or Bun backend, for agents, realtime apps and per-tenant databases, placed by Rivet Cloud or a control plane you deploy. tinyactors runs each session as a statechart in your process, with nothing beside it. Choose Rivet when actors must move between machines on their own.

[Upgrade running sessions](https://tinyactors.dev/compare/rivet/index.md#deploy) · [See when Rivet fits](https://tinyactors.dev/compare/rivet/index.md#choose-rivet)

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

## Rivet places actors; your program places hosts

Both run your actors in your backend's process. The difference is what runs beside it. And who decides where an actor lives.

- **Rivet's control plane places each actor**: Rivet calls its actors isolated, durable processes that run in your backend. You deploy the control plane yourself, or use Rivet Cloud. The platform may move an actor to another node, for example when its node stops during a deploy. In development, Rivet runs a local control plane for you and keeps actor data on your machine. Source: [Rivet, "Actors"](https://rivet.dev/docs/actors) · [Rivet, "Lifecycle"](https://rivet.dev/actors/docs/lifecycle/) · [Rivet, "Node.js and Bun quickstart"](https://rivet.dev/actors/docs/quickstart/backend/)
- **A tinyactors actor stays in its host**: `new Host(charts, options)` runs the actors inside the process that imports the package. An actor stays in the host that spawned it. A chart reaches the model's API or your database only through handlers you give the host. Source: [Architecture, "Actors run SCXML charts inside your process"](https://tinyactors.dev/architecture/index.md#what) · [Other systems, "Give each host a system name"](https://tinyactors.dev/guides/other-systems/index.md#systems)

There's nothing to operate. There's also nothing that moves an actor for you: which host runs where, and how a message reaches another host, is your program's code.

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

## A sleeping actor keeps what was stored

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

- **A Rivet actor keeps its SQLite database**: After 30 seconds without activity an actor sleeps, and the next request wakes it. Its `c.vars` are never saved. What must survive goes in `c.db`, a SQLite database per actor whose every committed write is replicated before it's acknowledged. `c.state`, which Rivet saved on a throttle, is deprecated since Rivet 3.0. Source: [Rivet, "Lifecycle"](https://rivet.dev/actors/docs/lifecycle/) · [Rivet, "State"](https://rivet.dev/actors/docs/state/) · [Rivet, "State (deprecated)"](https://rivet.dev/actors/docs/deprecated/state/)
- **A hibernated 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. A blob wakes only in the host that made it, or in one restored from that host's snapshot. Source: [Hibernation, "Cap how many actors stay in memory"](https://tinyactors.dev/guides/hibernation/index.md#a-store-and-a-bound) · [Hibernation, "Wake each blob where it was made"](https://tinyactors.dev/guides/hibernation/index.md#what-a-blob-holds)

Two million actors ran with at most 1000 in memory and the rest in SQLite ([Hibernation](https://tinyactors.dev/guides/hibernation/index.md#at-scale)). An actor's data your business must keep belongs in your own database, as with any process.

<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"
<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
       datamodel="ecmascript" name="payment" initial="charging">
  <datamodel><data id="attempts" expr="0"/></datamodel>
  <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>
  <final id="paid"><donedata><param name="outcome" expr="'paid'"/></donedata></final>
  <final id="failed"><donedata><param name="outcome" expr="'failed'"/></donedata></final>
</scxml>
```

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
```

- **Rivet's tests wait for real schedules**: `setupTest` starts your registry in test mode. Rivet's docs say Vitest's fake timers don't advance RivetKit's scheduler. They recommend a short schedule and polling the result with `expect.poll`. Source: [Rivet, "Testing"](https://rivet.dev/actors/docs/testing/)
- **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 Rivet deploy stops actors on old nodes**: Each deploy sets a version that only increases. Once a newer node connects, the old deploy gets no new actors. With draining on, old actors stop as in a node shutdown, each with up to 15 seconds to save its state. Each deploy must read the state the last one wrote. Source: [Rivet, "Versions and Upgrades"](https://rivet.dev/actors/docs/versions/)
- **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
```

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](https://tinyactors.dev/guides/migration/index.md#moving-running-actors)).

No process restarted. Every session kept its count, so each one ended at the limit instead of asking the model again.

<a id="crash"></a>

## A crash keeps what was written down

A machine dies halfway through a session. What comes back is what reached storage, and Rivet operates more of that storage for you.

- **Rivet keeps the database, not the memory**: The database survives the actor moving to another node. The sleep hook may not run in a crash, and a snapshot to SQLite on an interval loses what came after it. A `run` workflow resumes from its last completed step after a crash. Source: [Rivet, "State"](https://rivet.dev/actors/docs/state/) · [Rivet, "Lifecycle"](https://rivet.dev/actors/docs/lifecycle/)
- **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)

<a id="processes"></a>

## Run more processes by naming each host

One host runs in one process. To spread actors over several, you write the part Rivet's control plane does:

- **A system name per host**: The `system` option names each process's host, and every address starts with it, as in `tinyactors://eu-1/@order-7` ([Other systems](https://tinyactors.dev/guides/other-systems/index.md#systems)).
- **Routing by name**: Your code decides which process spawns each name, and sends to an actor by its address ([Other systems](https://tinyactors.dev/guides/other-systems/index.md#address-targets)).
- **A transport**: The host hands each send for another system to your `transport` handler, which writes it on a connection; the other side passes it to `host.send` ([Other systems](https://tinyactors.dev/guides/other-systems/index.md#over-a-socket)).

That code is yours to write and run: the connections, their reconnects and which process owns which names. When a process dies, its actors come back only where your program restores them.

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

## Choose tinyactors for one process you understand

- **Nothing to operate beside your backend**: The host is a library in your Node.js, Bun or Python process, so tests and production create it the same way.
- **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-rivet"></a>

## Choose Rivet when actors must move between machines

- **Placement and failover you don't write**: The control plane places each actor and moves it when its node stops. tinyactors leaves [placement and failover between hosts](https://github.com/tinyactors-dev/tinyactors/blob/main/README.md#layers-and-responsibilities) to your program.
- **A replicated database per actor**: Each actor's SQLite writes are [replicated before they're acknowledged](https://rivet.dev/actors/docs/state/), and the database follows the actor to another node.
- **A managed service**: [Rivet Cloud](https://rivet.dev/) runs the control plane on AWS and Google Cloud, or in your own VPC on AWS, Google Cloud or Azure.
- **Actors as ordinary code**: A Rivet actor is a set of actions in TypeScript or Rust ([Rivet, "Actors"](https://rivet.dev/docs/actors)), with no chart format to learn.

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