Skip to content

Personal Data and Erasure

Events are immutable: the library never updates or deletes them, and the Drizzle driver even restricts the events table to inserts. That conflicts with data protection law, such as the GDPR (German: DSGVO) “right to erasure”, as soon as events contain personal data like names, email addresses or phone numbers.

This guide uses encrypted fields to solve it: personal fields are stored encrypted under a key per person, and erasing a person destroys that key. The events stay untouched, but the personal data in them can never be decrypted again, including in future replays.

Encrypt every personal field under the key ID user:<userId>:

user.ts
import { createAggregateRoot, type EncryptedFieldOptions } from '@requence/event-sourcing'
const personalData: EncryptedFieldOptions = {
keyId: ({ streamId }) => `user:${streamId}`,
}
export const user = createAggregateRoot('user')
.withInitialState({ exists: false, erased: false })
.withEvents(({ z, encrypted }) => ({
UserRegistered: z.object({
name: encrypted(z.string(), personalData),
email: encrypted(z.email(), personalData),
plan: z.enum(['free', 'pro']),
}),
UserEmailChanged: z.object({
email: encrypted(z.email(), personalData),
}),
UserPersonalDataErased: z.object({}),
}))
.withEventHandlers((state) => ({
onUserRegistered() {
state.exists = true
},
onUserPersonalDataErased() {
state.erased = true
},
}))
.withCommands((state, event) => ({
register(data: { name: string; email: string; plan: 'free' | 'pro' }) {
if (state.exists) {
throw new Error('User already exists')
}
return event('UserRegistered', data)
},
changeEmail(email: string) {
if (!state.exists || state.erased) {
throw new Error('User does not exist')
}
return event('UserEmailChanged', { email })
},
erasePersonalData() {
if (!state.exists || state.erased) {
return
}
return event('UserPersonalDataErased', {})
},
}))

Commands take plain values; the library encrypts them before the event is stored. plan is not personal and stays readable, so statistics keep working after an erasure.

The aggregate’s own state only records that a user exists. Aggregate event handlers only see ciphertext, so business rules must not depend on encrypted fields.

eventStore.ts
import { createEventStore } from '@requence/event-sourcing/drizzle'
import { drizzleKeyStore } from '@requence/event-sourcing/drizzle/postgres'
import { drizzle } from 'drizzle-orm/node-postgres'
import { user } from './user'
export const db = drizzle(process.env.DATABASE_URL!)
export const eventStore = createEventStore({
database: db,
aggregateRoots: [user],
encryption: {
masterKeys: process.env.MASTER_KEYS, // openssl rand -base64 32
keyStore: drizzleKeyStore(db),
},
})

Keep MASTER_KEYS in a secret manager. With more than one instance, also pass invalidation: redisKeyInvalidation(redis), see Running multiple instances.

3. Handle null in projections and process managers

Section titled “3. Handle null in projections and process managers”

Projections receive plaintext, or null once the user’s key was destroyed. Read model columns for personal data must be nullable:

usersProjection.ts
import { eq } from 'drizzle-orm'
import { db, eventStore } from './eventStore'
import { users } from './tables'
eventStore
.createProjection('users')
.withEventHandlers({
async onUserRegistered({ streamId, payload }) {
await db.insert(users).values({
id: streamId,
name: payload.name, // string | null
email: payload.email,
plan: payload.plan,
})
},
async onUserEmailChanged({ streamId, payload }) {
await db.update(users).set({ email: payload.email }).where(eq(users.id, streamId))
},
async onUserPersonalDataErased({ streamId }) {
await db.update(users).set({ name: null, email: null }).where(eq(users.id, streamId))
},
})
.withReplay({
async deleteAll() {
await db.delete(users)
},
})

Process managers and listeners must skip side effects when a value is null, because a refresh after an erasure delivers the old events again:

eventStore.createProcessManager('welcome-email').withEventHandlers({
async onUserRegistered({ payload }, { refreshing }) {
if (refreshing || payload.email === null) {
return
}
await sendWelcomeEmail(payload.email)
},
})

Record the erasure as an event first, then destroy the key:

erasePersonalData.ts
import { eventStore } from './eventStore'
import { user } from './user'
export async function erasePersonalData(userId: string) {
await user.loadStream(userId).erasePersonalData().settled()
await eventStore.destroyKey(`user:${userId}`)
}
  • The event is part of the audit trail, and onUserPersonalDataErased removes the data from the read model. destroyKey() does not change read models on its own.
  • destroyKey() deletes the user’s data key. Every name and email of this user, in every event, now reads as null. It also drops the snapshots of projections that handle an encrypted field.
  • Both steps are idempotent. If destroyKey() fails, call erasePersonalData() again.

Remove the user’s data from everything else that holds a copy as well: search indexes, caches, logs, exports, and the systems you sent it to.

Some data has to be kept for a fixed period and must be deleted afterwards, for example invoices. Encrypt it under a key ID per company and year, and destroy that key when the period ends:

invoice.ts
export const invoice = createAggregateRoot('invoice')
.withEvents(({ z, encrypted }) => ({
InvoiceIssued: z.object({
companyId: z.string(),
fiscalYear: z.int(),
amount: z.number(),
customerName: encrypted(z.string(), {
keyId: ({ payload }) => `retention:${payload.companyId}:${payload.fiscalYear}`,
}),
}),
}))
// …
// retentionJob.ts — run once a day, e.g. from a cron job
export async function expireRetentionPeriods(companyIds: string[], retentionYears: number) {
const lastExpiredYear = new Date().getFullYear() - retentionYears - 1
for (const companyId of companyIds) {
await eventStore.destroyKey(`retention:${companyId}:${lastExpiredYear}`)
}
}

destroyKey() is idempotent, so the job can run any number of times. If it may miss a year, destroy all years up to lastExpiredYear.

Use the in-memory driver with memoryKeyStore() to check that no plaintext is stored and that erased data reads as null:

erasure.spec.ts
import { randomBytes } from 'node:crypto'
import { expect, it } from 'bun:test'
import type { Event } from '@requence/event-sourcing'
import { createEventStore, memoryKeyStore } from '@requence/event-sourcing/memory'
import { user } from './user'
it('erases personal data', async () => {
const stored: Event[] = []
const eventStore = createEventStore({
aggregateRoots: [user],
encryption: { masterKeys: randomBytes(32), keyStore: memoryKeyStore() },
onEventsAppended: (events) => void stored.push(...events),
})
const { streamId } = await user
.newStream()
.register({ name: 'Ada', email: 'ada@example.com', plan: 'pro' })
.settled()
expect(JSON.stringify(stored)).not.toContain('ada@example.com')
await user.loadStream(streamId).erasePersonalData().settled()
await eventStore.destroyKey(`user:${streamId}`)
const registered = await eventStore.decryptEvent(stored[0]!)
expect(registered.payload).toEqual({ name: null, email: null, plan: 'pro' })
})
  • Choose key IDs deliberately. Data about a person can appear before they have an ID of their own, for example in an invitation. Encrypt it under the ID the person will get, or destroy all related key IDs together on erasure.
  • Never put personal data in unencrypted places: metadata, stream IDs, actorId and event types are not encrypted. Use opaque IDs there.
  • Backups still contain the wrapped keys of erased users. Limit how long backups are kept, and call destroyKey() again for erased users after restoring one.
  • Losing the master key loses all encrypted data. Back it up in your secret manager.
  • A user who signs up again after an erasure under the same ID gets a fresh key. Old events stay unreadable, new ones are readable.