Sub topic 3
Consent and privacy as design constraints
This chapter assumes you have read the previous chapter on the customer data foundation and identity. You should know what a customer profile is and how events are tied to an identity. You should also be comfortable reading short Python snippets and basic pandas code.
Consent and privacy rules are inputs to your personalisation system. They are not a legal review that happens after launch. If you treat them as a late check, you will find that features, segments and templates already depend on data you may not use. This chapter shows how to model consent as data, enforce it in code, and design segments and content so they stay valid when a customer changes their mind.
Why privacy is a design constraint
A constraint shapes the design from the start. In personalisation, three things follow from that.
- What data you may collect. Some signals need explicit permission before you store them.
- What you may do with data. A customer may agree to order emails but not to profiling for targeted offers.
- How long you may keep it. Old behaviour data often has to be deleted or anonymised.
Laws differ by region. The GDPR (the EU General Data Protection Regulation) and the UK GDPR require a lawful basis for processing personal data. Consent is one lawful basis, and legitimate interest is another. The CCPA/CPRA in California gives residents rights to opt out of the sale or sharing of their data. Email and SMS rules, such as PECR in the UK and CAN-SPAM in the US, add channel-specific requirements. This chapter is not legal advice. Ask your legal or privacy team which rules apply to you, then encode their answer in your system.
Key terms
| Term | Meaning |
|---|---|
| Personal data | Any information that relates to an identifiable person, including IDs, emails, device IDs and behaviour linked to them. |
| Purpose | The specific reason you process data, such as "order updates" or "personalised marketing". |
| Lawful basis | The legal ground for processing for a given purpose, such as consent or legitimate interest. |
| Consent | A freely given, specific, informed and unambiguous agreement, which the person can withdraw. |
| Data minimisation | Collecting and keeping only what you need for the stated purpose. |
| Pseudonymisation | Replacing direct identifiers with a token. The data is still personal data if you can link it back. |
| Sensitive data | Special categories such as health, religion, ethnicity or sexual orientation, which usually carry stricter rules. |
Model consent as data
Consent is not a single yes/no flag. A useful consent record answers four questions: who agreed, to which purpose, on which channel, and when. It also records where the agreement came from and which version of the policy text the customer saw.
A practical schema looks like this:
| Field | Example | Why it matters |
|---|---|---|
| customer_id | 1042 | Links consent to the profile |
| purpose | personalised_marketing | Separates marketing from service messages |
| channel | Consent often differs per channel | |
| status | granted, denied, withdrawn | Withdrawal must be recorded, not just deleted |
| timestamp | 2026-03-14T09:12:00Z | Lets you reconstruct what was allowed at a given time |
| source | preference_centre | Gives you evidence for audits |
| policy_version | v3 | Shows what wording the customer accepted |
Keep this as an append-only history. When a customer withdraws consent, you add a new row. You do not overwrite the old one. The current state is the latest row for each customer, purpose and channel.
Enforce consent in code
The most common failure is a consent flag that exists but that no pipeline reads. Put the check in one place and make every downstream job call it.
import pandas as pd
consent_log = pd.DataFrame({
"customer_id": [1, 1, 2, 3, 3],
"purpose": ["personalised_marketing"] * 5,
"channel": ["email"] * 5,
"status": ["granted", "withdrawn", "granted", "denied", "granted"],
"timestamp": pd.to_datetime([
"2026-01-05", "2026-02-10", "2026-01-20", "2026-01-22", "2026-03-01",
]),
})
def current_consent(log, purpose, channel):
"""Return the latest status per customer for one purpose and channel."""
subset = log[(log["purpose"] == purpose) & (log["channel"] == channel)]
latest = subset.sort_values("timestamp").groupby("customer_id").tail(1)
return latest.set_index("customer_id")["status"]
status = current_consent(consent_log, "personalised_marketing", "email")
allowed_ids = status[status == "granted"].index
print(allowed_ids.tolist())The output is [2, 3]. Customer 1 granted and later withdrew, so they are excluded. Customer 3 denied first and then granted, so the later decision wins.
Two design choices matter here.
- Default to no. A customer with no consent row is not in
allowed_ids. The code excludes by default, which is the safe failure mode. - Filter early. Apply the consent filter before feature engineering and model training, not only before sending. Otherwise a model may learn from data you were not allowed to use for that purpose.
Where consent sits in the pipeline
Consent checks belong at several points. A check at only one point leaves gaps.
The send-time check exists because time passes between building a segment and using it. A customer can withdraw consent at 09:00 after a segment was built at 02:00. The send-time check reads the live consent store, so the withdrawal takes effect at once.
Data minimisation and feature choice
Ask of every feature: do we need it, and are we allowed to use it for this purpose? The RFM features used later in this tutorial (recency, frequency, monetary value) are a good example. They are derived from purchase history and are usually justifiable for marketing to existing customers. A feature such as "inferred health condition from basket contents" is much harder to defend.
Some practical rules:
- Prefer coarse values to precise ones. Use an age band instead of a birth date, and a postcode district instead of a full address.
- Avoid sensitive attributes, and avoid proxies for them. A model can infer a protected trait from seemingly harmless inputs such as product categories or location.
- Record the purpose for each feature in your feature catalogue, so a reviewer can see why it exists.
- Set a retention period for raw events and for derived features. Delete or aggregate once it expires.
Pseudonymisation and access control
Segmentation rarely needs a name or an email address. The analysts and models that build segments can work with a pseudonymous key. Only the activation step, which sends the message, needs the contact details.
import hashlib
import hmac
SECRET_KEY = b"load-this-from-a-secrets-manager"
def pseudonymise(customer_id: str) -> str:
"""Return a stable token for a customer ID using a keyed hash."""
return hmac.new(SECRET_KEY, customer_id.encode("utf-8"), hashlib.sha256).hexdigest()
print(pseudonymise("customer-1042")[:16])A keyed hash (HMAC) is better than a plain hash. Anyone can hash a list of known email addresses and compare the results to a plain hash, but they cannot do that without the key. In real code, load the key from a secrets manager and never commit it to source control.
Remember that a pseudonymous token is still personal data when you hold the key or the mapping table. Pseudonymisation lowers risk, but it does not remove your obligations.
Design segments that survive consent changes
Consent changes the membership of a segment over time. Build for that.
- Rebuild or re-filter on every refresh. A segment is a query result at a point in time, not a permanent list.
- Store the segment definition, not only the member list. You can then re-run it with the current consent state.
- Support deletion requests. When a customer asks for erasure, remove them from raw data, features, model training sets and exported audiences. Check that downstream copies, such as lists uploaded to ad platforms, are covered.
- Keep a suppression list. Record opt-outs and erasure requests so that re-imported data does not bring the person back.
Think about models too. A trained model may have learned from a person who later withdrew. Whether you must retrain is a legal question for your privacy team. Technically, plan for periodic retraining on current consent-filtered data so that withdrawals are reflected over time.
Consent and dynamic content
Consent also affects what a template may show. A message might use data the customer allowed for service messages but not for marketing. Treat each personalised field as having a purpose.
A simple approach is to give the template only the fields allowed for the current purpose. If a field is not allowed, it is absent, and the template's fallback handles the gap. The later chapter on templates and fallbacks covers this pattern in detail. The key point here is that the consent filter runs before rendering, so the template cannot leak a field it was never given.
ALLOWED_FIELDS = {
"service": {"first_name", "order_status"},
"personalised_marketing": {"first_name", "segment", "last_category"},
}
def fields_for(purpose: str, profile: dict) -> dict:
"""Return only the profile fields permitted for a purpose."""
allowed = ALLOWED_FIELDS.get(purpose, set())
return {k: v for k, v in profile.items() if k in allowed}
profile = {
"first_name": "Ana",
"order_status": "shipped",
"segment": "lapsed",
"last_category": "running shoes",
"birth_date": "1990-04-02",
}
print(fields_for("service", profile))
print(fields_for("personalised_marketing", profile))The birth_date field appears in neither output because no purpose lists it. An unknown purpose returns an empty dictionary, which again fails safe.
Common mistakes
- Treating a boolean as consent. A single
opted_incolumn loses the purpose, channel, time and source. You then cannot prove what was agreed. - Filtering only at send time. Models and segments built on non-consented data are still a problem, even if the message never goes out.
- Ignoring identity merges. If two profiles are merged, the merged profile must take the stricter consent state, or you must re-check each purpose.
- Overwriting history. If you delete the old row on withdrawal, you cannot show what you were permitted to do last month.
- Forgetting copies. Exports, caches, notebooks and uploaded audiences hold personal data. Include them in deletion and refresh processes.
- Dark patterns. Pre-ticked boxes and confusing wording do not produce valid consent in most jurisdictions. Make accepting and declining equally easy.
Summary
- Consent is a record with purpose, channel, status, time, source and policy version. Keep it append-only.
- Default to exclusion when no consent record exists.
- Filter by consent before features and models, and check again at send time.
- Collect less, use coarse values, and avoid sensitive attributes and their proxies.
- Use pseudonymous keys for analysis, and keep contact details in the activation step.
- Design segments as re-runnable definitions so they follow consent changes.
Exercise
A customer granted marketing consent in January and withdrew it in March. A segment was built in February and exported on 1 March to an ad platform. Name two places where the customer's data may still cause a problem, and say what check or process fixes each.
Show answer
First, the exported audience on the ad platform still contains the customer. Fix it with a send-time or activation-time check against the live consent store, and a process that removes withdrawn customers from uploaded audiences on each refresh. Second, any model or feature table built in February may include the customer's behaviour. Fix it by filtering on current consent before feature building and by retraining on consent-filtered data on a regular schedule, with the privacy team deciding how quickly this must happen. Also record the withdrawal as a new row in the append-only consent log, and add the customer to the suppression list.
Exercise
In the current_consent function, what happens to a customer who has no rows in the consent log, and why is that the right behaviour?
Show answer
The customer does not appear in the returned status series, so they are not in allowed_ids and are excluded from segments and sends. This is the right behaviour because absence of a consent record means permission was never given. Failing closed avoids contacting or profiling someone without a recorded basis.