Skip to content

Drizzle (PostgreSQL) Driver

The Drizzle driver persists events to a PostgreSQL database using Drizzle ORM. It is a recommended choice for production.

import { createEventStore, createAggregateRoot } from '@requence/event-sourcing/drizzle'
import { drizzle } from 'drizzle-orm/node-postgres'
const db = drizzle(process.env.DATABASE_URL!)
const eventStore = createEventStore({
database: db,
aggregateRoots: [userAggregateRoot],
})

The driver uses a dedicated event_sourcing PostgreSQL schema with the following tables:

TablePurpose
eventsAppend-only event log with position, stream, and metadata
checkpointsLast-processed position (and optimistic-concurrency version) per projection/process manager
aggregate_root_snapshotsCached aggregate state for fast rehydration
projection_snapshotsCached projection state for snapshot-based projections
projection_applied_eventsCounter for snapshot frequency tracking
encryption_keysWrapped data keys for encrypted fields (see Encryption keys)
encryption_master_keysWhen each master key was first seen, for rotation

The driver does not create the schema or the tables — neither autoInit nor init() runs any DDL. Create them through your own Drizzle migrations. The table definitions are exported from @requence/event-sourcing/drizzle/postgres:

import {
events,
checkpoints,
aggregateRootSnapshots,
projectionSnapshots,
projectionAppliedEvents,
encryptionKeys,
encryptionMasterKeys,
} from '@requence/event-sourcing/drizzle/postgres'

The simplest way is to re-export them from the schema file that drizzle-kit reads, so drizzle-kit generate includes them in your migrations:

src/db/schema.ts
export * from '@requence/event-sourcing/drizzle/postgres'
export const users = pgTable('users', { /* your read models */ })

drizzleKeyStore stores the data keys for encrypted fields in the encryption_keys table, each wrapped with a master key. Destroying a key deletes its row.

import { drizzleKeyStore } from '@requence/event-sourcing/drizzle/postgres'
const eventStore = createEventStore({
database: db,
aggregateRoots: [userAggregateRoot],
encryption: {
masterKeys: process.env.MASTER_KEYS, // comma-separated base64 keys, oldest first
keyStore: drizzleKeyStore(db),
},
})

Append a new key to MASTER_KEYS and deploy:

Terminal window
MASTER_KEYS=<old> # before
MASTER_KEYS=<old>,<new> # rotate
  1. Every instance can unwrap with both keys right away, but keeps wrapping new keys with <old> for a grace period (24 hours by default). Instances that only know <old> keep working while the rollout runs.
  2. After the grace period, new keys are wrapped with <new>, and a background job rewraps the existing keys onto it. Data keys and events stay unchanged.
  3. Optionally, on a later deploy, remove <old>. If keys are still wrapped with it, the event store refuses to initialize, so a key cannot be removed too early.

Change the grace period with masterKeyGracePeriod (milliseconds). It must be longer than your rollouts. To rotate right away after a leak, set it to 0; instances that only know <old> then fail on new keys until the rollout finishes.

Every instance caches the data keys it uses. With more than one instance, pass redisKeyInvalidation 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: [userAggregateRoot],
lock: redisLock(redis),
encryption: {
masterKeys: process.env.MASTER_KEYS,
keyStore: drizzleKeyStore(db),
invalidation: redisKeyInvalidation(redis),
},
})

It publishes the destroyed key ID on the event-sourcing:keys:destroyed channel (change it with { channel }) and subscribes on a duplicate of the client. Call close() on it at shutdown to close that connection. When an instance receives a 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.

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

  • Cached keys expire after keyCacheTtl milliseconds (5 minutes by default), so a missed message keeps a destroyed key usable for at most that long. Set it to false to keep keys until they are evicted.
  • 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, if that instance was disconnected.
import { redisLock } from '@requence/event-sourcing/redis'
import Redis from 'ioredis'
const redis = new Redis(process.env.REDIS_URL)
const eventStore = createEventStore({
// Required — Drizzle database instance or factory
database: db,
// Required — one or more aggregate roots
aggregateRoots: [user, project],
// Optional — distributed lock for multi-instance deployments
lock: redisLock(redis),
// Optional — disable automatic initialization
autoInit: false,
// Optional — callback invoked after events are appended
onEventsAppended(events) {
// e.g. broadcast via WebSocket
},
// Optional — replay and refresh progress callbacks
onProjectionReplay: { /* ... */ },
onProcessManagerRefresh: { /* ... */ },
// Optional — post-process events before persistence
postProcessEvent(event, aggregateRoot) {
return event
},
})