Privacy engineering in data pipelines: personal data, retention and erasure built into the code
TL;DR
Difficulty: Advanced
Privacy law has to live in the pipeline code, not in a policy document.
- Load only named columns. A column you never load needs no protection, retention or erasure.
- Classify every column and let the build fail on an unclassified one.
- Pseudonymised data is still personal data. Anonymisation is a much higher bar, so measure uniqueness before you call a file anonymous.
- A plain hash of an email is not anonymous. Use a keyed hash or a random token, with the key kept apart.
- Give each table a retention period and enforce it with a nightly job.
- Build one erasure job that reaches the shop, raw tables, every snapshot version and every processor, keep a suppression list for restored backups, and test it weekly with a synthetic customer.
A privacy notice promises things that the pipeline behind it often cannot do. This chapter turns the GDPR's demands into code: allowlists, classification tests, tokens, masking views, a retention policy and an erasure job, worked through on an invented homeware shop in Limerick.
Privacy law is a pipeline requirement, not a policy document
Most businesses meet data protection as a document: a privacy notice on the website, a policy in a shared folder, a cookie banner. Then the data goes into a warehouse, gets copied into raw tables, staging tables, snapshots, exports and spreadsheets, and nobody can say any more where a customer's email address actually lives. The policy promises things the pipeline cannot do.
This chapter answers one question: how do I build pipelines that respect privacy law by design? Not by adding a legal review at the end, but by making the law's requirements part of the code, the same way a test or a schema is part of the code.
A few terms first, so nobody is left behind:
- Personal data is any information about an identified or identifiable living person. An email address is personal data. So is an order number, if you can look up who placed it.1
- The controller decides why and how personal data is processed. For a shop, that is the shop. A processor handles personal data on the controller's behalf, such as the warehouse provider or the newsletter tool.
- The data subject is the person the data is about: the customer.
- Pseudonymisation replaces identifying details with a stand in (a token or a keyed hash) and keeps the key to reverse it somewhere else. Anonymisation removes the link to the person for good. The difference decides whether the law applies at all, and a whole section below is about it.
- Retention is how long you keep data. Erasure is deleting it, on schedule or because a person asked.
The legal frame for this edition is the Irish one: the EU General Data Protection Regulation (GDPR), the Data Protection Act 2018 that gives it further effect in Irish law, and the ePrivacy Regulations (S.I. No. 336 of 2011) for cookies and marketing messages, with guidance from the Data Protection Commission (DPC). This chapter is general information for people who build data systems, not legal advice. Where a decision carries legal risk, check it with a solicitor or your data protection officer.
It builds on the previous chapter, metadata, lineage, catalogues and a semantic layer: you cannot protect a column you cannot find, and a catalogue with lineage is what lets you find every copy.
Example: where one customer lives at Shannonside Home
Shannonside Home is the invented homeware shop in Limerick that runs through this whole series (shannonsidehome.example). Niamh owns it. Callum builds the shop and the data platform. The shop runs on Ruby on Rails and Solidus with PostgreSQL, and the warehouse is BigQuery in the EU multi region. Every figure for Shannonside in this chapter is invented for the example.
In five years about 78,000 people have ordered from Shannonside (1,300 new customers a month for 60 months). Callum picks one of them, an invented customer called Siobhán Byrne, and lists every place her email address can sit:
| Place | What it holds about Siobhán |
|---|---|
Shop database, spree_users and spree_addresses | Email, name, phone, two addresses |
Shop database, spree_orders | Her email again on every order, the IP address of the last checkout |
| Nightly backups of the shop database | All of the above, 30 days of copies |
| Warehouse raw layer (change tables) | Every version of every row since loading began |
| Warehouse staging and core models | Cleaned copies |
| dbt snapshot of customers | Every past version of her record, with old addresses |
| GA4 export in BigQuery | Her shop user id on every event after login |
| Newsletter tool | Email, name, consent date, clicks |
| Customer service tool | Two tickets with her phone number in the text |
| 3PL shipment file | Name and delivery address per parcel |
| Payment settlement files | Name and email on each charge |
| Customer lists uploaded to Google and Meta | Her email, hashed |
| A spreadsheet export someone made in March | Name, email, total spend |
Thirteen places. Every one of them has to honour her rights, and every one has to be deleted on schedule. A pipeline built without privacy in mind multiplies personal data. A pipeline built with it keeps that list short on purpose.
Data protection by design means decisions in the pipeline code
Article 25 of the GDPR is called "data protection by design and by default". It asks the controller, both when deciding how to process data and while processing it, to put in place appropriate technical and organisational measures, such as pseudonymisation, that put the data protection principles into effect. By default, only the personal data necessary for each specific purpose may be processed: the amount collected, how far it is processed, how long it is stored and who can access it.2 The European Data Protection Board (EDPB), whose guidance shaped how this article is read, adds that the measures must be effective, not just present on paper.3
For a data engineer, that turns into a short list of rules. Each one gets its own section below.
| Principle in the law | What it means in a pipeline |
|---|---|
| Data minimisation | Load only the columns a named purpose needs |
| Purpose limitation | Carry consent and purpose flags with the data, filter at the point of use |
| Storage limitation | A retention period per table, enforced by code, not by memory |
| Integrity and confidentiality | Pseudonymise at the door, restrict access by column, log who reads what |
| Accountability | Be able to show all of the above: catalogue, tests, logs |
| Rights of the data subject | An erasure job that reaches every layer, including history and backups |
The order matters. Every rule further down the list gets easier if the rules above it were followed. A column you never loaded needs no masking, no retention and no erasure.
Example: Callum's design review for a new model
Niamh wants a "repeat customers" report: how many customers order a second time within 12 months, by the channel of their first order. Before writing SQL, Callum answers six questions in the pull request description:
- Purpose: count repeat customers by first channel. No contact, no targeting.
- Personal data needed: a stable customer key, order dates, first channel. No email, no name, no address.
- Key: the person token from the identity store, never the email.
- Retention: the model is rebuilt daily from core tables, so it holds nothing the core tables do not.
- Access: Niamh and the analyst role. Aggregates only in the dashboard.
- Erasure: inherits from the core tables, because the model is a full rebuild.
Six answers, five minutes. That is what "by design" looks like in practice: the questions are asked before the code exists, and the answers are written down where a reviewer can check them.
The column you never load is the one you never have to protect
Data minimisation, Article 5(1)(c), says personal data must be adequate, relevant and limited to what is necessary for the purpose.4 The DPC adds that data should be processed only if the purpose could not reasonably be achieved by other means.5
The most common way a warehouse breaks this rule is SELECT *. A loader that copies every column of every table brings along email addresses, IP addresses, free text fields and session tokens that no report will ever use. Each one then needs protecting, retention and erasure, forever.
The fix is an allowlist at ingestion: the loader names the columns it copies, and a new column in the source stays out until someone adds it on purpose.
Example: the orders table, column by column
Solidus stores orders in spree_orders. Among its columns are email, last_ip_address, special_instructions (free text a customer types at checkout) and guest_token (a secret that lets a guest see their order).6 None of these is needed for revenue, margin or repeat purchase analysis.
Shannonside's spree_orders has 1,240,000 rows, most of them baskets that never completed. Leaving those four columns out of the warehouse means:
where is the number of personal data cells never copied, the number of rows and the number of columns left out. Nearly five million values that never need masking, retention or erasure. This is plain multiplication, as in Foundations: ratios and rates.
The email is still needed to know which orders belong to the same person. So it is not copied either. It is swapped for a token at the door (the section on tokenisation below shows how). The staging model then selects named columns only. In BigQuery SQL, as a dbt model:
-- models/staging/shop/stg_shop__orders.sql (BigQuery)
-- Allowlist: every column is named. A new source column stays out
-- until someone adds it here on purpose.
select
id as order_id,
number as order_number,
person_token, -- set by the loader, replaces email
state,
completed_at,
canceled_at,
currency,
item_total,
adjustment_total,
shipment_total,
additional_tax_total,
included_tax_total,
total,
channel,
store_id
from {{ source('shop', 'spree_orders') }}
-- not loaded on purpose: email, last_ip_address,
-- special_instructions, guest_token
The comment at the bottom is not decoration. It tells the next person that leaving those columns out was a decision, not an accident.
Classify every column before it lands
Minimisation needs a list of what is personal and how sensitive it is. That list is a classification, and it belongs in the catalogue from the previous chapter, next to the column's description and owner.
Four classes are enough for most shops:
| Class | What it is | Examples at a shop |
|---|---|---|
| Direct identifier | Points at one person on its own | Email, name, phone, street address, IP address, payment reference |
| Quasi identifier | Harmless alone, identifying in combination | Eircode, order date and time, rare products bought, town |
| Special category | Health, religion, ethnicity and the other categories in Article 9 | Rarely a column, often hidden in free text |
| Not personal | No link to a person | Product prices, stock levels, ad spend per campaign |
Quasi identifiers are the class people forget. In a well known study, Latanya Sweeney found that 87% of the population of the United States in the 1990 census data were likely unique on just three fields: five digit ZIP code, gender and date of birth.7 A dataset with no names in it can still point at one person.
Special category data at a shop is usually not a column at all. It hides in free text: a delivery note asking the driver to ring twice "because I use a wheelchair", a support ticket about a return after a hospital stay. Article 9 puts health data under stricter rules.8 Free text fields are therefore classified as possibly special category by default, and they stay out of the warehouse unless a purpose needs them.
Example: Shannonside's classification as data, with a test
Callum keeps the classification as a dbt seed, a small CSV file in the repository, so it is versioned and reviewed like code:
table_name,column_name,class
stg_shop__orders,order_id,not_personal
stg_shop__orders,person_token,pseudonym
stg_shop__orders,completed_at,quasi_identifier
stg_shop__orders,total,not_personal
stg_shop__addresses,person_token,pseudonym
stg_shop__addresses,eircode_routing_key,quasi_identifier
stg_shop__addresses,country_iso,not_personal
Then a singular dbt test fails the build when any column in the staging dataset has no class. In BigQuery SQL:
-- tests/assert_every_column_is_classified.sql (BigQuery)
-- Returns the unclassified columns. Any row returned fails the test.
select c.table_name, c.column_name
from `{{ target.project }}.staging.INFORMATION_SCHEMA.COLUMNS` as c
left join {{ ref('column_classification') }} as k
on k.table_name = c.table_name
and k.column_name = c.column_name
where k.class is null
The day a source system adds a column and someone adds it to a staging model without thinking, the build stops and asks: what is this, and who may see it? That question, asked automatically, is data protection by design in eight lines.
A fifth class appears in the seed: pseudonym. A token is not a direct identifier, but it is still personal data, as the next section explains.
Pseudonymisation is not anonymisation
This is the distinction that decides whether the law applies at all.
The GDPR defines pseudonymisation as processing personal data so that it can no longer be attributed to a specific person without additional information, provided that information is kept separately and protected.1 Recital 26 adds that pseudonymised data which could be attributed to a person by using additional information should be considered information on an identifiable person, and that the principles of data protection do not apply to anonymous information.9
So pseudonymised data is still personal data. Every rule in this chapter still applies to it. Pseudonymisation lowers the risk and is explicitly named as a good measure, but it does not take you out of the law. The EDPB's guidelines on pseudonymisation, adopted on 16 January 2025, say the same: pseudonymised data that could be attributed to a person with additional information stays personal, even if that additional information is held by someone else.10
There is one nuance from the courts. In September 2025 the Court of Justice of the European Union, in a case about the EU institutions' own data protection rules, confirmed that pseudonymised data need not be personal data for every person in every case: for a recipient who has no reasonable means to identify anyone, it may not be.11 That judgment binds the interpretation of the law in Ireland, but it does not change your position as the controller who holds the key. For Shannonside, the tokenised warehouse is personal data, full stop.
Anonymisation is a far higher bar. The DPC's guidance stresses that only data which has been irreversibly and effectively anonymised stops being personal data.12 The guidance of the UK's Information Commission (formerly the Information Commissioner's Office, ICO) describes identifiability as a spectrum and asks whether a "motivated intruder", a reasonably competent person with access to public information, could identify anyone from the data.13 Research shows how low that bar can be in practice: Rocher, Hendrickx and de Montjoye estimated that 99.98% of Americans would be correctly reidentified in any dataset using 15 demographic attributes.14
Two numbers help to judge a dataset that is meant to be anonymous, both simple ratios and counts as explained in Foundations: ratios and rates. The share of records that are unique on their quasi identifiers:
and the size of the smallest group of records that share the same quasi identifiers, called (a dataset is "k anonymous" when every record shares its combination with at least others):
where is the share of unique records, the number of records whose combination of quasi identifiers appears only once, the number of records, one group of records with identical quasi identifiers and its size. Both are ratios and counts as in Foundations: ratios and rates. A low and a high are necessary for anonymity. They are not sufficient: a rare product in the basket can still single someone out.
Example: the "anonymous" file for the marketing consultant
Niamh wants to send a marketing consultant a file of all 78,000 customers with their Eircode routing key, the week of their first order and their total spend. No names, no emails. She calls it anonymous. Callum measures it first. In BigQuery SQL:
-- How unique is each customer on the quasi identifiers? (BigQuery)
with groups as (
select
eircode_routing_key, -- for example V94
date_trunc(first_order_date, week) as first_week,
count(*) as group_size
from core.customers
group by 1, 2
)
select
sum(group_size) as customers,
sum(if(group_size = 1, 1, 0)) as unique_customers,
round(sum(if(group_size = 1, 1, 0)) / sum(group_size), 3) as share_unique,
min(group_size) as k
from groups;
He runs it at four levels of detail. The results (invented for the example):
| Location detail and time | Unique customers | Share unique |
|---|---|---|
| Full Eircode and month | 75,504 | 96.8% |
| Routing key (V94) and week | 55,692 | 71.4% |
| Routing key (V94) and month | 14,196 | 18.2% |
| County and quarter | 702 | 0.9% |
Worked through for the second row: , so 71.4% of customers are the only person in their routing key area who first ordered in that week. Anyone who knows a neighbour bought from Shannonside in a given week can find their row and read their total spend. The file is not anonymous. It is barely pseudonymous.
Only the last level comes close, and even there 702 customers are unique. Callum suggests the consultant gets aggregates instead: spend by county and quarter, with any cell under 10 customers suppressed. That answers the consultant's actual question (where do the valuable customers live) without handing over anyone's row.
Why hashing an email does not make it anonymous
A common shortcut is to replace the email with its hash, for example with the SHA256 function, and call the result anonymous. It is not, for a simple reason: a hash is deterministic. The same email always gives the same hash, on every computer, for everyone.
Anyone who has a list of emails can hash the whole list and compare. The EDPB guidelines use exactly this as their warning: if you know the transformation is merely a SHA256 hash of a name, you can apply it to all names you have elsewhere and see which hashes match.10 Google's own BigQuery documentation notes that its SHA256 masking rule is deterministic, so a value always produces the same hash.15 Advertising platforms rely on exactly this property: Google asks advertisers to normalise and hash customer emails with SHA256 before uploading them, so it can match them to its own users.16 A hashed email is a key that anyone can turn.
What the EDPB recommends instead is a transformation that involves a secret only the pseudonymising controller holds, with enough randomness that nobody can guess it, such as a message authentication code (MAC) with a secret key.10 The most common MAC is the HMAC: a hash computed over the data together with a secret key. Without the key, nobody can compute the pseudonym for a known email.
Example: Callum shows Niamh why her hash is not safe
In PostgreSQL, the built in sha256 function hashes a value.17 Callum hashes Niamh's own address:
-- PostgreSQL: the same input always gives the same hash
select encode(sha256(convert_to('niamh@shannonsidehome.example', 'UTF8')), 'hex');
-- the result is identical on any machine that runs this line
Anyone who has ever received an email from Niamh can run that line and find every row about her in a "hashed" export. Then he does it properly, with a keyed hash from the pgcrypto extension:18
-- PostgreSQL with pgcrypto: a keyed hash (HMAC with SHA256)
create extension if not exists pgcrypto;
select encode(
hmac(lower(trim(' Niamh@ShannonsideHome.example ')), -- normalise first
current_setting('app.pseudonym_key'), -- the secret, never in code
'sha256'),
'hex') as email_key;
Two details matter. First, normalise before hashing: lower case and trimmed whitespace. Otherwise "Niamh@ShannonsideHome.example" and "niamh@shannonsidehome.example" get different keys, which is exactly how 3.1% of Shannonside's accounts became duplicates in the first place (the chapter on duplicates and entity resolution covers the matching in depth). Second, the key is read from a setting that the application sets from a secret store at connection time, so it never appears in the code, the logs or the query history.
In the loader, written in Python, the same keyed hash looks like this:
import hashlib
import hmac
def normalise_email(raw: str) -> str:
"""Lower case and trimmed, so one person gets one key."""
return raw.strip().lower()
def email_key(raw_email: str, secret: bytes) -> str:
"""Keyed hash (HMAC with SHA256) of a normalised email, as hex."""
message = normalise_email(raw_email).encode("utf-8")
return hmac.new(secret, message, hashlib.sha256).hexdigest()
The keyed hash is still a pseudonym, so it is still personal data. But it can be shared inside the warehouse without letting anyone who holds an email list find a person, and the key can be rotated if it ever leaks.
Tokenisation and a separate key store
A keyed hash has one weakness: the pseudonym is computed from the email, so everyone with the key can recompute it. A stronger pattern is a token: a random value with no mathematical link to the person at all, stored in a lookup table. The lookup table is the only place where token and identity meet.
At Shannonside the design looks like this:
- A separate Google Cloud project,
shannonside-identity, holds one dataset,identity. Only the loader, the erasure job and the customer service tool's service account can read it. - The table
identity.personholdsperson_token(a random UUID),email_key(the keyed hash, used to find an existing token), the normalised email, name and phone. - Every other table in the warehouse carries
person_tokenonly.
When the loader sees an email, it computes the keyed hash, looks it up, and either reuses the existing token or creates a new one. Analysts never see the identity project. A leak of the analytics warehouse exposes tokens, order amounts and dates, not names and emails.
The same separation gives erasure a powerful tool. If the identity row is deleted, the token in the warehouse points at nobody. Whether the remaining data is then anonymous depends on the quasi identifiers still attached, as the previous section showed, so the erasure job still has work to do on Eircodes and free text. But the direct identifiers are gone from every table in one statement.
A related technique is crypto shredding: encrypt each person's personal fields with a key that belongs only to that person, and delete the key when the person must be erased. Every copy of the ciphertext, in snapshots, in exports, in backups, becomes unreadable at once. BigQuery supports this with its AEAD encryption functions.19 Whether a deleted key counts as erasure in the strict legal sense is not settled in guidance. It fits well with the idea that data in backups must at least be put "beyond use" (more on that below), and it is a strong measure for places you cannot rewrite.
Example: a per customer key for delivery addresses
The 3PL's shipment file brings Siobhán's name and delivery address into the raw layer every time she orders. Callum cannot avoid loading the file, because returns and delivery times are reconciled from it. So he encrypts the address fields on arrival with a key that belongs to her token. In BigQuery SQL:
-- Once per person: create a key (BigQuery, run in the identity project)
insert into `shannonside-identity.identity.person_key` (person_token, keyset, created_at)
select @person_token, keys.new_keyset('AEAD_AES_GCM_256'), current_timestamp();
-- On load: encrypt the delivery fields with that person's key.
-- The token is passed as additional data, so a ciphertext copied
-- onto another person's row will not decrypt.
select
s.shipment_id,
s.person_token,
aead.encrypt(k.keyset, s.delivery_name, s.person_token) as delivery_name_enc,
aead.encrypt(k.keyset, s.delivery_address, s.person_token) as delivery_address_enc,
s.eircode_routing_key,
s.shipped_at
from raw_3pl.shipments_parsed as s
join `shannonside-identity.identity.person_key` as k using (person_token);
Customer service reads the address through an authorised view that calls aead.decrypt_string(k.keyset, delivery_address_enc, person_token). When Siobhán asks to be erased, deleting her row in person_key makes every encrypted address of hers unreadable, in the raw table, in every snapshot and in every table copy made from it. One delete reaches places a DELETE ... WHERE never could.
Access control: who can see which column and which row
Pseudonymisation protects against outsiders. Access control protects against everyone inside who does not need the data. The principle is least privilege: each role sees the columns and rows its job needs, and nothing else.
Both PostgreSQL and BigQuery support this at the column level. PostgreSQL can grant SELECT on named columns only,20 can enforce row level security policies,21 and can serve a masking view. BigQuery attaches policy tags to columns, so that only principals with the right role read them,22 and can apply dynamic masking rules such as nullify, an email mask or a hash to the same column for other roles.15 Row level access policies filter rows by role.23
A masking view is the most portable tool, because it works on any database: it shows a reduced version of each personal field, and the role gets access to the view but not to the table behind it.
Example: four roles and one masking view at Shannonside
Callum writes the roles down first, as a table:
| Role | Direct identifiers | Quasi identifiers | Orders and money |
|---|---|---|---|
| Niamh, owner | Through customer service screens only | Yes | Yes |
| Analyst (Callum, and any future analyst) | No | Coarsened | Yes |
| Customer service | Yes, for the customer on the phone | Yes | Yes |
| Marketing consultant | No | No | Aggregates only |
Then the masking view, in PostgreSQL syntax, for the analyst role on the reporting replica:
-- PostgreSQL: a masking view for analysts
create view reporting.customers_masked
with (security_barrier = true) as
select
p.person_token,
-- email: keep only the domain, useful to spot business customers
split_part(p.email_normalised, '@', 2) as email_domain,
-- phone: present or not, never the number
(p.phone is not null and p.phone <> '') as has_phone,
-- Eircode: keep only the routing key, the first three characters
left(upper(replace(a.zipcode, ' ', '')), 3) as eircode_routing_key,
a.country_iso,
p.created_at::date as customer_since
from identity.person as p
left join identity.default_address as a using (person_token);
revoke all on identity.person, identity.default_address from analyst;
grant select on reporting.customers_masked to analyst;
Three details in this view are easy to miss. The security_barrier option stops the planner from pushing a user's own filter functions below the view's logic, which could otherwise leak hidden rows through clever WHERE clauses.24 The view runs with the owner's rights by default, so the analyst can read it without any right on the tables behind it. And the Eircode is cut to its routing key. A full Eircode points at a single address, so it is as identifying as a street address.
For dbt models in BigQuery, the grants live next to the model, so access is reviewed in the same pull request as the code:25
# models/marts/marts.yml
models:
- name: mart_repeat_customers
config:
grants:
select: ['group:analysts@shannonsidehome.example']
Retention: a schedule per table, enforced by code
Storage limitation, Article 5(1)(e), says personal data must be kept in a form that permits identification for no longer than necessary for the purpose.4 The DPC links it directly to minimisation: the period for which data is stored should be limited to a strict minimum.5
Two forces pull in opposite directions. The law on financial records makes you keep some data for years: Revenue expects the original business records to be kept for six years.26 Data protection makes you delete everything else as soon as its purpose is served.
The way out is to separate the transaction from the identity. An order's amount, VAT, date and products are the financial record and stay for six years. The name and email attached to it are only needed as long as there is a reason to know who it was: the customer relationship, returns, warranty, disputes. When those reasons end, the identity can go while the transaction stays.
A useful way to see why retention matters for risk is a rule from queueing theory known as Little's law: in a steady state, the number of items held equals the rate they arrive times how long each one stays.
where is the number of personal records held at any moment, the number of new records per month and the number of months each record is kept. Without a retention rule, grows every month and so does . It is a rate times a duration, as in Foundations: ratios and rates.
Example: Shannonside's retention schedule
Niamh decides the periods with her accountant. Callum turns them into a table that the code reads. The periods below are invented for the example and show the method, not a legal recommendation:
| Data | Where it lives | Kept for | Then | Reason |
|---|---|---|---|---|
| Completed orders: amounts, VAT, products, dates | core.orders | 6 years after the end of the year | Deleted | Business records (Revenue) |
| Identity on orders (token link, name, address) | identity project | Until the order's record period ends, or erasure | Token link removed, row stays as a transaction | Returns, disputes, records |
| Customer accounts with no order and no login | Shop and identity | 3 years of inactivity | Account erased | No remaining purpose |
| Abandoned baskets with an email | Shop and raw layer | 90 days | Personal fields deleted | Basket reminders only |
| GA4 event export | analytics_<property id> dataset | 14 months | Table expires | Matches the GA4 retention setting |
| Raw landing files (3PL, settlement) | Cloud Storage bucket | 90 days | File deleted, parsed tokenised rows stay | Reloads after errors |
| Payment settlement files | Finance archive bucket | 6 years after the end of the year | Deleted | Business records |
| Customer service tickets | Service tool and warehouse | 2 years after closing | Deleted | Follow up questions |
| Shop database backups | Backup storage | 30 days | Overwritten | Disaster recovery |
| Access logs of the identity project | Log bucket | 12 months | Deleted | Security reviews |
Abandoned baskets show the effect of the rule. Shannonside sees about 6,500 baskets a month that reach the email step and never complete (invented). With a 90 day rule, and , so email addresses at any moment. Without a rule, after the five years of history the shop already has, and .
Twenty times as many email addresses sitting in tables, for no purpose at all, and still growing by 6,500 a month. Every one of them is exposed in a breach and has to be found for every access request.
Example: the retention policy as code
Callum keeps the schedule in a YAML file in the repository, so a change of period is a reviewed commit, not a click in a console:
# retention/policy.yml
policies:
- table: shannonside-analytics.raw_shop.basket_contacts
rule: delete_rows
date_column: created_at
keep_days: 90
- table: shannonside-analytics.core.orders
rule: delete_rows
date_column: completed_at
keep_until: end_of_year_plus_years
years: 6
year_end: "12-31"
- dataset: shannonside-analytics.analytics_123456789
rule: default_table_expiry
keep_days: 425
A small Python job, run daily by the scheduler from the chapter on orchestration, turns each policy into SQL and runs it:
from datetime import date
import yaml
from google.cloud import bigquery
client = bigquery.Client(location="EU")
def cutoff_for(policy: dict, today: date) -> date:
if "keep_days" in policy:
return date.fromordinal(today.toordinal() - policy["keep_days"])
# orders: keep until the end of the year plus N years
month, day = (int(x) for x in policy["year_end"].split("-"))
year_end = date(today.year, month, day)
if year_end >= today:
year_end = date(today.year - 1, month, day)
return date(year_end.year - policy["years"], month, day)
def apply(policy: dict, today: date) -> None:
if policy["rule"] == "delete_rows":
sql = (f"delete from `{policy['table']}` "
f"where date({policy['date_column']}) <= @cutoff")
params = [bigquery.ScalarQueryParameter(
"cutoff", "DATE", cutoff_for(policy, today))]
job = client.query(sql, job_config=bigquery.QueryJobConfig(
query_parameters=params))
job.result()
print(policy["table"], "rows deleted:", job.num_dml_affected_rows)
elif policy["rule"] == "default_table_expiry":
client.query(
f"alter schema `{policy['dataset']}` "
f"set options (default_table_expiration_days = {policy['keep_days']})"
).result()
if __name__ == "__main__":
with open("retention/policy.yml") as f:
for p in yaml.safe_load(f)["policies"]:
apply(p, date.today())
Worked through for the orders policy on 19 February 2027: the last year end on or before that day is 31 December 2026. Six years before it is 31 December 2020. Every order completed on or before 31 December 2020 is deleted. Shannonside's history starts in 2022, so today the rule touches no row at all. The orders of 2022 go for the first time after 31 December 2028, automatically, without anyone having to remember in 2029.
One trap is hidden in the GA4 line. The GA4 export does not write into one partitioned table. It creates a new table every day, named events_YYYYMMDD.27 A partition expiry therefore does nothing. The dataset option default_table_expiration_days works instead, but it only applies to tables created after it is set.28 The tables that already exist need their own expiry, set once with alter table ... set options (expiration_timestamp = ...). And the retention setting inside GA4 itself (2 or 14 months for standard properties) controls the data Google Analytics keeps on its own servers, not your copy in BigQuery.29 Two settings, two places, and both belong in the policy.
Erasure: one request, every layer
Article 17 gives people the right to have their personal data erased without undue delay when one of its grounds applies, for example when the data is no longer needed or when they withdraw the consent it was based on.30 You must respond within one month, which can be extended by two further months for complex requests.31 The right has limits: among others, it does not apply where processing is needed to comply with a legal obligation, such as keeping financial records, or to establish, exercise or defend legal claims.30 And under Article 19 you must tell every recipient you shared the data with, unless that proves impossible or involves disproportionate effort. The DPC spells out both duties in its guidance on the right to erasure.3233
For a data engineer, three layers make erasure hard.
Immutable raw layers. The chapter on raw, staging and clean layers set the rule "never overwrite raw", for good reasons: you can always rebuild. Erasure is the one legal exception. The raw layer must either never hold direct identifiers (tokenise at the door), or hold them encrypted per person (crypto shredding), or be rewritten for the person concerned. "Raw is never touched" is not a defence.
History. Snapshots and slowly changing dimensions, as built in the chapter on versioning, history and audit trails, exist to remember old values. An old address in a dbt snapshot is still her address. The erasure job must update every version, not only the current one.
Backups and time travel. BigQuery keeps changed and deleted data for a time travel window of two to seven days (seven by default), and then for a further seven days of fail safe that cannot be shortened.34 Database backups keep whatever was in them on the day. The guidance of the UK's Information Commission is specific here, and a sensible reference point on this side of the Irish Sea too: you must take steps to erase from backups as well as live systems, it may be that the data remains in the backup until it is overwritten, and the key issue is to put the backup data "beyond use", which means you do not use it for any other purpose and it is simply held until replaced on an established schedule. You must be clear with the person about what will happen to their data in backups.35
That last point has an engineering consequence that is often missed. If you ever restore a backup, the erased person comes back. So the erasure job keeps a suppression list: the keyed hash of each erased email, and nothing else, checked after every restore and on every new load. The suppression list itself is pseudonymised personal data, kept for the purpose of honouring the erasure. Write that purpose down.
The longest the warehouse holds a deleted row is easy to calculate:
where is the number of days until the data has left BigQuery's storage for good, the days until the erasure job runs, the time travel window and the fail safe period. A simple sum, the kind of arithmetic in Foundations: ratios and rates.
Example: Siobhán asks to be erased
Siobhán writes to Shannonside on a Monday and asks for all her data to be deleted. Callum's job runs nightly, and he has set the time travel window of the analytics datasets to two days. For the warehouse, , and , so .
Ten days until her data has left BigQuery completely, well inside the one month. The shop database backups are kept for 30 days and are not edited. They are beyond use: nobody queries them, and a restore runs the suppression check before the shop opens again. Niamh's reply to Siobhán says exactly that, and that is grand for the one month deadline.
First, Callum must find all of Siobhán. She has an account under "Siobhan.Byrne@example.com " with a trailing space, and two older guest orders under "siobhan.byrne@example.com". Because the loader normalises before computing the keyed hash, all three map to one person_token. Without normalisation, the erasure would have missed two orders, and the shop would have kept data it promised to delete.
Then the shop. Solidus has no built in erasure, so Shannonside has a small service object. Orders stay (they are financial records), but the identity on them goes. In Ruby on Rails 8:
# app/services/erase_customer.rb
class EraseCustomer
def initialize(email:)
@email = email.strip.downcase
end
def call
ActiveRecord::Base.transaction do
orders = Spree::Order.where("lower(trim(email)) = ?", @email)
address_ids = orders.pluck(:bill_address_id, :ship_address_id).flatten.compact
# Keep the order as a financial record, remove who it was.
orders.update_all(email: nil, last_ip_address: nil,
special_instructions: nil, updated_at: Time.current)
# Addresses: keep the country for VAT, blank everything personal.
Spree::Address.where(id: address_ids).update_all(
name: "erased", address1: "erased", address2: nil,
company: nil, phone: nil, alternative_phone: nil,
zipcode: nil, city: "erased", email: nil, updated_at: Time.current
)
# Solidus refuses to destroy a user who has orders, so the
# account is emptied instead: no email, no saved addresses.
Spree::User.where("lower(trim(email)) = ?", @email).find_each do |user|
Spree::UserAddress.where(user_id: user.id).delete_all
user.update_columns(email: "erased_#{user.id}@erased.invalid",
bill_address_id: nil, ship_address_id: nil,
updated_at: Time.current)
end
end
end
end
Solidus guards against deleting a user who has orders: its user model raises an error before destroy unless the user has no orders,36 which is why the account is emptied rather than destroyed. Note also that update_all skips callbacks and validations on purpose, and sets updated_at by hand so the change data capture from the chapter on incremental loading picks it up. Whether the address columns can be blanked depends on your Solidus version and its validations, so this belongs under a test (more on that below).
Then the warehouse, all other layers and the processors. The erasure job, in Python:
import psycopg
from google.cloud import bigquery
bq = bigquery.Client(location="EU")
# Every table that carries person_token, and what to do there.
# Generated from the catalogue, never typed by hand.
WAREHOUSE_STEPS = [
"delete from `shannonside-identity.identity.person` where person_token = @t",
"delete from `shannonside-identity.identity.person_key` where person_token = @t",
"delete from `shannonside-analytics.raw_shop.basket_contacts` where person_token = @t",
"update `shannonside-analytics.snapshots.customers_snapshot` "
"set eircode_routing_key = null, town = null where person_token = @t",
"delete from `shannonside-analytics.core.service_tickets` where person_token = @t",
]
def erase(person_token: str, email_key: str, shop_dsn: str, processors) -> dict:
report = {}
params = [bigquery.ScalarQueryParameter("t", "STRING", person_token)]
for sql in WAREHOUSE_STEPS:
job = bq.query(sql, job_config=bigquery.QueryJobConfig(query_parameters=params))
job.result()
report[sql.split("`")[1]] = job.num_dml_affected_rows
# The suppression list holds only the keyed hash, so a restored
# backup or a new file cannot bring the person back unnoticed.
with psycopg.connect(shop_dsn) as conn:
conn.execute(
"insert into privacy.suppression (email_key, erased_at) "
"values (%s, now()) on conflict (email_key) do nothing",
(email_key,),
)
# Article 19: tell every processor and recipient, record the answer.
for processor in processors:
report[processor.name] = processor.request_erasure(person_token)
return report
Four things make this job safe to run. The SQL is parameterised, so Siobhán's token never appears in the query text or the query history.37 The list of steps is generated from the catalogue's lineage, so a new table that carries person_token is not forgotten. Downstream models in core and marts are rebuilt from the cleaned layers on the next run, so they need no step of their own. And the job returns a report per layer, which goes into the request's record as evidence of what was done and when, without repeating her email.
The processors list is the bridge to everything outside the warehouse: the newsletter tool's API, the customer service tool, the removal of her email from the next customer list upload to Google and Meta, and the GA4 User Deletion API for the data Google Analytics holds against her user id.38 The GA4 export tables in BigQuery are your own copy, so the warehouse steps must cover them too, for example by deleting rows where user_id matches her shop id.
A word on models built from personal data, such as a lifetime value model or a segmentation: erasing a person's rows does not remove their influence on a model that was already trained. The existing article on GDPR, AI and the right to be forgotten goes into that question in depth. For a shop, regular retraining on the current, cleaned data is usually the practical answer.
Consent and purpose flags travel with the data
Purpose limitation, Article 5(1)(b), says data collected for one purpose must not be used for another purpose that is incompatible with it.4 For marketing emails and for non essential cookies the basis is usually consent, and consent can be withdrawn at any time.
The engineering mistake is to copy consent once. A customer list exported on Monday with everyone who had consented on Monday is wrong on Tuesday, when someone withdraws. The fix is to treat consent as data with its own history, and to check it at the moment of use, not at the moment of copying.
On the analytics side, the rules for cookies come from Regulation 5 of the ePrivacy Regulations. Storing or reading information on a visitor's device needs their consent, given on the basis of clear and comprehensive information, with an exception only for transmitting a communication or for what is strictly necessary to provide a service the visitor explicitly asked for.39 Analytics does not fall under that exception. My own site runs front end analytics only after consent. The articles on event tracking and consent mode and server side tracking cover the collection side.
Example: the newsletter audience that respects every withdrawal
Shannonside's newsletter list has 38,000 subscribers, and about 290 people withdraw marketing consent each month (invented). Consent lives in one table with full history:
-- core.consent_events (BigQuery): one row per change, never updated
-- person_token | purpose | status | changed_at | source
-- p_7f3a... | marketing_email | granted | 2025-04-02 10:14:00 | checkout
-- p_7f3a... | marketing_email | withdrawn | 2027-02-11 18:40:00 | unsubscribe_link
The audience model takes the latest status per person and purpose, at the time it runs:
-- models/marts/mart_email_audience.sql (BigQuery)
with latest as (
select person_token, purpose, status, changed_at
from {{ ref('consent_events') }}
where purpose = 'marketing_email'
qualify row_number() over (
partition by person_token, purpose order by changed_at desc) = 1
)
select c.person_token, c.preferred_language, c.country_iso
from {{ ref('customers') }} as c
join latest as l using (person_token)
where l.status = 'granted'
And a test that fails the build if anyone whose latest status is "withdrawn" ever appears in the audience:
-- tests/assert_no_withdrawn_person_in_audience.sql
select a.person_token
from {{ ref('mart_email_audience') }} as a
join {{ ref('consent_events') }} as e using (person_token)
where e.purpose = 'marketing_email'
qualify row_number() over (
partition by e.person_token order by e.changed_at desc) = 1
and e.status = 'withdrawn'
The same pattern covers the customer lists uploaded to Google and Meta. Each upload is built from the audience model on the day, so the 290 people who withdrew this month are gone from the next upload without anyone remembering to remove them.
Logging who looked at what
Accountability, Article 5(2), means being able to show that you comply.4 Security of processing, Article 32, asks for measures appropriate to the risk.40 Section 36 of the Data Protection Act 2018 names logging mechanisms that show whether and by whom personal data were consulted, altered, disclosed or erased among its suitable and specific measures, next to strict time limits for erasure, pseudonymisation and encryption.41 Knowing who read the identity data, and when, is part of both. It also turns a vague worry ("could anyone have looked at customer addresses?") into a query with an answer.
BigQuery records every query job, with the user, the time, the statement type and the tables it referenced, in the INFORMATION_SCHEMA.JOBS views,42 and in more detail in Cloud Audit Logs.43 PostgreSQL can log statements through its logging settings,44 and the pgAudit extension adds structured audit logging of reads and writes per role.45
Two warnings. Logs are personal data too: they hold staff emails, and if queries contain literal customer values, customer data as well. That is one more reason to use query parameters everywhere. And logs need their own retention, which is why the access log line is in the schedule above.
Example: the weekly access review
Every Monday, Callum runs one query and Niamh reads the result. In BigQuery SQL:
-- Who read the identity project in the last 7 days? (BigQuery)
select
j.user_email,
t.table_id,
count(*) as queries,
min(j.creation_time) as first_read,
max(j.creation_time) as last_read
from (
-- JOBS lists the jobs run in one project, so read both projects
select * from `shannonside-identity`.`region-eu`.INFORMATION_SCHEMA.JOBS
union all
select * from `shannonside-analytics`.`region-eu`.INFORMATION_SCHEMA.JOBS
) as j,
unnest(j.referenced_tables) as t
where j.creation_time >= timestamp_sub(current_timestamp(), interval 7 day)
and t.project_id = 'shannonside-identity'
and t.dataset_id = 'identity'
group by 1, 2
order by queries desc;
The view lists jobs per project, so a query run from the analytics project that reads identity tables is recorded there, not in the identity project. That is why the query reads both. The data access entries in Cloud Audit Logs, which record reads on the identity project's tables wherever the job ran, are the more complete record for a formal review.
A normal week shows three service accounts: the loader, the erasure job and the customer service tool. A human email in that list is a question worth asking, kindly, the same day.
A data protection impact assessment for analytics
Article 35 requires a data protection impact assessment (DPIA) before processing that is likely to result in a high risk to people.46 The DPC publishes a list of the types of processing that require a DPIA, and notes that where it is not clear whether one is strictly needed, doing one is still good practice.47
Many analytics projects stay well below that line. Some cross it quietly: a customer lifetime value model, used to decide who gets which offer, and fed into ad platforms as custom audiences, is profiling, combines several sources and matches data with a third party. The DPIA is not a legal essay. Most of its content is engineering facts: what data, from where, to where, who sees it, how long it stays, what can go wrong and what stops it. Data engineers are the people who know those facts.
Example: screening the lifetime value audiences
Niamh wants to upload the top 10% of customers by predicted lifetime value to Meta as a seed audience. Callum fills in a screening table before any code is written:
| Screening question | Answer |
|---|---|
| Does it evaluate or score people? | Yes, predicted lifetime value |
| Does it combine data from several sources? | Yes: orders, newsletter clicks, service tickets |
| Does it match data with a third party? | Yes: hashed emails to Meta |
| Is it large scale? | About 7,800 people uploaded (10% of 78,000) |
| Does it use special category data? | No, free text excluded |
Three yeses: a DPIA is the sensible choice. The risks and the measures he records:
| Risk | Measure |
|---|---|
| A person who withdrew consent is uploaded | Audience built from the consent model on the day, test in the build |
| Service tickets reveal health details | Ticket text never enters the model, only ticket counts |
| Meta keeps matched data longer than needed | Check the processor terms, upload only the minimum fields |
| A person erased stays in the uploaded list | Erasure job triggers a fresh upload the same night |
The DPIA then lives next to the model's documentation in the catalogue, and the next change to the model gets reviewed against it.
Processors and transfers
Every tool that handles personal data for Shannonside is a processor, and Article 28 requires a written contract that, among other things, obliges the processor to delete or return the data at the end of the service and to help the controller answer requests from data subjects.48 When a processor stores or accesses data outside the European Economic Area, the rules on international transfers apply as well. For the United States, the General Court of the EU upheld the adequacy decision for the EU US Data Privacy Framework in September 2025.49 The existing article on vetting vendors and transfers covers the due diligence in depth.
For the pipeline, two things follow. Pick storage locations on purpose: Shannonside's BigQuery datasets sit in the EU multi region, and the location is fixed when a dataset is created, so this is a day one decision. And keep a processor register that the erasure job can read, so that "tell every recipient" is a loop in code, not a hope.
Example: Shannonside's processor register
| Processor | Personal data | Where it is stored | How erasure reaches it |
|---|---|---|---|
| Google Cloud (BigQuery, Cloud Storage) | Tokenised warehouse, identity project | EU multi region | Erasure job, then time travel and fail safe |
| Stripe and PayPal | Payment details, name, email | Their own systems | Business records kept, ask for marketing data only |
| Newsletter tool | Email, name, consent, clicks | Per the contract | API call from the erasure job |
| Customer service tool | Tickets, phone, email | Per the contract | API call from the erasure job |
| 3PL warehouse | Names and addresses of parcels | Their systems | Email request, answer recorded |
| Google Analytics | Events against the shop user id | User Deletion API | |
| Google Ads and Meta | Hashed customer lists | Their systems | Next upload excludes the person |
Every row with "API call" is a step the job runs. Every other row is a task the job creates and tracks until someone records the answer.
Testing privacy like any other requirement
I work test first, and privacy rules get tests like any other rule. The chapter on testing data pipelines covers the tools. Four tests carry most of the weight here:
- Every column is classified. The test from the classification section.
- No direct identifier in a mart. A test that fails if any column classed as a direct identifier appears in the
martsdataset. - Retention holds. For each policy, no row older than its cutoff.
- Erasure reaches everything. An end to end test with a synthetic customer.
Example: the erasure canary
Every Sunday night a job creates a synthetic customer, "canary" plus the date at a test domain, places an order, opens a ticket, subscribes to the newsletter and lets the nightly pipelines carry the data everywhere. On Monday the erasure job runs for the canary. On Tuesday a pytest suite checks every layer:
# tests/test_erasure_canary.py
import pytest
from google.cloud import bigquery
bq = bigquery.Client(location="EU")
TABLES_WITH_TOKEN = [
"shannonside-identity.identity.person",
"shannonside-identity.identity.person_key",
"shannonside-analytics.raw_shop.basket_contacts",
"shannonside-analytics.core.service_tickets",
]
@pytest.mark.parametrize("table", TABLES_WITH_TOKEN)
def test_canary_is_gone(table, canary_token):
sql = f"select count(*) as n from `{table}` where person_token = @t"
cfg = bigquery.QueryJobConfig(query_parameters=[
bigquery.ScalarQueryParameter("t", "STRING", canary_token)])
n = list(bq.query(sql, job_config=cfg).result())[0].n
assert n == 0, f"{table} still holds the erased canary"
def test_canary_is_suppressed(shop_conn, canary_email_key):
row = shop_conn.execute(
"select 1 from privacy.suppression where email_key = %s",
(canary_email_key,)).fetchone()
assert row is not None
The canary is the only way to know the erasure job still works after six months of new tables, new tools and new colleagues. When a test fails, it fails on a synthetic person, before a real one asks. The data observability checks then watch the same jobs for freshness and failures.
What Irish law adds
Most of this chapter follows directly from the GDPR. A few points are specific to Ireland:
- Suitable and specific measures. Section 36 of the Data Protection Act 2018 lists the measures Irish law expects where it requires suitable and specific safeguards: among them limits on access, strict time limits for erasure with mechanisms to make sure they are kept, logging of who consulted, altered, disclosed or erased personal data, pseudonymisation and encryption.41 Read as a checklist, it is almost the table of contents of this chapter.
- Cookies. Regulation 5 of S.I. No. 336 of 2011 requires consent for storing or reading information on a device, with only narrow exceptions.39
- Anonymisation guidance. The DPC's guidance on anonymisation and pseudonymisation is the Irish reference for deciding whether a dataset is truly anonymous.12
- The courts. The Court of Justice's September 2025 judgment on how the recipient sees pseudonymised data applies directly in Ireland.11 For you, as the controller holding the key, the tokenised warehouse stays personal data.
- Records. Revenue expects original business records to be kept for six years.26 That period wins for the transaction tables.
- The regulator. The Data Protection Commission is the supervisory authority, and its guidance on erasure, DPIAs and the data protection principles is the first place to check.3347
Again: this is general information for building systems, not legal advice. The retention periods and the DPIA decision for a real business belong with its accountant and its data protection officer.
Conclusion
Privacy by design in a pipeline is not a document and not a banner. It is a set of decisions written into code: an allowlist instead of SELECT *, a classification that the build checks, a token instead of an email, a keyed hash instead of a plain one, a masking view instead of a full table, a retention policy that runs every night, an erasure job that reaches raw tables, snapshots and processors, and a suppression list for the day a backup comes back.
Done this way, the work pays twice. Shannonside's warehouse holds 4,960,000 fewer personal values from one table alone, 370,500 fewer abandoned basket emails, and no copy of a customer that nobody can find. And when Siobhán writes to ask what Shannonside holds about her, or to be forgotten, the answer is a query and a job, not a week of searching thirteen places by hand.
The next chapter in this series looks at the performance and cost of a data platform, where several of the decisions made here, such as time travel windows and table expiry, show up again on the bill.
