Skip to content

Persisting clients

BehavioralFsm tracks per-client state internally in a WeakMap, and machina doesn’t stamp anything onto the client object. The engine is entirely synchronous, without a storage concept of its own, and it doesn’t perform I/O. dehydrate() converts a client’s full FSM state into plain data, and rehydrate() converts it back. Your application’s repository layer does the actual load and save.

Keep persistence in one place: a repository that fetches a client and its FSM snapshot together, and saves them back together in one atomic write.

class CartRepository {
    async getCart(id: string): Promise<Cart> {
        const row = await store.carts.get(id); // { cart, fsm }, parsed however your storage parses
        const cart = deserializeCart(row.cart); // revive YOUR object: Dates, class instances, etc.
        cartFsm.rehydrate(cart, row.fsm); // silent placement, deferrals requeued, no revival needed
        return cart;
    }

    async saveCart(cart: Cart): Promise<void> {
        const fsm = cartFsm.dehydrate(cart); // throws here if defer args can't persist
        await store.carts.put(cart.id, { cart: serializeCart(cart), fsm }); // one atomic write
    }
}

The following properties make the pattern work:

  • dehydrate() throws at save time. If a handler deferred an input with a non-serializable argument, you find out immediately, and the error identifies the exact input and value path.
  • The client’s business data and its FSM state are saved in one write. There’s no window where one could be persisted without the other.
  • rehydrate() takes the parsed object. Whether your driver hands you parsed documents (MongoDB, Postgres jsonb) or strings you JSON.parse yourself (raw Redis) is your storage layer’s concern. The snapshot is guaranteed JSON-safe plain data and passes through any of those boundaries unchanged. Only your object may need revival, the step deserializeCart represents. A client that is plain data skips that step.

The service bracket: explicit load → handle → save

Section titled “The service bracket: explicit load → handle → save”

Machina’s API is entirely synchronous, and handle() doesn’t await anything. Async work (fetching, saving) belongs in the layer that calls into the FSM. A service method spells out the full bracket:

async function checkout(id: string) {
    const cart = await repo.getCart(id); // load
    cartFsm.handle(cart, "checkout"); // core API, synchronous, untouched
    await repo.saveCart(cart); // save
}

This bracket (load, handle, save) is the whole pattern, without hidden middleware or an implicit persistence hook on transitioned. You decide exactly when a save happens, and the failure modes follow from that decision. If saveCart throws, the in-memory cart object already reflects the new state while the durable copy doesn’t. Retry the save, or re-fetch and re-apply, the same as any other transactional write.

compositeState() plus the string form of rehydrate() is enough for a client with an empty deferred queue, because a state name is the complete description. A client with a queued deferred input needs more, because the queued input must make the round trip too, or it silently vanishes on restore.

dehydrate() returns everything machina tracks for a client as a plain, nested object, which mirrors the FSM hierarchy for clients with child FSMs:

const snapshot = cartFsm.dehydrate(cart);
// {
//   state: "validating",
//   deferred: [{ inputName: "applyDiscount", args: ["WELCOME10"], untilState: "checkout" }],
// }

Restoring is the object form of rehydrate(). It has the same silent-placement contract as the string form (lifecycle hooks and events are skipped), and the deferred queue gets requeued at every level:

cartFsm.rehydrate(cart, snapshot);
cartFsm.handle(cart, "advance"); // proceeds normally; "applyDiscount" replays once "checkout" is reached

For hierarchical FSMs, the walk is full-fidelity: dehydrate() captures each state whose _child has tracked the client at some point, beyond the one the client currently occupies. A child the parent left mid-task (powered on, or mid-retry) is captured under its declaring state name and restored the same way. The distinction matters because leaving a child’s state differs from resetting it. The child stays exactly where it was until the parent re-enters that state. At that point the reset transition fires the child’s stale _onExit and then its _onEnter (skipped if the child was already at its initialState). Anything still in that child’s deferred queue replays afterward. A restored client reproduces that sequence identically, matching one that stayed in memory.

  • Storage I/O is yours. dehydrate()/rehydrate() hand you plain data, and where it’s stored (Redis, Postgres, a file, a message queue) is entirely your call.
  • Identity is the object reference. Client state is tracked in a WeakMap keyed by the client object itself. The snapshot moves with your client through the repository. Horizontal scaling works by construction, without server affinity or a shared session store.
  • The API is synchronous. handle(), transition(), rehydrate(), and dehydrate() are all synchronous, a design decision that makes the state machine’s own logic simple and testable. Async belongs in the bracket around it.

Concurrent requests for the same client can still race. Each request loads its own snapshot and handles an input against its own in-memory copy. Both then save, and the second save silently clobbers the first. This is an application architecture problem, and machina’s API leaves it to you. A client that takes concurrent requests needs a single-writer discipline, such as a consistent-hash-routed worker or a per-entity mailbox. A database-level lock on the save works too. load → handle → save then runs as a serialized sequence for that entity, and the discipline belongs entirely in your service layer.