The previous lesson answered the question of who can access the data. This one deals with a deeper question: what you are allowed to do with people's data, even when you have access to it. NovaMarket's two million customers have not handed over ownership of their information; they have entrusted it for specific purposes and they retain rights over it. In the European Union, that relationship is governed by the General Data Protection Regulation (GDPR).
You will see what personal data is (quite a lot more than it seems), what the law requires, how that translates into technical decisions inside a data lake and which techniques make it possible to analyse without identifying. In the hands-on part you will build a pseudonymised version of the customers and orders tables, and measure its re-identification risk.
Warning. This lesson is for training purposes and deliberately simplifies; it is not legal advice. Data protection law is extensive, is interpreted case by case and changes over time. Every real decision (lawful bases, retention periods, transfers, impact assessments, handling of rights requests or breaches) must be reviewed with the data protection officer (DPO), legal counsel or the compliance department, consulting the current text of the legislation and the guidance of the supervisory authority (in Spain, the Spanish Data Protection Agency, AEPD).
Security and privacy are not the same thing
| Security | Privacy | |
|---|---|---|
| Question | Who can access the data? | Is it legitimate to process it, for what purpose and for how long? |
| Protects | The organisation and its assets | The people the data relates to |
| Typical failure | An unauthorised third party steals the customers table | The company uses data it holds, with correct access, for a purpose the customer did not expect |
| Tools | Access control, encryption, auditing | Legal basis, minimisation, retention periods, pseudonymisation, handling of rights requests |
Security is necessary for privacy, but not sufficient: a perfectly protected system can make unlawful use of data without a single intrusion taking place.
What personal data is
It is any information relating to an identified or identifiable natural person. The key word is identifiable: the name does not have to appear; it is enough that the person can be identified, directly or indirectly, with reasonable effort. The GDPR expressly mentions identification numbers, location data and online identifiers.
- Direct identifiers: point to a person on their own (name, national ID number, email address, phone number).
- Indirect identifiers or quasi-identifiers: do not identify on their own, but can do so in combination (province, signup date, age, postcode).
- Special categories of personal data: data revealing racial or ethnic origin, political opinions, religious or philosophical beliefs or trade union membership; genetic data, biometric data for the purpose of uniquely identifying a person, data concerning health and data concerning a person's sex life or sexual orientation. As a general rule, processing them is prohibited except in narrowly defined cases.
Classification of NovaMarket's columns:
| Column | Type | Comment |
|---|---|---|
customers.name |
Direct identifier | |
customer_id (in any table) |
Personal data: identifier | It does not say who someone is, but it singles out a person and allows them to be linked to their name |
customers.province, customers.signup_date |
Quasi-identifiers | Together they greatly reduce the set of candidates |
orders and order_lines |
Personal data as long as they carry customer_id |
Purchase history describes a person, and sensitive traits can be inferred from it |
web_events.session_id, device |
Personal data (online identifier) | Also in anonymous visitors' sessions: it singles out a browser |
web_events (browsing history) |
Personal data | With customer_id it is, in addition, a profile of interests |
reviews.text |
Free text | Can contain anything, including special categories (lesson 05-05) |
products |
Not personal | |
gold/daily_kpis, gold/daily_funnel |
Aggregates | Not personal, provided no group is so small that it points to someone |
The conclusion is uncomfortable: almost the whole lake is personal data. Replacing the name with a number does not change that.
The GDPR and the LOPDGDD: principles and lawful bases
The GDPR (Regulation (EU) 2016/679) has applied since May 2018 throughout the European Union, and also to organisations outside it that offer goods or services to people located in it. In Spain it is supplemented by the LOPDGDD (Organic Law 3/2018 on the Protection of Personal Data and the Guarantee of Digital Rights), Spain's national data protection act.
The principles
| Principle | What it requires | At NovaMarket |
|---|---|---|
| Lawfulness, fairness and transparency | A legal basis, no deception, and clear information | The privacy policy explains what is collected and why |
| Purpose limitation | Collect for specified purposes and do not use for other, incompatible ones | Order data is not simply reused to build advertising profiles |
| Data minimisation | Only the data that is adequate and necessary for the purpose | Marc does not need the name to calculate sales by province |
| Accuracy | Correct, up-to-date data | The quality rules from lesson 05-02 |
| Storage limitation | Do not keep data in identifiable form for longer than necessary | Retention policy (see below) |
| Integrity and confidentiality | Appropriate security | Everything covered in lesson 07-01 |
| Accountability | Comply and be able to demonstrate it | Records, assessments and documented decisions |
The lawful bases
All processing must rest on at least one of these six bases:
| Basis | Indicative example at NovaMarket |
|---|---|
| Consent (freely given, specific, informed and unambiguous; as easy to withdraw as to give) | Analytics and advertising cookies; marketing newsletter |
| Performance of a contract | Processing and delivering an order |
| Legal obligation | Keeping invoices for as long as tax and commercial law requires |
| Vital interests | Unusual in e-commerce |
| Public task or exercise of official authority | Typical of public administrations |
| Legitimate interests (after a documented balancing test against the person's rights) | Fraud prevention |
Which basis applies to each processing activity is a legal decision, not a technical one, and it is not always obvious (personalised recommendations are a debated case). What is your job as a data professional is to know that every table you use has a purpose and a basis behind it, and that using it for something else is not simply an engineering decision.
Individuals' rights
| Right | Content | Technical implication |
|---|---|---|
| Access | To know whether their data is being processed and obtain a copy | Locate everything held about a customer_id across all zones and systems |
| Rectification | To have inaccurate data corrected | Propagate the correction to derived copies |
| Erasure ("right to be forgotten") | To have data erased when it is no longer necessary, consent is withdrawn, etc., subject to exceptions (for example, a legal obligation to retain it) | Genuinely deleting from immutable files |
| Restriction of processing | To "freeze" the use of the data in certain cases | A flag that the pipelines respect |
| Portability | To receive their data in a structured, commonly used format | Per-customer export |
| Objection | To object to processing based on legitimate interests and, always, to direct marketing | An exclusion list that filters before processing |
| Automated decision-making | Not to be subject to a decision based solely on automated processing, including profiling, that produces legal or similarly significant effects, subject to exceptions and with safeguards such as human intervention | Human review of fraud blocks (lesson 03-05) |
The general response deadline is one month from the request, extendable in complex cases. A lake where nobody knows in how many places a customer appears cannot meet it: the lineage and catalogue of lesson 05-02 are also compliance tools.
The organisation's obligations
- Controller and processor. The controller determines the purposes and means of processing (NovaMarket). The processor processes data on the controller's behalf (the cloud provider, an agency), under a contract that sets out what it may do. Engaging a processor does not transfer responsibility.
- Data protection officer (DPO). A role that advises on and monitors compliance, independently; mandatory in certain cases, including large-scale processing of special categories or regular and systematic monitoring of individuals on a large scale. NovaMarket, which profiles two million customers, has a DPO, who works hand in hand with Irene.
- Records of processing activities. An inventory of processing activities: purpose, categories of data and of individuals, recipients, retention periods, security measures. Your data dictionary is its best source.
- Data protection impact assessment (DPIA). A prior analysis, mandatory when processing is likely to result in a high risk to people's rights and freedoms, such as systematic profiling with significant effects or large-scale processing of special categories.
- Data protection by design and by default. Build protection in when designing the system, and make the most protective configuration the default.
- Breach notification. A personal data breach must be notified to the supervisory authority without undue delay and, where feasible, within 72 hours of becoming aware of it, unless it is unlikely to result in a risk; if the risk is high, the affected individuals must also be informed. The compromised credential from lesson 07-01 starts that clock.
- International transfers. Sending personal data outside the European Economic Area requires safeguards: a European Commission adequacy decision on the destination country, standard contractual clauses or other mechanisms. This is an area that has changed several times through court rulings, especially regarding the United States: you need to check the current position.
Data residency. Lesson 06-04 flagged it: NovaMarket chose a cloud region in Spain, which keeps storage and processing inside the EU. It is a good decision, but it does not settle the matter: technical support accessing from other countries, the provider's sub-processors, connected SaaS tools and the legislation of the provider's home country also count.
Penalties. The most serious infringements can be punished with fines of up to €20 million or 4% of total worldwide annual turnover for the preceding financial year, whichever is higher; there is a lower tier of up to €10 million or 2%. On top of that come reputational damage and possible compensation claims.
Other regulations
| Regulation | Scope | Key feature |
|---|---|---|
| UK GDPR and Data Protection Act | United Kingdom | Derived from the GDPR, with its own evolution |
| CCPA / CPRA | California (US) | Rights to know, delete and opt out of the sale or sharing of data; the US lacks a general federal law and several states have their own |
| LGPD | Brazil | Structure heavily inspired by the GDPR |
| PIPL | China | Strict requirements on consent and transfers |
| ePrivacy Directive and, in Spain, the LSSI | EU / Spain | Regulate, among other things, cookies and similar technologies |
A company that sells in several countries usually adopts the most demanding standard as its baseline and manages the differences as exceptions.
What it means technically in a data lake
Privacy by design. Every table is born with its classification, its purpose and its retention period in the data dictionary; the zone the analysts use contains no direct identifiers; development environments do not use real data.
Minimisation. It applies at three moments: when collecting (do not capture what is not needed), when propagating (do not drag the name into every derived table) and when granting access (column-level control, lesson 07-01).
Retention and deletion. Lesson 05-03 set retention periods on cost grounds (bronze and silver two years, gold indefinitely) and left the legal criterion pending. With it, the policy becomes more nuanced:
| Dataset | Indicative policy (to be validated with the DPO) |
|---|---|
web_events with identifiers |
Identifiable for a short period tied to the analytical purpose; then aggregated or anonymised |
orders, order_lines |
Whatever tax and commercial obligations require; once the period has elapsed, deletion or anonymisation |
customers |
For the duration of the relationship plus the subsequent liability periods |
Aggregated gold (daily_kpis, daily_funnel) |
Indefinitely: it is no longer personal data |
Customer-level gold (dim_customer, customer_segments) |
Not indefinitely: it inherits the periods of its sources |
The challenge of the right to erasure. A customer asks for their data to be erased, and the lake is built for the opposite:
- Parquet files are immutable: deleting a row means rewriting the whole file.
- Bronze keeps the originals, and the customer appears in dozens of daily files.
- There are copies: derived tables, Kafka topics, the Cassandra table, caches, backups, extracts.
Three technical aids:
- Table formats (lesson 02-05). With Delta Lake or Iceberg, deletion is a single statement, and the format takes care of rewriting only the affected files. But the old versions still exist for time travel until they are purged:
-- Illustrative (Delta Lake)
DELETE FROM silver.customers WHERE customer_id = 123;
VACUUM silver.customers; -- removes old files once the configured retention period has passed- Crypto-shredding. Each customer's data is encrypted with its own key, stored in the KMS. To "erase" the customer, their key is destroyed: their data, whether in bronze, in a backup or in a forgotten file, becomes unreadable for ever. It is the most practical way to reach immutable copies.
- Short-lived bronze for personal data, or with direct identifiers split off into a separate table, which is the only one that needs to be modified.
And an organisational requirement: a procedure that goes through every system, supported by lineage, and keeps a record of what was done.
Consent management. The events in web_events originate from cookies and similar technologies, which, apart from those strictly necessary, require consent. Technically: the consent status is recorded with each session; events from people who have not consented to analytics are not collected, or are filtered out at ingestion; and withdrawal of consent is propagated going forward. A pipeline that ignores that field turns the user's decision into a dead letter.
Protection techniques: from pseudonymisation to synthetic data
The most important distinction in the lesson:
- Pseudonymisation: identifiers are replaced with pseudonyms, so that the data can no longer be attributed to a person without additional information that is kept separately. It reduces risk, but the data is still personal and the GDPR applies to it in full.
- Anonymisation: the person is no longer identifiable, irreversibly, by any reasonable means. Truly anonymous data falls outside the GDPR. Achieving it is much harder than it looks.
| Technique | What it consists of | Limitation |
|---|---|---|
| Salted or keyed hash (HMAC) | Pseudonym computed with a hash function and a secret | Whoever has the secret can recompute it; without a secret, it can be reversed by brute force |
| Tokenisation | Random pseudonym stored in a protected lookup table | That table has to be safeguarded and scaled |
| Masking | Hide part of the value (P**** G*****, ***1234) |
Only useful for display; analytically poor |
| Generalisation | Reduce precision: date → month, province → region, age → band | Loses detail |
| Suppression | Remove columns or rows that are too unique | Loses data, and can bias the analysis |
| k-anonymity | Ensure that every combination of quasi-identifiers is shared by at least k people | Gives no protection if the whole group shares the same sensitive value |
| Differential privacy | Add calibrated random noise to the results | Less accuracy; hard to tune well |
| Synthetic data | Generate artificial data that mimics the statistical properties of the real data | Can leak real cases if the generator memorises them |
Why HMAC and not a plain hash? A hash such as SHA-256 is deterministic and public. NovaMarket's customer_id values run from 1 to 2,000,000: anyone can compute the hash of all two million values in seconds and undo the pseudonym. HMAC mixes the value with a secret key: without it, the pseudonym cannot be recomputed.
k-anonymity and l-diversity. If the table contains only one customer from Las Palmas who signed up in 2024, anyone who knows those two facts can identify them even without a name. A table is k-anonymous if every combination of quasi-identifiers appears at least k times. l-diversity adds that, within each group, the sensitive attribute must take at least l distinct values: a group of ten people who all bought the same sensitive product protects none of them.
Differential privacy, the idea. Imagine you publish how many customers in a province bought a certain product. If someone knows yesterday's figure and today's, and knows who signed up in between, they can deduce what that person bought. Differential privacy adds a small amount of random noise to each result, calibrated so that the answer is practically the same whether or not a particular person is in the data. A little accuracy is lost in exchange for a mathematical guarantee.
Hands-on: pseudonymised tables and k-anonymity
You are going to create a new zone, lake/silver_pseudo/, designed for the analysts: the same customer and order data, with no name, with customer_id replaced by a pseudonym and the signup date generalised to the month. First generate a random key in an environment variable (as you learned in lesson 07-01, never in the code):
Create ~/novamarket/pseudonymise.py:
import hashlib
import hmac
import os
from pathlib import Path
from pyspark.sql import SparkSession
from pyspark.sql import functions as F
from pyspark.sql.types import StringType
LAKE = Path.home() / "novamarket" / "lake"
MIN_K = 5
# 1. The secret key is read from the environment: it is never written in the code
key = os.environ.get("NOVAMARKET_PSEUDO_KEY")
if not key:
raise SystemExit("The NOVAMARKET_PSEUDO_KEY environment variable is missing")
KEY = key.encode("utf-8")
spark = SparkSession.builder.master("local[*]").appName("pseudonymise").getOrCreate()
spark.sparkContext.setLogLevel("ERROR")
# 2. Pseudonym = HMAC-SHA256(key, customer_id), in hexadecimal
@F.udf(StringType(), useArrow=False)
def pseudonym(customer_id):
if customer_id is None:
return None
return hmac.new(KEY, str(customer_id).encode("utf-8"), hashlib.sha256).hexdigest()
customers = spark.read.parquet(str(LAKE / "silver" / "customers"))
orders = spark.read.parquet(str(LAKE / "silver" / "orders_complete"))
# 3. Customers: no name, no customer_id, signup date generalised to the month
customers_pseudo = customers.select(
pseudonym("customer_id").alias("customer_pseudo"),
F.coalesce("province", F.lit("unknown")).alias("province"),
F.date_format("signup_date", "yyyy-MM").alias("signup_month"),
)
# 4. Orders: the same pseudonym replaces customer_id
orders_pseudo = orders.withColumn("customer_pseudo", pseudonym("customer_id")).drop("customer_id")
customers_pseudo.coalesce(1).write.mode("overwrite").parquet(str(LAKE / "silver_pseudo" / "customers"))
orders_pseudo.coalesce(1).write.mode("overwrite").parquet(
str(LAKE / "silver_pseudo" / "orders_complete"))
customers_pseudo = spark.read.parquet(str(LAKE / "silver_pseudo" / "customers"))
orders_pseudo = spark.read.parquet(str(LAKE / "silver_pseudo" / "orders_complete"))
customers_pseudo.show(3, truncate=20)
# 5. Analysis is still possible: the join works on the pseudonym
(orders_pseudo.where(F.col("status") != "returned")
.join(customers_pseudo, "customer_pseudo")
.groupBy("province").agg(F.round(F.sum("total_amount"), 2).alias("sales"))
.orderBy(F.desc("sales")).show(3))
# 6. k-anonymity: size of the smallest group sharing the quasi-identifiers
def k_anonymity(df, quasi, label):
groups = df.groupBy(*quasi).count()
f = groups.agg(
F.count("*").alias("groups"), F.min("count").alias("k"),
F.sum(F.when(F.col("count") == 1, 1).otherwise(0)).alias("unique"),
F.sum(F.when(F.col("count") < MIN_K, F.col("count")).otherwise(0)).alias("at_risk"),
).first()
print(f"{label:<24} groups={f['groups']:>4} k={f['k']:>3} "
f"single-person groups={f['unique']:>4} customers in groups with k<{MIN_K}={f['at_risk']}")
return groups
k_anonymity(customers_pseudo, ["province", "signup_month"], "(province, signup_month)")
# 7. Generalise further: from month to year
by_year = customers_pseudo.withColumn("signup_year", F.substring("signup_month", 1, 4))
k_anonymity(by_year, ["province", "signup_year"], "(province, signup_year)").where(
F.col("count") < MIN_K).orderBy("count").show()
# 8. Also generalise the province to a wider region
ZONES = {"Valencia": "East", "Alicante": "East", "Castellon": "East",
"Murcia": "East", "Illes Balears": "East", "Madrid": "Centre",
"Barcelona": "Northeast", "Zaragoza": "Northeast", "Sevilla": "South", "Malaga": "South",
"Las Palmas": "South", "A Coruna": "North", "Bizkaia": "North", "Asturias": "North"}
mapping = F.create_map(*[F.lit(x) for pair in ZONES.items() for x in pair])
by_zone = by_year.withColumn("zone", F.coalesce(mapping[F.col("province")], F.lit("unknown")))
k_anonymity(by_zone, ["zone", "signup_year"], "(zone, signup_year)").orderBy("count").show(4)
spark.stop()- Steps 1 and 2. The
pseudonymfunction is a UDF (lesson 03-03) that applies HMAC-SHA256 with the key read from the environment.useArrow=Falserequests the classic variant of UDFs: the Arrow-optimised one adds nothing here and, with some combinations of PySpark, pandas and PyArrow versions, it can hang. The result is deterministic: the same customer always gets the same pseudonym, as long as the key does not change. - Steps 3 and 4. The name is dropped (minimisation), the date is generalised and the pseudonym is applied to both tables with the same key. The 20 customers with no province are labelled
unknown. - Step 5. The essential check: the join on
customer_pseudoworks just as it does oncustomer_id. - Steps 6 to 8.
k_anonymitygroups by the quasi-identifiers and looks at the smallest group. Then the data is generalised in two steps, at the cost of detail.
Output of python pseudonymise.py (your pseudonyms will be different, because your key is):
+--------------------+---------+------------+ | customer_pseudo| province|signup_month| +--------------------+---------+------------+ |c54aa54e2584fee5c...|Castellon| 2023-01| |6a056d347bfc5076f...|Castellon| 2024-11| |d954b077230bc44cb...| Alicante| 2022-02| +--------------------+---------+------------+ only showing top 3 rows +---------+----------+ | province| sales| +---------+----------+ | Valencia|6905275.27| | Madrid|6145802.21| |Barcelona|4932768.05| +---------+----------+ only showing top 3 rows (province, signup_month) groups= 426 k= 1 single-person groups= 198 customers in groups with k<5=665 (province, signup_year) groups= 60 k= 1 single-person groups= 1 customers in groups with k<5=29 +-------------+-----------+-----+ | province|signup_year|count| +-------------+-----------+-----+ | Las Palmas| 2024| 1| | unknown| 2023| 2| | Las Palmas| 2022| 3| | Zaragoza| 2022| 3| |Illes Balears| 2022| 4| |Illes Balears| 2023| 4| | Bizkaia| 2025| 4| | unknown| 2022| 4| | Las Palmas| 2025| 4| +-------------+-----------+-----+ (zone, signup_year) groups= 24 k= 2 single-person groups= 0 customers in groups with k<5=6 +-------+-----------+-----+ | zone|signup_year|count| +-------+-----------+-----+ |unknown| 2023| 2| |unknown| 2022| 4| |unknown| 2025| 6| |unknown| 2024| 8| +-------+-----------+-----+ only showing top 4 rows
The reading is clear. With province and signup month, the "nameless" table has k = 1: 198 customers are unique in their combination and two out of three are in groups of fewer than five. With the year, 29 customers remain at risk. With region and year, only 6, those with an unknown province, who would have to be suppressed (exercise 2). Each step gains protection and loses detail: that is the permanent trade-off between privacy and utility. With the two million real customers the groups would be much larger, but the check is the same, and rare combinations would still exist.
Three warnings about what you have just built:
- It is pseudonymisation, not anonymisation.
silver_pseudostill contains personal data: whoever has the key can recompute the pseudonyms, and a customer's order history may be enough to recognise them. - The key is the critical point. In production it lives in a secrets manager, only the load process uses it and the analysts have no access to it. If it changes, all the pseudonyms change.
- The access matrix from lesson 07-01 changes: Marc stops reading
silver/customersandsilver/orders_complete, and works onsilver_pseudo. Tables with direct identifiers are reserved for the processes that genuinely need them.
The re-identification risk
Removing names does not anonymise. Several datasets published as "anonymous" over the years (search histories, film ratings, taxi journeys, health records) ended up partially re-identified by cross-referencing them with other available sources: a census, a social network, a news story. A widely cited study estimated that the combination of postcode, date of birth and sex was enough to single out the vast majority of the population of the United States.
The lessons for a lake:
- The risk lies not in a single column but in the combination, and in what the attacker already knows.
- Behavioural data is a fingerprint: a handful of purchases or locations with their dates are usually unique.
- More data, more risk: every new source that is cross-referenced reduces the anonymity of all the others.
- Anonymisation is assessed, not assumed, and it is reassessed when new sources appear.
Impact assessment of NovaMarket's recommendations
A real DPIA is a lengthy document that follows the supervisory authority's methodology. This condensed template shows its structure, applied to the recommendations use case:
| Section | Content (teaching summary) |
|---|---|
| Description | Personalised recommendations on the website and the app based on order and browsing history; collaborative filtering model (lesson 04-03) |
| Data and individuals | Registered customers; orders, order_lines, web_events; no declared special categories |
| Purpose and basis | Improve the experience and sales; basis to be determined by the DPO, with consent for data coming from cookies |
| Necessity and proportionality | Is the full history needed, or are 12 months enough? Can the model be trained on pseudonyms? Is there a less intrusive alternative (best-sellers)? |
| Risks | Inference of sensitive traits from purchases; recommendations that reveal information to whoever shares the device; re-identification; breach |
| Measures | Training on silver_pseudo; exclusion of sensitive product categories; a visible option to turn off personalisation; limited retention; access control and auditing |
| Residual risk and decision | Assessment after the measures; DPO's opinion; review date |
Two of those risks, sensitive inferences and what a customer would consider acceptable, are not clearly resolved by any regulation. They are the territory of the next lesson.
Common Mistakes and Tips
- Believing that without a name there is no personal data.
customer_id,session_idand a purchase history all are. - Calling pseudonymised data "anonymised". The difference decides whether the law applies or not.
- Using an unkeyed hash on enumerable identifiers. It can be reversed by brute force in seconds.
- Collecting "just in case". Every piece of data without a purpose is cost, risk and a breach of the data minimisation principle.
- Forgetting the copies when erasing. Derived tables, topics, caches, backups and extracts count too.
- Choosing the lawful basis after building. First the purpose and the basis, with the DPO; then the pipeline.
- Tip: before using a table for something new, ask yourself three questions: what was this data collected for? Would the customer expect this? Can I do it with less?
Exercises
Exercise 1: classify and minimise
Marketing asks Marc for an extract with name, province, signup_date and the total amount spent by each customer, to "study which provinces spend the most". Classify each column, state which ones are necessary for that purpose and propose the minimum delivery.
Exercise 2: suppress what cannot be generalised
After generalising to (region, signup year), six customers remain in groups of fewer than five. Write the code that publishes only the rows from groups with k ≥ 5 and check the resulting k. What price is paid?
Exercise 3: an erasure request
Customer 123 exercises their right to erasure. List the places on NovaMarket's platform that hold their data, which of them cannot be erased immediately and why, and what you would do with each one.
Solutions
Exercise 1
name: direct identifier, unnecessary. province: quasi-identifier, necessary. signup_date: quasi-identifier, unnecessary for the question. Amount per customer: personal data, unnecessary at that level. The purpose is met with an aggregated table: province, number of customers and total and average spend. Around fifteen rows instead of two million, with no personal data at all (making sure that no province has so few customers that the aggregate gives someone away). The best protection is not to hand over the data.
Exercise 2
Add at the end of pseudonymise.py, before spark.stop():
from pyspark.sql import Window
group = Window.partitionBy("zone", "signup_year")
publishable = (by_zone.withColumn("group_size", F.count("*").over(group))
.where(F.col("group_size") >= MIN_K)
.select("customer_pseudo", "zone", "signup_year"))
print("Rows published:", publishable.count(), "of", by_zone.count())
print("k =", publishable.groupBy("zone", "signup_year").count().agg(F.min("count")).first()[0])The six customers with an unknown region who signed up in 2022 and 2023 are suppressed, and the table becomes 6-anonymous with respect to those two attributes. The price: 0.6% of the rows are lost, and not at random; if those customers behaved differently, the analysis would be slightly biased. Moreover, k-anonymity only covers the chosen quasi-identifiers: the order history linked through customer_pseudo remains a route to re-identification.
Exercise 3
Places: bronze/customers, bronze/orders, bronze/order_lines, bronze/web_events and bronze/reviews; their equivalents in silver and silver_pseudo; in gold, dim_customer, fact_sales and customer_segments; quarantine/orders; the Kafka topic for as long as its retention lasts; the Cassandra events_by_customer table and the Redis keys; backups and old object versions; extracts in analysts' hands; and, outside the lake, the shop database. The gold aggregates are not affected.
Not erased immediately: billing data, if a legal obligation requires it to be kept (it is blocked and its use restricted to that purpose); immutable backups, which will expire on their own schedule (or become unreadable if crypto-shredding is used); and the historical versions of the tables, until they are purged. For everything else: deletion from the tables, rebuilding of the derived ones, and documentary evidence. Which exceptions apply is for the DPO to decide; the response deadline is one month.
Conclusion
Privacy does not ask who can access the data, but what it is legitimate to do. You have seen that personal data covers almost everything in the lake, including customer_id, session_id and browsing history; that the GDPR and the LOPDGDD require a set of principles (purpose limitation, minimisation, storage limitation, accountability), a lawful basis for each processing activity and respect for rights that oblige you to know where every piece of data is and to be able to delete it, which is far from trivial with immutable files; and that the organisation must document, assess impact, notify breaches within 72 hours and keep track of where the data travels. On the technical side, you have distinguished pseudonymisation from anonymisation, built lake/silver_pseudo/ with HMAC and generalisation, and checked with k-anonymity that a table without names can still point to specific people.
Now suppose NovaMarket does everything right: legal basis, consent, pseudonyms, retention periods and impact assessment. Does that mean any use of the data is acceptable? Can it charge more to someone shopping from an expensive phone, or deduce from their shopping basket a personal situation the customer has told nobody about? These are things the law may not clearly prohibit, and that many customers would nonetheless regard as a betrayal. The next lesson, Ethics in the Use of Big Data, deals with that space between what is legal and what is right.
