Articles / Privacy

  • event-sourcing
  • crypto-shredding
  • kafka
  • uk-gdpr
  • erasure
  • go

How to Delete One Person's Data From an Append-Only Event Log

Your event log has one rule: never change history. Then someone asks you to erase their data, and their email address is sitting in event 12, event 4,051 and event 900,000, interleaved with everybody else's.

The usual answer is to make their data unreadable without touching the log. Encrypt each person's fields with their own key, keep the keys somewhere mutable, and destroy the key when they leave. This is called crypto-shredding. The code is short, but everything around it is awkward.

Pick your approach before you write events

You have three sensible options, and all of them are far cheaper before the first event is written.

  • Keep personal data out of the log. Events carry a random reference, and the name and address live in an ordinary table. Erasure is a DELETE, but replaying the log now depends on that table.
  • Crypto-shred. Events carry ciphertext. The log stays self-contained apart from a small key table, but you now run key management.
  • Rewrite the log. Copy every event into a new stream, dropping or blanking the person's fields, switch consumers over and destroy the old one. It works on existing plaintext, but offsets, signatures, hash chains and consumer checkpoints may all need attention.

If you can keep the data out entirely, do that. It is the boring option, and boring is good here. Crypto-shredding is worth it when events need to carry the data as it was at the time.

If plaintext is already in the log, encrypting new events does nothing for the old ones, so you will have to rewrite it.

Give every person their own key

Watch out for one thing: an erased subject must never silently get a new key. A tempting "get or create key" helper will do exactly that when a late message arrives, and you will start collecting their data again.

So creation is a separate, explicit step, and erasure leaves a marker behind. This version holds everything in memory to stay readable. A real one needs a durable table, and key deletion and the marker should commit in one transaction. It also needs the keys themselves wrapped by a key held elsewhere.

package shred

import (
	"crypto/aes"
	"crypto/cipher"
	"crypto/rand"
	"errors"
	"fmt"
	"sync"
)

var ErrErased = errors.New("subject erased")

// Keys is an in-memory stand-in for a mutable table of per-subject keys.
type Keys struct {
	mu     sync.RWMutex
	keys   map[string][]byte
	erased map[string]bool
}

func NewKeys() *Keys {
	return &Keys{keys: map[string][]byte{}, erased: map[string]bool{}}
}

// Create makes a key for a new subject. It refuses an erased one.
func (k *Keys) Create(subject string) error {
	k.mu.Lock()
	defer k.mu.Unlock()
	if k.erased[subject] {
		return ErrErased
	}
	if _, ok := k.keys[subject]; !ok {
		key := make([]byte, 32)
		rand.Read(key) // never returns an error since Go 1.24
		k.keys[subject] = key
	}
	return nil
}

func (k *Keys) Erase(subject string) {
	k.mu.Lock()
	defer k.mu.Unlock()
	delete(k.keys, subject)
	k.erased[subject] = true
}

func (k *Keys) aead(subject string) (cipher.AEAD, error) {
	k.mu.RLock()
	defer k.mu.RUnlock()
	key, ok := k.keys[subject]
	if !ok {
		// A missing key is only "erased" if we recorded erasing it.
		if k.erased[subject] {
			return nil, ErrErased
		}
		return nil, errors.New("no key for subject")
	}
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}
	return cipher.NewGCMWithRandomNonce(block)
}

// aad ties a ciphertext to one subject and one event.
func aad(subject, eventID string) []byte {
	return fmt.Appendf(nil, "%q %q", subject, eventID)
}

func (k *Keys) Seal(subject, eventID string, pii []byte) ([]byte, error) {
	a, err := k.aead(subject)
	if err != nil {
		return nil, err
	}
	return a.Seal(nil, nil, pii, aad(subject, eventID)), nil
}

func (k *Keys) Open(subject, eventID string, box []byte) ([]byte, error) {
	a, err := k.aead(subject)
	if err != nil {
		return nil, err
	}
	return a.Open(nil, nil, box, aad(subject, eventID))
}

cipher.NewGCMWithRandomNonce (Go 1.24 and later) generates the nonce and stores it with the ciphertext, so there is no nonce bookkeeping to get wrong. It is limited to 232 messages per key, which is roomy for one person's events.

The associated data stops a ciphertext being pasted into a different event and still decrypting. The %q quoting keeps the boundary between the two IDs unambiguous.

Check that erasure really breaks reads

Test the failures as well as the round trip: after erasure, both reading and re-creating must fail.

package shred

import (
	"errors"
	"testing"
)

func TestErase(t *testing.T) {
	k := NewKeys()
	if err := k.Create("s1"); err != nil {
		t.Fatal(err)
	}
	box, err := k.Seal("s1", "e1", []byte("[email protected]"))
	if err != nil {
		t.Fatal(err)
	}
	if got, err := k.Open("s1", "e1", box); err != nil || string(got) != "[email protected]" {
		t.Fatalf("open: %q %v", got, err)
	}
	if _, err := k.Open("s1", "e2", box); err == nil {
		t.Fatal("ciphertext moved to another event")
	}
	k.Erase("s1")
	if _, err := k.Open("s1", "e1", box); !errors.Is(err, ErrErased) {
		t.Fatalf("open after erase: %v", err)
	}
	if err := k.Create("s1"); !errors.Is(err, ErrErased) {
		t.Fatalf("recreate after erase: %v", err)
	}
}

Your projections need to treat ErrErased as a normal outcome: show a blank or a placeholder and carry on. A replay that crashes on the first erased customer is a fun thing to discover during an outage.

Any other decryption error should still be loud. Otherwise a lost key or corrupted event looks exactly like a successful erasure.

Hunt down everything outside the ciphertext

Shredding a key affects only what that key encrypted. Every plaintext copy survives, so list them:

  • read models, caches and search indexes
  • snapshots of aggregate state
  • dead-letter queues, debug logs and traces
  • analytics exports and anything a downstream consumer stored
  • decryption keys cached by other processes

Check the envelope too. A stream called [email protected] defeats the whole exercise, and a hash of the email can be matched by anyone who guesses the address. Use a random subject ID, and delete the table that maps it to the person when you no longer have a reason to keep it.

Quick detour, because this one is interesting: what about an event involving two people, such as "A sent B a message"? One key per event cannot express that. Encrypt A's fields under A's key and B's under B's. Free text mentioning both is harder, because encryption has no idea whose sentence it is.

Stop backups resurrecting the key

Restore last week's key table and the shredded key comes straight back. The "erased" marker may also disappear, which is worse, because nothing looks wrong.

Two habits help:

  • Keep a separate list of erased subject IDs that is not rolled back with the key table, and reapply it before a restored system serves traffic.
  • Give key backups a short, fixed expiry, so old copies of a key age out on a schedule you can state.

You can then back up the log itself for as long as you like, with one condition: the keys must not be sitting in the same backup.

Do not assume Kafka compaction has deleted it

Kafka can remove old records, but it has no on-demand "forget this person" button.

With log compaction, Kafka keeps at least the latest value for each message key, and a null value (a tombstone) marks a key for deletion. That has consequences:

  • If events are keyed by user, compaction can throw away their history during normal operation, which is rarely what event sourcing wants.
  • If every event has a unique key, you need a tombstone for each of that person's events.
  • The active segment is never compacted.
  • max.compaction.lag.ms is effectively unlimited by default, so set it if you rely on compaction, and still verify the result.

The other tool, kafka-delete-records, trims a partition up to an offset. Everyone before that point goes, including people who never asked.

Hang on, why can't the broker just cut one record out? The log is a run of segment files read by offset, built for appending and sequential reads. Compaction works by writing cleaned copies of older segments, so it is really a background rewrite with good manners.

Whether a shredded key counts as erasure

The legislation, Article 17 of the UK GDPR, gives a right to erasure on particular grounds. It is not absolute: some data you may have to keep, for instance to meet a legal obligation. It does not prescribe a technique.

ICO guidance says encrypted data is still personal information in your hands. Its erasure guidance talks about putting backup data "beyond use" where it cannot be overwritten immediately, and being clear with people about what happens to it.

Neither page mentions crypto-shredding. My view is that destroying every copy of a strong, per-person key is a defensible way to erase or put data beyond use. That is my interpretation, not an ICO endorsement, and it gets much weaker if a key survives in a backup, cache or export.

There are deadlines too. The ICO says to respond without undue delay and at the latest within one month, with an extension of up to two further months for complex or repeated requests. If you shared the data, you generally have to tell the recipients too, unless that is impossible or disproportionate.

So write the erasure as a job you can rerun and audit: destroy the key, purge the projections, notify consumers, record what happened using the random ID. Then pick a test account, erase it, and go looking for its email address everywhere. The place you find it will probably be a log line somebody added on a Friday.