Retries and timeouts, without a Temporal server

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 timeoutsSee when Temporal fits

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"Temporal, "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"

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

Durable Objects and Rivet run actors as a platform too: see tinyactors compared with Durable Objects and tinyactors compared with Rivet.

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:

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:

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

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)

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

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"

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

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"Temporal, "Versioning" (TypeScript)

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"

Choose tinyactors for logic inside your program

  • Workflows in a program you already runThe host is a library, so no server, database or worker fleet runs beside your program.
  • Tests that reach every timeoutA simulated clock jumps to each deadline, so one program checks a payment's rules over a thousand runs.
  • Many workflows, most of them waitingWaiting actors hibernate into your store: two million ran with at most 1000 in memory, the rest in SQLite.
  • The whole flow written downEvery state and transition is in one SCXML chart, which a test, a reviewer or the command line can read.

Choose Temporal when its service must own durability

  • Durability you don't buildThe service keeps each workflow's event history in its database. Replay restores the state after infrastructure fails.
  • Work spread across many machinesWorkers on any machine poll task queues. tinyactors leaves placement and failover between hosts to your program.
  • Retries without writing themTemporal retries a failed activity by default, 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 codeA workflow is code in your language, with no chart format to learn (Temporal, "Workflow Definition").

Test a payment's timeoutsSee when to use tinyactorsRead what a snapshot keeps