콘텐츠로 이동
한국어

Durable state

이 콘텐츠는 아직 번역되지 않았습니다.

DurableStateActor<Command, S> is the “I just want the current value to survive” persistence model. No event log, no replay — just a snapshot of the state, overwritten on each persist(newState).

DurableStateActor

onCommand(command)

read this.state

next = transform(...)

await this.persist(next)

revision++

Durable State Store

Compared to PersistentActor:

AspectPersistentActorDurableStateActor
What’s storedEvery event everThe current state snapshot
RecoveryReplay eventsLoad the snapshot
Storage costGrows with eventsConstant per actor
HistoryYesNo
Audit / time travelYesNo
Concurrent writesSequentialOptimistic (revision check)

Pick durable state when history isn’t useful — feature flags, last-known configs, “current cart contents” without the audit trail.

import { ActorSystem } from 'actor-ts';
import { DurableStateActor, DurableStateOptions } from 'actor-ts/persistence';
import { InMemoryDurableStateStore } from 'actor-ts/persistence';
import { match } from 'ts-pattern';
type AddCommand = { kind: 'add'; sku: string };
type RemoveCommand = { kind: 'remove'; sku: string };
type ViewCommand = { kind: 'view'; replyTo: ActorRef<State> };
type CartCommand = AddCommand | RemoveCommand | ViewCommand;
type State = { items: string[]; };
class Cart extends DurableStateActor<CartCommand, State> {
constructor(options: DurableStateOptions<State>) { super(options); }
override async onCommand(command: CartCommand): Promise<void> {
await match(command)
.with({ kind: 'add' }, (c) => this.onAdd(c))
.with({ kind: 'remove' }, (c) => this.onRemove(c))
.with({ kind: 'view' }, (c) => this.onView(c))
.exhaustive();
}
private onAdd(c: AddCommand): Promise<void> {
return this.persist({ items: [...this.state.items, c.sku] });
}
private onRemove(c: RemoveCommand): Promise<void> {
return this.persist({ items: this.state.items.filter(s => s !== c.sku) });
}
private onView(c: ViewCommand): void {
c.replyTo.tell(this.state);
}
}
// Setup:
const system = ActorSystem.create('demo');
const store = new InMemoryDurableStateStore();
const durableStateOptions = DurableStateOptions.create<State>()
.withPersistenceId('cart-user-42')
.withStore(store)
.withEmptyState(() => ({ items: [] }));
const cart = system.spawn(
() => new Cart(durableStateOptions),
'cart',
);
cart.tell({ kind: 'add', sku: 'book-1' });
cart.tell({ kind: 'add', sku: 'book-2' });
// After restart: `this.state.items` is ['book-1', 'book-2'] again.
type DurableStateOptionsType<S> = {
persistenceId: string;
store?: DurableStateStore;
emptyState: () => S;
};

Three fields, one of them optional:

  • persistenceId — the key under which the state is stored. Like PersistentActor, one ID per logical entity (cart-user-42, flags-region-eu, …), and subject to the same rules on what an ID may contain: non-empty, at most 255 characters, no / or \, no control characters. DurableStateOptionsValidator checks them in the constructor — earlier than preStart, because an ID that can never address a record is worth refusing before the actor is wired to a store — and reports a violation as an OptionsError on the persistenceId field.
  • store — the DurableStateStore implementation (in-memory, SQLite, object-storage, custom). Optional: left unset, the actor uses the store the system selected — see Selecting the store from configuration.
  • emptyState() — factory invoked when no record exists yet (first run, deleted state). Provides the initial value.

Pass them through the () => new Cart({...}) factory. The settings can vary per actor incarnation (different IDs for different users, same store).

Durable state used to be the one persistence contract with no plugin registry: every registerXxxPlugins(...) helper built its store eagerly and handed it back, so the only way to reach it was to thread that instance through your own code. It is now selected the same way the journal and the snapshot store always were:

actor-ts.persistence.durable-state {
plugin = "actor-ts.persistence.durable-state.sqlite"
sqlite { path = "/var/lib/my-app/app.db" }
}
const systemOptions = ActorSystemOptions.create().withPersistence({
plugins: [(persistence) => registerSqlitePlugins(persistence)],
});
const system = ActorSystem.create('demo', systemOptions);
// No store in the options — the actor takes the configured one.
const cartFactory = () => new Cart(
DurableStateOptions.create<State>()
.withPersistenceId('cart-user-42')
.withEmptyState(() => ({ items: [] })),
);

The default is the in-memory reference store, exactly as it is for the journal, so an app that configures nothing behaves as it always did. A withStore(...) in the options still wins — that is the right call for a store the application owns, such as a handle shared with something else, one of several stores in one process, or a spy in a test. What changed is that it stopped being the only way to have one.

Every backend that ships a durable-state store registers one: SQLite, the five relational backends, MongoDB, DynamoDB and object storage. Cassandra is the one exception, and it is an honest one — the framework has no Cassandra durable-state store, so that backend has two plugin axes where the rest have three.

An unregistered plugin id is refused rather than silently replaced: ext.durableStateStore throws Unknown durable-state plugin '…' naming the id, the same failure mode the other two axes have had since #377. With the boot-time open on, the default, the system resolves the selected stores inside create, so the refusal fails the startup — see opening the stores at startup.

A value written in place of the block is refused too, naming the key. actor-ts.persistence.durable-state = "actor-ts.persistence.durable-state.sqlite" looks like a selection, but it replaces the block that holds the selector, and it used to be read as no selection at all: the store stayed in memory, the startup reported ready, and the state was gone on the next restart. It now fails the startup with a ConfigError saying that actor-ts.persistence.durable-state must be a block with a plugin field — write plugin = "…" inside the block, as above. The same holds for the journal and snapshot-store blocks and for actor-ts.persistence itself, and a selector holding no id at all — null, a block, a list — fails every axis, not only its own.

A misspelt key is refused as well, naming the full key. plugn = "…" in the block is read by nothing, and it used to leave plugin at the in-memory id reference.conf ships, so the system started on the in-memory store with no error and no warning, exactly as if nothing had been selected. It now fails the startup with a ConfigError naming actor-ts.persistence.durable-state.plugn, and so does any other value in the block beside plugin — a plug-in’s setting written a level too high among them — and any key directly under actor-ts.persistence that the framework does not read. Correct the spelling, or move the setting into its plug-in’s block. A misspelt leaf inside a plug-in’s own block is that plug-in’s to refuse.

A selected SQLite store with no path is refused as well, and earlier: when registerSqlitePlugins runs it checks every store the configuration selects — except one that withPersistence sets in code, which replaces the selection and leaves it unbuilt — so create throws with an error that names actor-ts.persistence.durable-state.sqlite.path. Give the block a path — ":memory:" for an in-memory database — or hand the plugin a database in code.

Inside the actor’s handlers:

this.state // current state value — read anywhere
this.revision // monotonic counter, bumped on every persist
this.persist(s) // overwrite the stored state with `s`, returns Promise<DurableStateRecord<S>>

this.state is synchronous — the framework loads the state in preStart, and state returns whatever’s currently set in memory. Before the first persist (or load), it returns emptyState().

this.persist(next) writes the new state to the store with the current revision + 1. Returns once the store acknowledges. Inside onCommand, await it before treating the next state as authoritative.

State is stored in the tagged JSON tree format on every backend, so Date / Map / Set / bigint / Uint8Array round-trip as real instances — see what events and state may contain.

try {
await this.persist(next);
} catch (e) {
if (e instanceof DurableStateConcurrencyError) {
// Another writer beat us — reload and retry, or surface to the user.
}
}

When two writers update the same persistenceId concurrently, the store’s revision check rejects the second one with DurableStateConcurrencyError. Strategies:

  • Avoid the problem — make sure only one actor at a time writes to a given persistenceId. This is usually trivial: each cart-user-42 has one actor, on one node (via sharding or singleton).
  • Reload and retry — catch the error, reload state, recompute the new value, persist again. Works when the operation is idempotent.
  • Surface to caller — reply with an error; let the caller decide whether to retry.

For most actor-system patterns, concurrent writes shouldn’t happen — one entity per persistenceId, addressed via routing or sharding. If you see concurrency errors in production, that usually means two actors are writing the same key, which is a routing bug.

When durable state wins over persistent actor

Section titled “When durable state wins over persistent actor”

Three signals you’ve picked the right tool:

  • The state shape is simple (a single object, a small map). Overwriting the whole thing is cheap.
  • You don’t need an event stream — no projections, no audit log, no “show me how we got here” requirements.
  • Reads dominate writes — every read is a synchronous this.state, no replay.

Three signals you should reach for PersistentActor instead:

  • History matters — auditing, regulatory, “show the user a changelog.”
  • State is large and changes are small — writing the whole state on every change is wasteful; appending small events is cheaper.
  • You want projections — read-side views that need the event stream.

Like PersistentActor, durable state supports schema evolution through an adapter:

import { StateAdapter } from 'actor-ts/persistence';
const v1ToV2Adapter: StateAdapter<StateV2> = {
manifest: () => 'Cart',
toJournal: (state) => ({ manifest: 'Cart', version: 2, payload: state }),
fromJournal: (stored) => stored.version === 1
? migrate(stored.payload as StateV1)
: stored.payload as StateV2,
};
class Cart extends DurableStateActor<...> {
protected stateAdapter() { return v1ToV2Adapter; }
}

The persisted record gets wrapped in a { _v, _t, _e } envelope; on load, the adapter’s fromJournal runs to migrate older versions. See Migration overview for the full story.

Three per-actor overrides are available:

class Sensitive extends DurableStateActor<Command, State> {
protected encryption() {
return { mode: 'client-aes256-gcm' as const, masterKey, info: 'acme/prod/durable-state/v1' };
}
protected compression() { return { algorithm: 'gzip' as const }; }
protected integrity() {
return { mode: 'hmac-sha256' as const, integrityKey };
}
}

The object-storage and SQL durable-state stores read these. The object-storage store and the SQL family — SQLite, Postgres, MariaDB, MSSQL, libSQL and D1 (#1802) — honour all three hooks on write and on read. The SQL stores keep the schema: the record goes into the same payload column, as the object-storage frame in base64 behind an ats1: prefix, bound to the persistence id and the revision, so a payload paired with another revision fails to decrypt. An actor with encryption() refuses a row that is not encrypted, plaintext JSON included, because that row is either older than the hook or was written by someone with access to the table. To turn a hook on over existing records, build the store with withAllowPlaintextRows(true): the next persist rewrites each row sealed, and the option comes out again afterwards. What no key can detect is a whole row — revision and payload together — put back to an older copy.

The other three durable-state stores accept the options and never look at them — but they say so, through a persistenceOptionSupport declaration the framework checks at actor start (#960). On in-memory, Mongo and DynamoDB, encryption() or integrity() refuses the actor before it starts, with an UnsupportedPersistenceOptionError naming the store and the field. The refusal comes ahead of preStart’s load rather than at the first write, deliberately: a durable-state actor reads before it writes, and reading against a store that cannot decrypt would hand it a plaintext record it believes was ciphertext. compression() is a performance hint, so it warns once and the record is written uncompressed; { mode: 'none' } is accepted everywhere.

Configuring either authenticator — client-aes256-gcm or hmac-sha256 — buys a second thing besides privacy and tamper-evidence: it is what gives the object-storage store move detection. Every write binds the body to the storage key it goes to, so a record that later turns up under another entity’s key is refused, with nothing to switch on. Without one — the default — nothing at that layer notices: a durable-state body is { revision, state, timestamp } and names no entity, and load answers with the persistenceId you asked for. The snapshot store is not in the same position, and What encryption does not cover is where the asymmetry is set out.

See Object storage encryption for the durable-state encryption story and per-actor policies for all three hooks.

The DurableStateActor API reference covers the full surface.