<!-- https://tinyactors.dev/guides/hibernation/ -->
# Hibernation

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

> Keep only the busy actors in memory: the host writes the others to blobs in your store and wakes them when they have work.

An actor that waits days for its next event can wait as bytes in your database instead. Two million actors ran with at most 1000 in memory, about 150 bytes of memory each.

<a id="a-store-and-a-bound"></a>

## Cap how many actors stay in memory

Most actors spend most of their time waiting: an order for a payment, a session for its user. Hibernation turns a waiting actor into a blob, a `Buffer` your store keeps.

Give the host a store, which puts the blobs where you choose, and the most actors it may hold in memory.

- **`store: { save, load, delete }`**: where the blobs go, keyed by the actor's session, a `bigint`: `save(session, blob)`, `load(session)` returning the blob, and `delete(session)`. Each may return a promise instead, which the host follows. The package has `MemoryStore`, a `Map` for tests, and `SQLiteStore(path)`, a table in a file through the runtime's own SQLite (`node:sqlite` under Node.js, `bun:sqlite` under Bun).
- **`resident: n`**: the most actors the host keeps in memory. After each turn the host hibernates the actors past the bound that ran least recently, and saves their blobs. It picks them with a CLOCK sweep: an actor that ran since the previous sweep is passed over once.
- **Waking**: When an event comes for a hibernated actor, or one of its delayed sends falls due, the host loads its blob, wakes it and deletes the blob. The actor's events wait in its queue and run at the next turn. An actor terminated while hibernated is woken the same way to end, so its blob goes too.

Of three counters with `resident: 1`, two go to the store, and two events to one of them load it once:

```javascript title="resident.mjs"
import { compileCharts, Host, MemoryStore } from '@tinyactors/node';

const compiled = compileCharts([{ name: 'counter.scxml', text: `
<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
       datamodel="ecmascript" name="counter" initial="counting">
  <datamodel><data id="n" expr="0"/></datamodel>
  <state id="counting">
    <transition event="add">
      <assign location="n" expr="n + _event.data"/>
      <log expr="'counter ' + _sessionid + ' is at ' + n"/>
    </transition>
  </state>
</scxml>` }]);

const store = new MemoryStore();
const host = new Host(compiled, {
  system: 'demo',
  store,
  resident: 1,
  log: (entry) => console.log(entry.text),
});
compiled.close();

const counters = [1, 2, 3].map(() => host.spawn('counter'));
await host.idle();
console.log(`${store.blobs.size} in the store`);

counters[1].send('add', 5);
counters[1].send('add', 5); // one load for both
await host.idle();
console.log(`${store.blobs.size} in the store, ${[...store.blobs.keys()].includes(counters[1].id) ? 'with' : 'without'} counter 2`);
host.close();
```

```text title="output"
2 in the store
counter 2 is at 5
counter 2 is at 10
2 in the store, without counter 2
```

<a id="what-a-blob-stores"></a>

## Keep variables to plain data

On the native datamodel, the default engine for chart code, variables are written as values of the [value table](https://github.com/tinyactors-dev/tinyactors-napi/blob/main/README.md#values):

- **Stored**: numbers, `bigint`s, strings, `Uint8Array`s, arrays, plain objects, `true`, `false`, `null` and `undefined`.
- **Kept in memory**: an actor whose variable holds anything else: a function, a `Map`, a `Date`, a class's instance, an XML document.

A script's top-level `var`s are variables of the actor and come back from the blob. A chart-level script's functions are the chart's helpers and come back with the chart.

On quickjs, the engine also stores a `Date`, `Map`, `Set` or typed array ([what differs on quickjs](https://tinyactors.dev/guides/quickjs/index.md#what-differs-from-the-native-datamodel)).

<a id="a-failed-save"></a>

## Recover from a failed save

A save that throws, or whose promise rejects, wakes the actor back from its blob. The actor stays resident past the bound until a later turn.

The host reports the error the way it reports a handler's ([README, Errors](https://github.com/tinyactors-dev/tinyactors-napi/blob/main/README.md#errors)). A load that finds no blob is reported the same way, and the actor stays hibernated.

The host calls the store between its runs, never inside one, and loads a session only after its pending save.

<a id="a-policy-of-your-own"></a>

## Hibernate actors on your own schedule

Leave out `resident`, and your program picks which actors leave memory: on a timer, or when memory runs short.

Your program takes actors out with `sweep` and `hibernate`. The host still wakes them from the store when their events come.

- **`host.sweep(maxScan, limit)`**: returns at most `limit` sessions that have not run since the previous sweep and can be hibernated now, looking at no more than `maxScan` actors. Calling it regularly is what makes "not run since the previous sweep" mean cold: the first sweep after an actor ran skips it.
- **`host.hibernate(actor)`**: takes the actor out of memory and returns its blob, for you to save in the store.
- **`host.wake(actor, blob)`**: puts it back, which the host does itself when it has a store. Without a store a hibernated actor stays hibernated, and its events wait, until you call it.

The first sweep after the counter ran passes it over, and the second hibernates it:

```javascript title="sweep.mjs"
import { compileCharts, Host, MemoryStore, TinyactorsError } from '@tinyactors/node';

const compiled = compileCharts([{ name: 'counter.scxml', text: `
<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
       datamodel="ecmascript" name="counter" initial="counting">
  <datamodel><data id="n" expr="0"/></datamodel>
  <state id="counting">
    <transition event="add"><assign location="n" expr="n + _event.data"/></transition>
    <transition event="show"><log expr="'counter ' + _sessionid + ' is at ' + n"/></transition>
  </state>
</scxml>` }]);
const store = new MemoryStore();
const host = new Host(compiled, { system: 'demo', store, log: (entry) => console.log(entry.text) });
compiled.close();

function evict() {
  for (const session of host.sweep(1 << 20, 1024)) {
    try {
      store.save(session, host.hibernate(session));
    } catch (error) {
      if (!(error instanceof TinyactorsError)) throw error; // not at rest: it stays
    }
  }
}

const counter = host.spawn('counter');
counter.send('add', 2);
await host.idle();
evict(); // it ran since the last sweep: it stays
evict(); // it did not: it goes
console.log(`${store.blobs.size} in the store`);
counter.send('show');
await host.idle();
host.close();
```

```text title="output"
1 in the store
counter 1 is at 2
```

In a server, run such a sweep on a timer or after a burst of work. Size `limit` so that one sweep does not hold the event loop for long.

<a id="when-an-actor-cannot-hibernate"></a>

## Handle an actor that cannot hibernate

`hibernate` throws a `TinyactorsError` and the actor stays where it is:

- **`TA_ERROR_STATE`**: not now. It has events waiting in its queue (an input you gave since its last turn, an event another actor sent, a delayed send that fell due); or its step is not over, as when called from the handler of a send it made in this turn; or it runs an invoked child chart or a service; or it is not resident: already hibernated, or its blob is loading from the store. Every case gives the same status, and only the message, which is for people, says which.
- **`TA_ERROR_STALE`**: the session ended, or never was.
- **`TA_ERROR_UNSUPPORTED`**: a variable holds what its datamodel cannot store. The message names the variable.

The first three cases of `TA_ERROR_STATE` pass after a turn, and the last does not. The status cannot tell them apart.

So hibernate only what `sweep` returns, which is resident: a `TA_ERROR_STATE` there passes after a turn. With `resident`, the host skips each refused actor and hibernates another.

A `Map` in a variable is outside the value table, and the message names the variable:

```javascript title="unsupported.mjs"
import { compileCharts, Host } from '@tinyactors/node';

const compiled = compileCharts([{ name: 'c.scxml', text: `
<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
       datamodel="ecmascript" name="c" initial="s">
  <datamodel><data id="seen" expr="new Map()"/></datamodel>
  <state id="s"/>
</scxml>` }]);
const host = new Host(compiled, { system: 'demo' });
compiled.close();

const actor = host.spawn('c');
await host.idle();
try {
  host.hibernate(actor);
} catch (error) {
  console.log(error.status);
  console.log(error.message);
}
host.close();
```

```text title="output"
TA_ERROR_UNSUPPORTED
variable 'seen' cannot be stored: only plain objects, arrays and Uint8Arrays are values (docs/values.md)
```

<a id="what-a-blob-holds"></a>

## Wake each blob where it was made

A blob holds the actor's active states, its variables, its `_event` and its place in the host. It lives in your store until the wake, and the host keeps only which hibernation it was.

A blob also wakes in a host [restored](https://tinyactors.dev/guides/snapshots/index.md) from its host's snapshot.

Every host draws a random identity when it is created, and every blob carries it. Another host's blob throws `TA_ERROR_INVALID`, even for the same session number and chart.

A wake takes the session's latest blob only. An earlier blob throws `TA_ERROR_STALE` and the actor stays hibernated, so no state is lost without an error.

A stale replica hands back such a blob, and so does a store whose overwrite failed.

A restored host also accepts a blob of a hibernation made after the snapshot was taken. So a store that keeps one blob per session goes on working there.

<a id="size-the-host"></a>

## Count hibernated actors when you size a host

A hibernated actor still counts toward `system.maxActors`. It uses 81 B of records in the host ([what an actor costs](https://tinyactors.dev/guides/capacity/index.md#what-an-actor-costs)).

The data of its pending delayed sends and of the events waiting in its queue stays in the host too. A pending delayed send wakes the actor when it falls due.

The [capacity guide](https://tinyactors.dev/guides/capacity/index.md) says how many actors a host holds and how much memory it needs.

<a id="at-scale"></a>

## Run two million actors with 1000 in memory

[`tools/stress.mjs`](https://github.com/tinyactors-dev/tinyactors-napi/blob/main/tools/stress.mjs) (`mise run stress`) runs this guide's pattern at scale, with the actors past the bound in SQLite.

Its 200,000 events went to actors drawn at random, so nearly every event woke one and the sweep sent another back. Each run woke 199,870 actors from the store.

Every sampled actor's count matched the events it was sent. After every eviction at most 1000 actors were resident.

| Runtime, datamodel | Populate (spawn and hibernate 2,000,000) | 200,000 events (woken, swept back) | Peak resident | Core's region | SQLite file |
|---|---|---|---|---|---|
| node, native | 48.2 s (41,500 a second) | 13.1 s (15,300 a second) | 307 MB (153 B per actor) | 164 MB (82 B per actor) | 378 MB |
| node, quickjs | 35.9 s (55,800 a second) | 12.1 s (16,500 a second) | 319 MB (159 B per actor) | 164 MB (82 B per actor) | 409 MB |
| bun, native | 39.6 s (50,600 a second) | 12.2 s (16,400 a second) | 300 MB (150 B per actor) | 164 MB (82 B per actor) | 378 MB |
| bun, quickjs | 34.2 s (58,400 a second) | 12.3 s (16,300 a second) | 287 MB (143 B per actor) | 164 MB (82 B per actor) | 409 MB |

Two million actors of a counter chart, at most 1000 resident, the rest in SQLite (`node:sqlite` under Node.js, `bun:sqlite` under Bun), then 200,000 events. One run of `tools/stress.mjs`, alone on the machine, 2026-11-20: Intel Xeon at 2.10 GHz, 4 CPUs, 16 GiB, Linux; Node.js 22.23.5, Bun 1.4.1.

Populating slows as the population grows: after each turn the sweep looks over every actor's slot, hibernated ones included. Events to a population that exists do not slow.
