<!-- https://tinyactors.dev/compare/temporal/ -->
# tinyactors compared with Temporal

Kind: pitch. For: [Workflow developer who tests](https://tinyactors.dev/audiences/workflow-tester.xml), [Tech lead who approves dependencies](https://tinyactors.dev/audiences/tech-lead.xml).
Voice: [Pitch](https://tinyactors.dev/voices/pitch.xml).

> Where a workflow with retries and timeouts runs, how its tests move time, what a crash keeps, and when Temporal is the better choice.

A payment that retries every 30 seconds runs as a statechart inside your own process. One program checks it over a thousand simulated runs, with no server and no database. Choose Temporal when its service must keep every workflow through a machine's failure.

[Test a payment's timeouts](https://tinyactors.dev/guides/testing-recipes/index.md#a-test) · [See when Temporal fits](https://tinyactors.dev/compare/temporal/index.md#choose-temporal)

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

## Temporal is a service; tinyactors is a library

A payment that retries three times is a few states of logic. With Temporal, it spans a server, a database and the workers you run. tinyactors keeps it in your process.

- **Temporal runs a server and its database**: Its docs define the service as the Temporal Server combined with persistence and visibility stores. In production the store is Cassandra, PostgreSQL or MySQL. SQLite is for development and testing only. Source: [Temporal, "Temporal Service"](https://docs.temporal.io/temporal-service) · [Temporal, "Persistence"](https://docs.temporal.io/temporal-service/persistence)
- **Your workers poll the service for tasks**: Worker processes are external to the service, and you operate them. Each one polls a task queue, runs your code and reports the result back. Source: [Temporal, "Workers"](https://docs.temporal.io/workers)
- **A tinyactors host lives in your program**: `new Host(charts, options)` runs the actors inside the program that imports `@tinyactors/node` or `tinyactors`. A chart reaches the world 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)

Temporal Cloud takes the service off your hands: Temporal operates its persistence, replication, upgrades and availability. Your workers still run in your environment ([Temporal, "Temporal Cloud"](https://docs.temporal.io/evaluate/cloud)).

Durable Objects and Rivet run actors as a platform too: see [tinyactors compared with Durable Objects](https://tinyactors.dev/compare/durable-objects/index.md) and [tinyactors compared with Rivet](https://tinyactors.dev/compare/rivet/index.md).

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

## Test a thousand payments in one program

A workflow's bugs hide in its timeouts. This chart charges a card, charges again after 30 seconds without an answer and gives up after three charges. Every attempt carries the same key, the payment's session:

```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 gives the host a stand-in payment provider. It answers a charge at once, 45 seconds late, after the next charge has gone out, or never.

A simulated clock jumps to each timeout and each late answer, so a thousand payments run in one program. Then it checks three rules:

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

One key for every attempt lets the provider charge the card once, however many requests reach it. The 51 answers that came after the chart gave up are payments your program must reconcile with the provider.

- **Temporal's tests skip time with a server**: Temporal's test framework is an in-memory Temporal Server whose timers fast-forward, except while activities run. The `@temporalio/testing` package downloads that server. Source: [Temporal, "Testing suite" (TypeScript)](https://docs.temporal.io/develop/typescript/testing-suite)

Here the host and its clock are the whole test. No server starts.

The stand-in service is an object, so it answers, fails or stays silent as each case needs ([Testing recipes](https://tinyactors.dev/guides/testing-recipes/index.md#three-tools)).

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

## Temporal keeps history; your program keeps snapshots

A process dies halfway through a payment. What survives depends on who wrote it down.

- **Temporal replays every workflow from its history**: The service records each workflow's event history, a complete ordered log that is its source of truth. To continue a workflow, it reruns the code from the beginning against that history. Its docs say workflows keep running for years, even if the underlying infrastructure fails. Source: [Temporal, "Temporal Workflow"](https://docs.temporal.io/workflows)
- **A crash keeps what your program saved**: tinyactors actors live in your process's memory, so a crash stops them all. What comes back is what your program saved: hibernated actors in its store, and its last snapshot. Inputs after that snapshot return when your program journaled them: replaying a journal is one loop. 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)

The journal is one write per input, to a store your program already runs. If you'd rather not own that write and its storage, choose Temporal.

A snapshot holds only its moment. A snapshot of two million actors takes 165 MB ([Snapshots](https://tinyactors.dev/guides/snapshots/index.md)).

<a id="changes"></a>

## Change a workflow that is already running

An order waits a week for delivery. On Tuesday the rules change. The running order must take the new rules without losing its place.

- **Temporal's replay needs deterministic code and patches**: Replay reruns workflow code, so given the same input it must make the same API calls in the same order. Adding, removing or reordering one causes a nondeterminism error. `patched()` marks a change in the event history, a branch like a feature flag, so running workflows keep their old path. Source: [Temporal, "Workflow Definition"](https://docs.temporal.io/workflow-definition) · [Temporal, "Versioning" (TypeScript)](https://docs.temporal.io/develop/typescript/versioning)
- **A migration moves running actors to a version**: A new chart version is added to the running host, and `host.migrate()` moves running actors to it. Each keeps its active states, queue and delayed sends. The new chart reads the old variables from one event and decides what carries over. Source: [Migration, "Move the actors and carry their variables"](https://tinyactors.dev/guides/migration/index.md#moving-running-actors)

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

## Choose tinyactors for logic inside your program

- **Workflows in a program you already run**: The host is a library, so no server, database or worker fleet runs beside your program.
- **Tests that reach every timeout**: A simulated clock jumps to each deadline, so one program checks a payment's rules over a thousand runs.
- **Many workflows, most of them waiting**: Waiting actors hibernate into your store: [two million ran with at most 1000 in memory](https://tinyactors.dev/guides/hibernation/index.md#at-scale), the rest in SQLite.
- **The whole flow written down**: Every state and transition is in one [SCXML chart](https://tinyactors.dev/guides/charts/index.md), which a test, a reviewer or the [command line](https://tinyactors.dev/cli/index.md) can read.

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

## Choose Temporal when its service must own durability

- **Durability you don't build**: The service keeps each workflow's event history in its database. Replay restores the state after infrastructure fails.
- **Work spread across many machines**: Workers on any machine poll task queues. tinyactors leaves [placement and failover between hosts](https://github.com/tinyactors-dev/tinyactors/blob/main/README.md#layers-and-responsibilities) to your program.
- **Retries without writing them**: Temporal [retries a failed activity by default](https://docs.temporal.io/encyclopedia/retry-policies), starting after one second and doubling. In a chart, the retry is two transitions you can read and test, as the payment above shows.
- **Workflows as ordinary code**: A workflow is code in your language, with no chart format to learn ([Temporal, "Workflow Definition"](https://docs.temporal.io/workflow-definition)).

[Test a payment's timeouts](https://tinyactors.dev/guides/testing-recipes/index.md#a-test) · [See when to use tinyactors](https://tinyactors.dev/when-to-use/index.md) · [Read what a snapshot keeps](https://tinyactors.dev/guides/snapshots/index.md)
