Skip to content

    Concepts12

    Long streams close their books

    What to do in Bounda with a stream that keeps growing, an account or the stock of a SKU, why closing the books comes before snapshots, and how snapshots work when a stream has nothing to close, with a validity the runtime checks itself.

    Every command in Bounda loads its aggregate’s whole stream and folds it: begin for the first event, evolve for each one after, every upcaster in the chain on the way. For an order, with its dozen events, that costs nothing. For a bank account or the stock of a SKU, which gain events every day and never end, the cost grows with the stream, forever. The usual answer is a snapshot. Bounda’s answer is, first, a different model: a stream that never ends is usually a business period that nobody has named yet; close it, and open the next one carrying only what it needs.

    Which streams those are is measured, not guessed: the bounda.fold.events histogram records how many events each load folds, per aggregate type (observability), and an aggregate whose numbers keep climbing is the one whose books to close or, with nothing to close, the one to give snapshots.

    Accountants do not recompute a balance from the day the account was opened. They close a period, carry the closing balance forward as the opening balance of the next one, and leave the old period alone. In Bounda that is an aggregate per period, ledger, with a predictable id such as acc-42:2026-10, so whoever posts an entry knows from the date which ledger to address:

    app/domain/ledger/ledger-opened.tsTypeScript
    import type { Event } from "./+types/ledger-opened";
    export const payload = ({ z, notPersonal }: Event.PayloadArgs) =>
    z.object({
    accountId: notPersonal(z.string()),
    period: notPersonal(z.string()),
    balance: z.number(),
    });
    export const begin = ({ event }: Event.BeginArgs) => ({
    status: "open" as const,
    accountId: event.payload.accountId,
    balance: event.payload.balance,
    });

    EntryPosted folds each movement into balance. The closing event is the summary, with what the next period needs and nothing more:

    app/domain/ledger/commands/close-ledger.tsTypeScript
    import type { Command } from "./+types/close-ledger";
    export const payload = ({ z, notPersonal }: Command.PayloadArgs) =>
    z.object({ ledgerId: notPersonal(z.string()), nextPeriod: notPersonal(z.string()) });
    export const rejections = ({ command }: Command.RejectionsArgs) => ({
    NotOpen: `Ledger ${command.aggregateId} is not open`,
    });
    export const handler = ({ command, state, events, reject }: Command.HandlerArgs) => {
    if (state.status !== "open") return reject("NotOpen");
    const { nextPeriod } = command.payload;
    return [events.ledgerClosed({ accountId: state.accountId, nextPeriod, balance: state.balance })];
    };

    A policy opens the next period from it:

    app/domain/ledger/policies/open-next-on-ledger-closed.tsTypeScript
    import type { Policy } from "./+types/open-next-on-ledger-closed";
    export const handler = async ({ event, commands }: Policy.HandlerArgs) => {
    const { accountId, nextPeriod: period, balance } = event.payload;
    await commands.openLedger({ ledgerId: `${accountId}:${period}`, accountId, period, balance });
    };

    openLedger returns [] when that ledger already exists, so the policy running twice changes nothing; postEntry rejects on a ledger that is not open. The closing itself can be a scheduled command at the end of the month, a process deadline, or an operator’s action: the domain decides when a period ends, which is the point. Each stream now holds one month of one account, and every command folds that month alone, while the closed ones stay in the event store for a read model that shows the account across years. The same shape fits a SKU’s stock with a stock-take per period, or a cashier’s shift.

    A snapshot stores the folded state so that the next load starts from it instead of from the first event. It is a cache, and a cache can be stale. The question is what a stale one breaks.

    A stale read model shows wrong rows. That is bad, and it is repairable: bounda rebuild projects the history again into a fresh table, and the history never changed. A stale snapshot is the state commands decide from. A handler that reads it accepts what it should reject, or computes a balance from a number that is no longer right, and the events it returns are stored as facts. The next fold, even a correct one, starts from those facts, and no rebuild removes an event. A bad snapshot does not show old data; it writes wrong history, for as long as it is used.

    Snapshots go stale for ordinary reasons: an evolve fixed, a field added to begin, a new upcaster, a state.ts with another initial value. Any deploy that changes how the state is folded makes every stored snapshot a fold by code that no longer exists. Axon asks a person to notice: it filters snapshots by the @Revision of the aggregate class, which its reference says to adjust on every deployment that changes the aggregate’s state. Bounda’s state is inferred by the generator and carries no version a person maintains, and a version someone has to remember to bump is the bug waiting for the one deploy where they forget.

    So Bounda’s snapshots are a cache of the fold, never the source of truth, with a validity the runtime checks itself. One that is missing, written by other code, unreadable or doubtful is ignored, and the stream is folded from the start, with the same result. They are opt-in per aggregate, for the stream that has nothing to close.

    bounda.config.tsTypeScript
    runtime: {
    overrides: {
    account: { snapshot: { every: 200 } },
    },
    },

    every sets how often a stream is snapshotted: each time its version reaches a multiple of every, the subscriber writes a snapshot at the head it finds, and between two it rests, writing nothing, like any subscriber. A subscriber named snapshot:account follows the global stream like a projection does and writes the snapshots in the background, in the worker role or an app from createTestApp after runUntilIdle(), so no command ever waits for one: a command loads the snapshot, folds the events after it and appends as before. The first deploy with snapshots walks the whole history and writes one for every stream long enough, so the streams that hurt today are covered without a migration. app.getLag() reports the subscriber like any other. A command dispatched again with the same idempotencyKey is answered from what the first one recorded, without loading the aggregate, so it reads no snapshot and writes none.

    The generator computes a fingerprint of every aggregate’s state and writes it to the registry as stateFingerprint: a digest of state.ts, of every event module with its upcasts, of every module those reach through relative imports, and of the state type it inferred. A snapshot is written under that fingerprint and used only under the same one, so a change to any of those files, a reformat or a comment included, retires every snapshot of the aggregate at the next deploy: each stream is folded from its first event once, and the subscriber writes a fresh snapshot the next time it reads that stream, at the latest when the stream reaches its next multiple of every. Nobody decides when; the cost is one slow load per stream, and a wrong state is never decided from.

    What the fingerprint cannot see is a module reached through a package or a path alias such as ~/lib/money, since the generator follows relative paths only. When one of those changes what the state folds to, raise snapshot.version, which is part of what the snapshot is valid for too:

    TypeScript
    account: { snapshot: { every: 200, version: 2 } },

    A snapshot is used only when its fingerprint is the aggregate’s, it reads back, and the stream reaches its version; one that reads badly or is past the stream’s head is dropped. On top of that, snapshot.verify, 0.01 by default, is the share of loads from a snapshot that are checked against a fold of the whole stream: a snapshot that folds to another state is logged, dropped and not used, and the command goes on with the state of the stream. Such a difference means the fold is not a function of the events alone, an evolve reading the clock or a module variable, which is worth knowing however the state is loaded. The bounda.snapshots counter says what every load found: used, verified, mismatch, missing, stale, unreadable or ahead (observability).

    An app from createTestApp checks every load and throws SnapshotError instead of dropping the snapshot, from the command that loaded it or from runUntilIdle() when the subscriber met it. A test suite that runs its aggregates with snapshot configured therefore proves their folds deterministic (testing).

    The state is kept with its types: Date, Map, Set, bigint, undefined, RegExp and nested plain objects and arrays come back as they were. A class instance or a function in the state cannot be kept: the subscriber logs it and writes no snapshot for that stream, and a test app throws SnapshotError from runUntilIdle(). Keep the state to data.

    The state is kept as it was folded, in the clear, personal fields included. Each snapshot names the people whose fields it holds and the key it read each one under, and forgetting one of them removes their snapshots in the same transaction that removes their key, so no snapshot keeps what the events no longer show; one folded before that transaction is never written after it, even once the person has a new key.

    • Speed up a rebuild. A rebuild runs projections over the global stream; it never folds an aggregate, so an aggregate’s snapshot saves it nothing. What would make a large rebuild faster is projecting the history in segments, a different piece of work.
    • Raise the ceiling. A store (the event store of one database, PostgreSQL schema or Durable Object, with everything that hangs off it) has one writer at a time, and a snapshot saves a read, not a commit. More throughput comes from one store per tenant.
    • Replace closing the books. A stream with a period has a natural end and a state the next period starts from; a snapshot keeps a stream without one loadable, while the stream itself keeps growing and every projection of it still reads it whole.
    • Marten treats a snapshot as a projection of a single stream: Snapshot<T> registered as Inline is updated in the transaction that appends the events, and stored as an ordinary document. Marten 8 also offers stream compacting, which replaces a stream’s old events with one event holding the state; its documentation offers it for a stream modelled longer than it should have been, and its own example admits that closing the books was the better answer.
    • EventStoreDB, now KurrentDB, had no built-in snapshotting when Greg Young answered on its forum in 2016. He called snapshots a versioning cost many systems do not want, since adding a field means deleting and rebuilding them all. Kurrent’s blog, in a post by Oskar Dudycz, says reading a few dozen events is not a significant overhead and that needing snapshots may hint at a flaw in the model, and it puts closing the books first and snapshots last.
    • Axon creates snapshots from a trigger; the one it ships fires when loading an aggregate takes more events than a threshold, and the snapshotter, best run on a thread of its own, stores the aggregate instance itself. The @Revision filter above is what keeps old snapshots out after a change, as long as someone changes the revision.
    • Oskar Dudycz calls short streams the most important modelling practice in event sourcing and closing the books its main enabler; snapshots, he writes, get harder to keep consistent with the events as the model grows, while a stream with few events and no lifecycle can live long.
    • A stream with no period and many events. If the business has nothing to close, a snapshot keeps each command’s fold to the events since the last one; a projection or a read of the stream still goes through all of it.
    • The moment between periods. A command writes one stream, so the next ledger opens when the policy runs, after the closing commits, not in the same transaction. An entry posted in between is rejected and retried by its caller.
    • Finding the open instance without a predictable id. When periods have no calendar, the current one is found through a read model, which is eventually consistent; the rejection on a closed ledger keeps a stale answer from writing anything.