Skip to content

createEventStore

createEventStore is the central orchestrator of the library. It connects your aggregate roots to the underlying storage, manages event distribution to projections, process managers, and event listeners, and handles initialization and replay.

import { createEventStore } from '@requence/event-sourcing'

This is the core function, which takes the storage functions (loadEvents, appendEvents, checkpoint) directly. In most applications you use the createEventStore of a driver instead (e.g. @requence/event-sourcing/drizzle), which supplies those functions for you and takes a database instead. Everything else on this page — options, return value, transactions — applies to both.

function createEventStore<Root extends AnyAggregateRoot>(
params: EventStoreParams<Root>
): EventStore<Event, Root>

The function accepts a single configuration object:

ParameterTypeRequiredDescription
loadEventsLoadEvents✓Async generator that loads events from the underlying storage.
appendEventsAppendEvents✓Function that persists new events and returns them with assigned positions.
aggregateRootsRoot[]✓Array of aggregate root instances to register.
checkpointCheckpointMethods✓Methods for persisting projection/process manager checkpoints.
lockLockCreatorCustom locking strategy for aggregate root streams. Defaults to an in-memory lock with a 5-second TTL. Use redisLock from @requence/event-sourcing/redis for distributed deployments.
aggregateRootSnapshotAggregateRootSnapshotMethodsEnables snapshot support for aggregate roots.
projectionSnapshotProjectionSnapshotMethodsEnables snapshot support for projections.
postProcessEvent(event, aggregateRoot) => WrappedEventHook to mutate or decorate events before they are appended.
onProjectionReplayOnProgressCallbacks for tracking projection replay progress.
onProcessManagerRefreshOnProgressCallbacks for tracking process manager refresh progress.
autoInitbooleanWhen set to false, the event store will not initialize automatically. You must call .init() manually. Defaults to true.
encryptionEncryptionOptionsEnables encrypted fields. Required as soon as an aggregate root declares an encrypted field.

The encryption option configures encrypted fields. Without it, an event store whose aggregate roots declare an encrypted field refuses to initialize and never appends plaintext.

import { createEventStore } from '@requence/event-sourcing/drizzle'
import { drizzleKeyStore } from '@requence/event-sourcing/drizzle/postgres'
const eventStore = createEventStore({
database: db,
aggregateRoots: [user],
encryption: {
masterKeys: process.env.MASTER_KEYS,
keyStore: drizzleKeyStore(db),
},
})
OptionTypeDefaultDescription
masterKeysstring | Buffer | (string | Buffer)[] | undefined—Master keys that wrap the data keys, oldest first: a comma-separated string of base64 keys, a 32-byte buffer, or an array of either. Generate one with openssl rand -base64 32. If missing, an insecure development key is used and a warning is logged; with NODE_ENV=production, a missing key is an error.
keyStoreKeyStore—Where the wrapped data keys are stored: memoryKeyStore(), drizzleKeyStore(db) or surrealKeyStore(db).
masterKeyGracePeriodnumber24 hoursMilliseconds a newly added master key waits before it wraps new keys and existing keys are rewrapped onto it. Must be longer than a rolling deploy. See Rotating the master key.
invalidationKeyInvalidationBusno-opTells other instances about destroyed keys. Required with more than one instance, see below.
keyCacheTtlnumber | false5 minutesMilliseconds a data key stays in an instance’s cache. false keeps keys until they are evicted.

On initialization, the event store refuses to start if stored keys are wrapped with a master key that is not configured, so a master key cannot be removed too early.

Aggregate root streams are automatically locked before any command is executed. This prevents concurrent modifications to the same stream and eliminates event stream version collisions.

By default, the library uses an in-memory mutex (via async-mutex) with a 5-second TTL. This is suitable for single-process deployments.

For multi-instance deployments, pass redisLock as the lock parameter to coordinate across all instances via Redis:

import { createEventStore } from '@requence/event-sourcing/drizzle'
import { redisLock } from '@requence/event-sourcing/redis'
import Redis from 'ioredis'
const redis = new Redis(process.env.REDIS_URL)
const eventStore = createEventStore({
database: db,
aggregateRoots: [user, project],
lock: redisLock(redis), // distributed lock via Redis
})
ParameterTypeDefaultDescription
clientRedis (ioredis)—An ioredis client instance.
defaultTtlnumber5000Lock time-to-live in milliseconds.

The implementation uses atomic SET NX PX for acquisition and Lua scripts for safe extend/release, preventing split-brain issues.

The lock and the storage adapter’s version check are two layers of the same story: the lock avoids the race by serializing writers, and the version check catches it if a race slips through (raising a ConcurrencyError). A race can still slip through when a lock’s TTL lapses mid-command, or in single-instance deployments where no distributed lock is configured.

For those residual cases, opt in to recovery at the call site with settled({ maxRetries }): the stream is reloaded and the commands re-applied against the current version instead of the error surfacing.

await settingsRoot.loadStream('global').update({ theme: 'dark' }).settled({
maxRetries: 5,
})

Retry is opt-in per call (default 0) rather than a global setting, because it is only safe for pure command handlers and some flows — such as a fixed-id newStream(...) used for idempotent create — deliberately rely on the ConcurrencyError surfacing.

Inside a process manager or a transaction, settled() cannot be called — the surrounding scope settles dispatched streams automatically when it completes. Declare the retry defaults on that scope instead: createProcessManager(name, { settled }) or transaction(handler, { settled }).

redisLock makes the write path safe to scale: any number of instances can accept commands, because stream appends are guarded by both the distributed lock and the storage adapter’s optimistic-concurrency check (a ConcurrencyError is raised if two instances race on the same stream version).

The read/reaction path works differently, and it is important to understand how events reach your handlers when scaling:

  • Events are delivered to projections, process managers, and event listeners only on the instance that appended them. There is no built-in cross-instance event bus. On startup, each instance also catches up from its checkpoint, but after that it only sees events it writes itself.
  • The same applies to separate processes such as seed or migration scripts. A script that appends events only updates read models if it registers the same projections itself (and waits for eventStore.isReady() / settled() before exiting). A server that is already running does not pick those events up until it restarts.
  • Because each event is therefore processed by exactly one instance, projections and listeners that write to a shared store (a SQL read model, Redis, a search index) or perform idempotent side effects stay consistent — every event is applied exactly once, with no duplication.

Given that model, the recommended topology is:

ComponentSafe to run on N instances?Notes
Command / write handlers✅ YesUse redisLock. Concurrency is enforced by the lock + storage adapter.
Projections → shared read model✅ YesMake writes idempotent (upsert by id). The checkpoint cursor is shared and advances monotonically.
Event listeners (side effects)✅ YesEach event fires its side effect once, on the writing instance.
Projections holding in-memory state⚠️ NoOnly the writing instance’s copy updates. Back the projection with a shared store instead.
Stateful process managers (.withState())⚠️ With careState is folded into a shared checkpoint under optimistic concurrency (see below).
Push delivery (WebSocket/SSE) to connected clients⚠️ Needs a busUse onEventsAppended to fan out to a message broker; the writing instance only reaches its own clients.

Stateful process managers across instances

Section titled “Stateful process managers across instances”

Process-manager state lives in the shared checkpoint and is reloaded at the start of every processing session. When two instances fold events into the same process manager concurrently, writes use optimistic concurrency: if another instance advanced the checkpoint in the meantime, the losing write is rejected, the latest state is reloaded, and the event is re-folded on top of it. This prevents lost updates without a lock.

Every instance caches the data keys it uses. With more than one instance, pass redisKeyInvalidation as encryption.invalidation, so destroyKey() on one instance reaches all of them:

import { redisKeyInvalidation, redisLock } from '@requence/event-sourcing/redis'
import Redis from 'ioredis'
const redis = new Redis(process.env.REDIS_URL)
const eventStore = createEventStore({
database: db,
aggregateRoots: [user],
lock: redisLock(redis),
encryption: {
masterKeys: process.env.MASTER_KEYS,
keyStore: drizzleKeyStore(db),
invalidation: redisKeyInvalidation(redis),
},
})

When an instance receives a destroyed key ID, it evicts the key from its cache and deletes the snapshots of its own projections that use snapshots and handle an encrypted field.

ParameterTypeDefaultDescription
clientRedis (ioredis)—An ioredis client. Subscribing uses a duplicate of it, because a subscribed connection cannot run other commands.
options.channelstring'event-sourcing:keys:destroyed'The pub/sub channel. The message is the key ID.

Call close() on the returned bus at shutdown to close the subscriber connection. The passed client stays open.

Redis pub/sub does not store messages: an instance that is disconnected while a key is destroyed misses the message.

  • Its cached key still expires after keyCacheTtl (5 minutes by default). The TTL bounds how long a destroyed key stays usable on an instance that missed the message.
  • Snapshots are not covered by the TTL. Snapshots of a projection that is only registered on the instance that missed the message stay in place and may hold the destroyed plaintext. Call destroyKey() again on an instance that registers that projection, or delete its snapshots.

Returns an EventStore object with the following methods:

Creates and registers a new Projection with the given name. Each name must be unique within the event store.

const userList = eventStore.createProjection('user-list')
.withEventHandlers({
async onUserCreated({ streamId, payload }) { /* ... */ }
})

Creates and registers a new Process Manager with the given name.

const cascadeDelete = eventStore.createProcessManager('cascade-delete')
.withEventHandlers({
async onOrganizationDeleted({ payload }) { /* ... */ }
})

Streams that handlers dispatch commands on are settled automatically when the handler completes (explicit settled() calls are not allowed inside a process manager). The optional second parameter declares defaults for those auto-settles:

// Unattended cascades: recover from residual concurrency races
// instead of surfacing them, up to 3 reload-and-re-apply attempts.
const cascadeDelete = eventStore.createProcessManager('cascade-delete', {
settled: { maxRetries: 3 },
})
OptionTypeDescription
settledSettledOptionsDefaults applied when the process manager auto-settles dispatched streams — see Retrying on concurrency conflicts.

Creates and registers a new Event Listener with the given name.

const auditLog = eventStore.createEventListener('audit-log')
.withEventHandlers({
async onUserCreated({ payload }) { /* ... */ }
})

Returns a registered aggregate root by its type name. Fully type-safe — the return type narrows based on the provided type string.

const userRoot = eventStore.getAggregateRoot('user')

Executes the given async handler inside a transaction. Commands on all streams dispatched within the handler are validated first; events are only appended once every command succeeded. If any command (or the handler itself) throws, no stream appends anything.

await eventStore.transaction(async () => {
const org = orgRoot.newStream()
org.create({ name: 'Acme' })
const user = userRoot.newStream()
user.create({ name: 'Alice', orgId: org.streamId })
})

Streams dispatched inside the handler are settled automatically when the transaction completes (explicit settled() calls are not allowed there). The optional second parameter declares defaults for those auto-settles:

await eventStore.transaction(async () => {
// ...
}, { settled: { maxRetries: 3 } })
OptionTypeDescription
settledSettledOptionsDefaults applied when the transaction auto-settles dispatched streams — see Retrying on concurrency conflicts.

When the returned promise resolves, every dispatched stream is settled: its events are persisted and all projections, process managers, and event listeners have processed them. Read models are up to date at that point.

Manually initializes the event store. Required when autoInit is set to false. Returns the event store instance for chaining.

const store = createEventStore({ autoInit: false, /* ... */ })
await store.init()

Returns a promise that resolves when all projections and process managers have finished their initial catch-up hydration.

await eventStore.isReady()
// All projections and process managers are now up to date

Performs a full rebuild of all replayable projections and stateful process managers. This re-reads every event from the store and re-applies them from scratch.

await eventStore.rebuild()

Destroys the data key of keyId (crypto-shredding). Requires the encryption option.

await eventStore.destroyKey(`user:${userId}`)

Once the promise resolves:

  • the key is deleted from the key store and evicted from this instance’s cache, and other instances were notified through encryption.invalidation;
  • every field encrypted under keyId, in every event, reads as null in projections, process managers, listeners and decryptEvent();
  • the snapshots of projections registered here that use snapshots and handle an encrypted field are deleted, so they are rebuilt from events.

destroyKey() is idempotent. It does not change read models: remove the data from them yourself, for example with an erasure event that your projections handle. Aggregate state is not affected, because aggregates only ever hold the ciphertext. A later event with the same key ID gets a fresh data key.

Decrypts a raw event as loaded from storage, for example for an export or a support tool. Returns the event with its encrypted fields as plaintext, or null if their key was destroyed. The passed event is not changed.

import { fetchEvents } from '@requence/event-sourcing/drizzle'
const events = await fetchEvents(db)
const decrypted = await Promise.all(events.map((event) => eventStore.decryptEvent(event)))

Throws a DecryptionError if a value cannot be decrypted although its key exists, for example because the ciphertext was tampered with.

import { createEventStore } from '@requence/event-sourcing/drizzle'
import { drizzle } from 'drizzle-orm/node-postgres'
import userRoot from './aggregates/user.ts'
import orgRoot from './aggregates/organization.ts'
const db = drizzle(process.env.DATABASE_URL!)
const eventStore = createEventStore({
database: db,
aggregateRoots: [userRoot, orgRoot],
})
await eventStore.isReady()

The onProjectionReplay and onProcessManagerRefresh parameters accept an object with the following optional callbacks:

type OnProgress = {
begin?: (name: string) => void
progress?: (name: string, index: number, event: BaseOutputEvent) => void
end?: (name: string) => void
}