Protecting Personal Data: Pseudonymize, Encrypt, Retain, Erase
Protect the personal data in a small raw, clean and mart pipeline: see a plain hash fall to a dictionary attack and replace it with a keyed HMAC token, encrypt each contact with its own key, erase one customer from every layer, keep them erased through replays and restores, and expire old raw files.
Contentsand lesson path
On this page
- The problem
- Step 1: The raw layer
- Step 2: Why a plain hash is not a pseudonym
- Step 3: Build the clean layer, the vault and the mart
- Step 4: One customer in every layer
- Step 5: Erase the customer
- Step 6: A replay must not bring the customer back
- Step 7: Retention and the remaining controls
- Check your understanding
- Apply it
- Review prompt
Lessons of Data Contracts & Governance
- Data Products, Data Mesh and Contracts Between Teams Concept · 20 min
- Lab: Enforcing a Contract and Shipping a Breaking Change Lab · 25 min
- Lineage: Recording and Querying the Data Graph Worked example · 25 min
- Lab: Catalog Entries, Classification and Access Control Lab · 25 min
- Protecting Personal Data: Pseudonymize, Encrypt, Retain, Erase Worked example · 30 min
- Check: Governance Review of a Pipeline Knowledge check · 10 questions
What you will learn
- Implement retention and erasure requirements for personal data across raw, cleaned and modeled layers.
- Protect sensitive fields with encryption in transit and at rest, tokenization or keyed-hash pseudonymization, least-privilege grants and access audit logs, and explain why pseudonymized data is still personal data.
01. The problem
A web shop lands raw events, one JSON line per order with the customer's email, in daily folders. A clean layer and a mart are built from them. The privacy team has five requirements:
- The email must not travel beyond the raw layer. Downstream tables use a pseudonym, a token that stands for the person, and only a separate key can link token and person.
- The receipt service still needs emails, so they are stored encrypted.
- Raw files are kept for 30 days, then deleted.
- When a customer asks to be erased, they disappear from every layer, and a replay of old files or a restored backup must not bring them back.
- Connections are encrypted, access follows least privilege, and reads of personal data are logged.
These come from law as much as from good practice. In the EU's GDPR, Article 4(5) defines pseudonymisation as processing data so that it can no longer be linked to a person without additional information that is kept separately and protected. Recital 26 adds that pseudonymised data is still information about an identifiable person, so the regulation still applies to it. Article 5(1)(e) requires that data identifying people is kept no longer than its purpose needs (storage limitation), Article 17 gives people a right to erasure, with some exceptions, and Article 32 names pseudonymisation and encryption among the security measures to consider. California's CCPA gives consumers a similar right to delete, also with exceptions. The EU AI Act adds data governance duties for the training, validation and testing data of high-risk AI systems (Article 10). This lesson shows the engineering; what the law requires in your case is a question for your privacy or legal team.
You need Python 3.10 or later and pip install "duckdb==1.5.6" cryptography; it was run with Python 3.12, DuckDB 1.5.6 and cryptography 50.0.2. Put every file of this lesson in one folder, and set the pseudonymisation key in the environment. In production it comes from a secret manager, never from the code or the warehouse.
export PSEUDO_KEY="lab-only-key-from-a-secret-store"02. Step 1: The raw layer
Three days of events for 25 customers, from a seeded generator.
"""Write three days of raw web-shop events, the same on every run."""
import json
import random
from pathlib import Path
rng = random.Random(5)
for day in ("2026-11-01", "2026-11-02", "2026-11-03"):
folder = Path(f"raw/ingest_date={day}")
folder.mkdir(parents=True, exist_ok=True)
with open(folder / "events.jsonl", "w") as f:
for _ in range(40):
n = rng.randint(1, 25)
f.write(json.dumps({"email": f"customer{n}@example.com",
"country": ["GB", "DE", "FR"][n % 3],
"amount": round(rng.uniform(5, 120), 2)}) + "\n")
for path in sorted(Path("raw").glob("*/events.jsonl")):
print(path, sum(1 for _ in open(path)), "events")python gen_raw.pyraw/ingest_date=2026-11-01/events.jsonl 40 events
raw/ingest_date=2026-11-02/events.jsonl 40 events
raw/ingest_date=2026-11-03/events.jsonl 40 events03. Step 2: Why a plain hash is not a pseudonym
A common first idea is to replace the email with its SHA-256 hash. A hash cannot be reversed, but it does not need to be: emails are guessable, so an attacker hashes millions of likely addresses and looks the results up. This is a dictionary attack. A keyed hash, HMAC-SHA256 with a secret key, gives each email a stable token, so joins still work, but nobody can compute a token without the key. pseudo.py holds both functions; attack.py plays the attacker against tokens copied from a table.
"""Keyed pseudonymisation: the same email always gives the same token, but only
someone who holds PSEUDO_KEY can compute it. The key never enters the warehouse."""
import hashlib
import hmac
import os
def token(email):
key = os.environ["PSEUDO_KEY"].encode()
return hmac.new(key, email.strip().lower().encode(), hashlib.sha256).hexdigest()
def unkeyed(email):
"""What not to do: a plain hash that anyone can recompute."""
return hashlib.sha256(email.strip().lower().encode()).hexdigest()"""A dictionary attack: hash every guessable email and look the hashes up."""
import json
from pathlib import Path
from pseudo import token, unkeyed
emails = {json.loads(line)["email"] for p in Path("raw").glob("*/events.jsonl")
for line in open(p)}
guesses = [f"customer{n}@example.com" for n in range(1, 10_001)]
for name, make in (("unkeyed SHA-256", unkeyed), ("HMAC with a key", token)):
leaked = {make(e) for e in emails} # what an attacker copies from a table
# Without the key, the attacker can only compute plain hashes of guesses.
found = sum(1 for g in guesses if unkeyed(g) in leaked)
print(f"{name:<16} tokens: {len(leaked)} | re-identified by guessing: {found}")python attack.pyunkeyed SHA-256 tokens: 25 | re-identified by guessing: 25
HMAC with a key tokens: 25 | re-identified by guessing: 0Every plain hash was matched; no HMAC token was. The key is now the secret that protects everyone, so store it in a secret manager, give it to the ingestion job only, and plan how to rotate it (a new key means new tokens, so old and new must be mapped once). Even with a good key, the clean table is still personal data: whoever holds the key can link it back, and other columns can identify people too. A rare country, amount and date together can single out one customer. That is the limit of anonymisation: removing names is not enough when the remaining attributes describe one person.
04. Step 3: Build the clean layer, the vault and the mart
build.py reads every raw file and replaces the email with its token. It skips anyone in the erasure ledger, which steps 5 and 6 use; the ledger is a file of its own, ledger.duckdb, for a reason step 6 explains. The receipt service still needs each email, so the build stores it in a vault table, encrypted with AES-GCM under a data key of its own. The keys live in kms.duckdb, which stands in for a key management service (KMS): a separate system, with its own access rules and logs.
"""Rebuild the clean layer, the contact vault and the mart from the raw files."""
import json
import os
from pathlib import Path
import duckdb
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
from pseudo import token
wh = duckdb.connect("warehouse.duckdb")
kms = duckdb.connect("kms.duckdb") # stands in for a key management service
kms.execute("create table if not exists data_keys (token text primary key, key blob)")
ledger = duckdb.connect("ledger.duckdb") # its own file, outside the warehouse backup
ledger.execute("create table if not exists erasure_ledger (token text primary key)")
wh.execute("create table if not exists vault (token text primary key, nonce blob,"
" email blob)")
erased = {t for (t,) in ledger.sql("select token from erasure_ledger").fetchall()}
rows, contacts = [], {}
for path in sorted(Path("raw").glob("ingest_date=*/events.jsonl")):
day = path.parent.name.removeprefix("ingest_date=")
for line in open(path):
event = json.loads(line)
t = token(event["email"])
if t in erased: # a second guard, after erase.py
continue
rows.append((t, event["country"], event["amount"], day))
contacts[t] = event["email"]
wh.execute("""create or replace table clean_orders (customer_token text,
country text, amount decimal(10, 2), ingest_date date)""")
wh.executemany("insert into clean_orders values (?, ?, ?, ?)", rows)
# Each person's email is encrypted with their own key, so deleting the key
# makes every copy of it unreadable, including copies in backups.
known = {t for (t,) in wh.sql("select token from vault").fetchall()}
for t, email in contacts.items():
if t not in known:
key, nonce = AESGCM.generate_key(bit_length=256), os.urandom(12)
kms.execute("insert into data_keys values (?, ?)", [t, key])
wh.execute("insert into vault values (?, ?, ?)",
[t, nonce, AESGCM(key).encrypt(nonce, email.encode(), None)])
wh.execute("""create or replace table mart_sales_by_country as
select country, count(distinct customer_token) as customers,
sum(amount) as revenue
from clean_orders group by country order by country""")
print(wh.sql("select * from mart_sales_by_country"))python build.py┌─────────┬───────────┬───────────────┐
│ country │ customers │ revenue │
│ varchar │ int64 │ decimal(38,2) │
├─────────┼───────────┼───────────────┤
│ DE │ 9 │ 2334.03 │
│ FR │ 8 │ 1955.80 │
│ GB │ 8 │ 3195.14 │
└─────────┴───────────┴───────────────┘The clean layer holds tokens, not emails. Here are the first characters of three.
python -c 'import duckdb
print(duckdb.connect("warehouse.duckdb", read_only=True).sql(
"select left(customer_token, 16) as token, country, amount"
" from clean_orders order by ingest_date, customer_token limit 3"))'┌──────────────────┬─────────┬───────────────┐
│ token │ country │ amount │
│ varchar │ varchar │ decimal(10,2) │
├──────────────────┼─────────┼───────────────┤
│ 08e00e28f7add26c │ DE │ 41.07 │
│ 331115ab66d64284 │ DE │ 67.53 │
│ 331115ab66d64284 │ DE │ 39.36 │
└──────────────────┴─────────┴───────────────┘Take a backup of the raw files and the warehouse, as a nightly job would.
mkdir backup && cp -r raw warehouse.duckdb backup/05. Step 4: One customer in every layer
check.py counts what exists about one person in each layer, and read_contact.py does what the receipt service does: it decrypts one email with that person's key.
"""Count what is left of one person in each layer."""
import json
import sys
from pathlib import Path
import duckdb
from pseudo import token
email = sys.argv[1]
t = token(email)
wh = duckdb.connect("warehouse.duckdb", read_only=True)
kms = duckdb.connect("kms.duckdb", read_only=True)
ledger = duckdb.connect("ledger.duckdb", read_only=True)
raw_lines = [x for p in Path("raw").glob("*/events.jsonl") for x in open(p)]
counts = {"raw events": sum(json.loads(x)["email"] == email for x in raw_lines)}
for label, con, table, column in [
("clean rows", wh, "clean_orders", "customer_token"),
("vault rows", wh, "vault", "token"),
("keys", kms, "data_keys", "token"),
("in ledger", ledger, "erasure_ledger", "token")]:
sql = f"select count(*) from {table} where {column} = ?"
counts[label] = con.execute(sql, [t]).fetchone()[0]
print(" | ".join(f"{label}: {n}" for label, n in counts.items()))"""What the receipt service does: decrypt one email with that person's key."""
import os
import sys
import duckdb
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
from pseudo import token
t = token(sys.argv[1])
warehouse = os.environ.get("WAREHOUSE", "warehouse.duckdb") # or a backup copy
row = duckdb.connect(warehouse, read_only=True).execute(
"select nonce, email from vault where token = ?", [t]).fetchone()
key = duckdb.connect("kms.duckdb", read_only=True).execute(
"select key from data_keys where token = ?", [t]).fetchone()
if row is None:
sys.exit("no vault row for this person")
if key is None:
sys.exit("vault row found, but its key is gone: the email cannot be decrypted")
print("decrypted:", AESGCM(key[0]).decrypt(row[0], row[1], None).decode())python check.py [email protected]
python read_contact.py [email protected]raw events: 4 | clean rows: 4 | vault rows: 1 | keys: 1 | in ledger: 0
decrypted: [email protected]06. Step 5: Erase the customer
Customer 7 asks to be erased. erase.py writes their token to the ledger, deletes their data key, deletes their vault and clean rows, and rewrites every raw file without their events. Deleting the key is crypto-shredding: any copy of the encrypted email, including the one in last night's backup, becomes unreadable at once, provided the key store keeps no copy of the deleted key in its own backups. Real KMSs delete a key only after a waiting period (7 to 30 days in AWS KMS) during which the deletion can be cancelled, so plan for that delay. The ledger is a tombstone: it keeps the token, not the email, which is just enough to recognise the person in future loads. Then rebuild the mart from the cleaned files.
"""Erase a person from every layer. Usage: erase.py EMAIL, or erase.py --reapply
after restoring raw files or the warehouse from a backup."""
import json
import sys
from pathlib import Path
import duckdb
from pseudo import token
wh = duckdb.connect("warehouse.duckdb")
kms = duckdb.connect("kms.duckdb")
ledger = duckdb.connect("ledger.duckdb")
if sys.argv[1] != "--reapply":
t = token(sys.argv[1])
# The ledger keeps the token, not the email: enough to recognise the person
# in future loads, without keeping their contact details.
ledger.execute("insert or ignore into erasure_ledger values (?)", [t])
erased = {t for (t,) in ledger.sql("select token from erasure_ledger").fetchall()}
for t in erased: # safe to repeat; also cleans restored copies
kms.execute("delete from data_keys where token = ?", [t]) # crypto-shred
wh.execute("delete from vault where token = ?", [t])
wh.execute("delete from clean_orders where customer_token = ?", [t])
removed = 0
for path in sorted(Path("raw").glob("ingest_date=*/events.jsonl")):
lines = path.read_text().splitlines(keepends=True)
keep = [x for x in lines if token(json.loads(x)["email"]) not in erased]
if len(keep) != len(lines):
removed += len(lines) - len(keep)
path.write_text("".join(keep))
print(f"ledger: {len(erased)} erased people | raw events removed: {removed}")python erase.py [email protected]
python build.py
python check.py [email protected]ledger: 1 erased people | raw events removed: 4
┌─────────┬───────────┬───────────────┐
│ country │ customers │ revenue │
│ varchar │ int64 │ decimal(38,2) │
├─────────┼───────────┼───────────────┤
│ DE │ 8 │ 2112.90 │
│ FR │ 8 │ 1955.80 │
│ GB │ 8 │ 3195.14 │
└─────────┴───────────┴───────────────┘
raw events: 0 | clean rows: 0 | vault rows: 0 | keys: 0 | in ledger: 1Try to read the email, first from the live warehouse, then from the backup taken in step 3.
python read_contact.py [email protected]; echo "exit code: $?"
WAREHOUSE=backup/warehouse.duckdb python read_contact.py [email protected]
echo "exit code: $?"no vault row for this person
exit code: 1
vault row found, but its key is gone: the email cannot be decrypted
exit code: 107. Step 6: A replay must not bring the customer back
A month later, a bug fix needs the 1 November raw files reprocessed, and someone restores them from the backup. The restored file contains customer 7 again. The ledger stops the build from loading them, but the personal data is back in the raw layer, so the restore procedure must also re-apply the ledger.
cp -r backup/raw/ingest_date=2026-11-01 raw/
python build.py > /dev/null
python check.py [email protected]
python erase.py --reapply
python check.py [email protected]raw events: 2 | clean rows: 0 | vault rows: 0 | keys: 0 | in ledger: 1
ledger: 1 erased people | raw events removed: 2
raw events: 0 | clean rows: 0 | vault rows: 0 | keys: 0 | in ledger: 1The warehouse backup was also taken before the erasure, so its clean rows still contain the token. Backups therefore need a short retention of their own, and a restore must re-apply the current ledger before anyone uses the data: erase.py --reapply deletes the keys, vault rows, clean rows and raw events of every token in it, and build.py then rebuilds the mart. That is why the ledger lives in ledger.duckdb, outside the warehouse backup, which must not roll it back. Protect the ledger itself: only the erasure job may write to it, and an old copy must never be restored over a newer one.
Table formats need one more step. In Delta Lake or Apache Iceberg, a DELETE writes new files and a new snapshot, but older snapshots still point to the old files for time travel. The deleted rows stay readable until those snapshots are expired and their files removed: VACUUM in Delta Lake, snapshot expiry in Iceberg.
08. Step 7: Retention and the remaining controls
Retention is a scheduled delete. retention.py takes the date as an argument, so you can test it, and deletes raw partitions older than 30 days. A cloud bucket would use a lifecycle rule instead. The next build.py rebuilds the clean layer and the mart from the files that remain, so old orders leave those layers too. The vault is not rebuilt: a complete policy also deletes the vault rows and data keys of people who have no data left in any layer, for example in a monthly job.
"""Delete raw partitions older than the retention period. Usage: retention.py DATE"""
import shutil
import sys
from datetime import date, timedelta
from pathlib import Path
RETENTION_DAYS = 30
today = date.fromisoformat(sys.argv[1]) # pass the date, so a test can choose it
cutoff = today - timedelta(days=RETENTION_DAYS)
for folder in sorted(Path("raw").glob("ingest_date=*")):
day = date.fromisoformat(folder.name.removeprefix("ingest_date="))
if day < cutoff:
shutil.rmtree(folder)
print(f"deleted {folder} (older than {cutoff})")
else:
print(f"kept {folder}")python retention.py 2026-12-02deleted raw/ingest_date=2026-11-01 (older than 2026-11-02)
kept raw/ingest_date=2026-11-02
kept raw/ingest_date=2026-11-03The last requirement is not code in this folder. Encryption in transit means TLS on every connection, for example sslmode=verify-full for PostgreSQL clients, so that nobody on the network can read the data. Encryption at rest means disks, buckets and backups are encrypted with keys in a KMS, so a stolen copy is useless. Neither stops an authorised user from reading too much, so add least-privilege grants to group roles, and access audit logs that record each named user's reads of personal data and are kept long enough to answer an auditor. The access-control lab shows both in PostgreSQL.
09. Check your understanding
10. Apply it
This is the privacy part of the skill practice. In a pipeline you built:
- Replace the customer identifier with an HMAC token before it leaves the raw layer, with the key in a secret store, and show that a dictionary attack on the clean layer fails.
- Script an erasure request that removes one customer from every layer, including derived tables, then replay an old raw partition and prove that the customer stays erased.
- Write down how long backups are kept, how they age out, and how the erasure ledger is re-applied after a restore.
11. Review prompt
Without looking back, explain: why a plain hash of an email is weak and what the key adds; why pseudonymised data is still personal data; how crypto-shredding makes old copies unreadable; what the erasure ledger stores and why it must survive restores; why lakehouse snapshots must be expired after a delete; and what encryption in transit, encryption at rest, least privilege and audit logs each protect against.
References
- Regulation (EU) 2016/679 (GDPR), EUR-Lex
- Regulation (EU) 2024/1689 (AI Act), EUR-Lex
- California Attorney General: California Consumer Privacy Act (CCPA)
- Python documentation: hmac
- cryptography documentation: Authenticated encryption (AESGCM)
- Delta Lake documentation: Remove files no longer referenced (VACUUM)
- Apache Iceberg documentation: Maintenance (expire snapshots)
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.