Sub topic 2
Building the customer data foundation
This chapter covers the data layer that every later step depends on: segments, features, templates and tests. It assumes you know basic marketing terms (campaigns, channels, conversion), can read tabular data, and can follow short Python programs. Consent rules get their own chapter, so here they appear only as a field you must store.
Why the data layer comes first
A segmentation model can only group what it can see. If one person appears as three customers, or if purchase data and email data cannot be joined, every later result is wrong in a way that is hard to spot. A clustering run on bad data still produces tidy clusters.
The foundation has four jobs:
- Collect events and attributes from each source.
- Resolve identity, so records that belong to one person are linked.
- Clean and standardise values, so the same thing is always written the same way.
- Store the result in a shape that segmentation and content systems can query.
Data sources and what each one gives you
Most programmes pull from a handful of systems. Each has its own strengths and its own blind spots.
| Source | Typical content | Strength | Common weakness |
|---|---|---|---|
| Transactions (orders, returns) | Order id, items, amount, timestamp | Reliable, tied to real money | Only shows buyers, and often arrives late |
| Web and app events | Page views, searches, add to basket | Rich, near real time | Anonymous until login, noisy, bots |
| Email and messaging | Sends, opens, clicks, unsubscribes | Shows channel response | Open rates are distorted by mail privacy features |
| CRM and loyalty | Name, address, tier, preferences | Declared by the customer | Often stale or incomplete |
| Support and returns | Tickets, complaints, refund reasons | Signals dissatisfaction | Free text, hard to structure |
| Third-party data | Demographics, enrichment | Fills gaps | Cost, accuracy and legal risk |
Prefer first-party data (collected directly from your own customers) where you can. It is more accurate for your business and easier to justify under privacy rules.
The three kinds of data you will store
Separating data by its shape keeps the design clear.
- Events are things that happened: an order, a click, a login. Each has a timestamp and never changes after it is written.
- Attributes are facts about a customer that can change: city, loyalty tier, preferred language. Store when they changed, not only their current value.
- Derived values are computed from the other two, such as "orders in the last 90 days". The next chapters call these features. Keep them separate from raw data so you can rebuild them when the definition changes.
Keep raw events in their original form. If you only keep derived values, you cannot recompute them after you find a bug.
Identity resolution
Identity resolution is the process of deciding which records refer to the same person. It matters because a customer may browse on a phone, buy on a laptop, and subscribe to email with a different address.
There are two approaches, and most programmes combine them.
- Deterministic matching links records that share an exact identifier, such as a login id or a verified email address. It is precise but only covers people who identify themselves.
- Probabilistic matching links records that are likely the same, using signals like device, name similarity and location. It covers more people but makes mistakes.
The two kinds of mistake cost different amounts. A false merge joins two different people. This is the worse error, because one person may receive messages based on another person's purchases, which can expose private information. A false split leaves one person as two profiles. This only weakens the data. For personalisation, set matching thresholds conservatively and prefer false splits.
A durable customer key
Do not use an email address as the primary key. Emails change and get reused. Instead, create an internal customer_id and keep a mapping table from each external identifier to it.
The sketch below builds such a mapping from deterministic matches. It treats two records as the same customer when they share a normalised email, and it assigns each group one customer_id.
import pandas as pd
records = pd.DataFrame({
"source": ["web", "orders", "orders", "loyalty", "web"],
"email": [
"[email protected] ",
"[email protected]",
"[email protected]",
"[email protected]",
None,
],
"source_id": ["c-101", "o-9", "o-12", "L-77", "c-102"],
})
records["email_clean"] = records["email"].str.strip().str.lower()
known = records.dropna(subset=["email_clean"]).copy()
known["customer_id"] = known.groupby("email_clean").ngroup() + 1
unknown = records[records["email_clean"].isna()].copy()
start = known["customer_id"].max() + 1
unknown["customer_id"] = range(start, start + len(unknown))
mapping = pd.concat([known, unknown])[["source", "source_id", "customer_id"]]
print(mapping.sort_values("customer_id").to_string(index=False))The three records for Ana share one customer_id, Bo gets another, and the web record with no email stays on its own. That last record is a false split you accept for now. If the visitor later logs in, you add a link and merge the profiles.
Real systems also need to handle un-merging. Keep a log of every link and the rule that created it, so a wrong merge can be reversed without rebuilding everything.
Cleaning and standardising
Messy values quietly break segments. A customer whose country is "UK", "U.K." and "United Kingdom" will fall into three groups. Common cleaning steps:
- Normalise case, whitespace and formats (emails, phone numbers, postcodes, dates).
- Convert all timestamps to one time zone, normally UTC, and store the customer's local zone separately. Mixed zones shift "last 7 days" windows and send-time logic.
- Convert currencies to one reporting currency and record the exchange rate used.
- Remove test accounts, staff orders and bot traffic. Bots inflate event counts and create fake highly engaged customers.
- Deduplicate events. Retries in tracking code often send the same event twice.
Missing data and data quality checks
Missing values are normal. What matters is whether they are random or systematic. If app users rarely have an email address, then "email missing" is really a proxy for "app only", and a model may treat it that way without telling you.
Automate checks so problems surface before a campaign goes out:
- Completeness: share of customers with a value in each key field.
- Uniqueness: no duplicate
customer_idor duplicate order id. - Validity: values in range (no negative quantities, no future order dates).
- Freshness: the newest event in each source is recent enough.
- Volume: today's event count is within a normal range of the past weeks.
The freshness and volume checks catch the most damaging failure, which is a silent pipeline break. If the order feed stops for three days, every customer looks like they stopped buying, and a clustering or churn model will report a dramatic and false rise in lapsed customers.
import pandas as pd
orders = pd.DataFrame({
"order_id": [1, 2, 2, 3, 4],
"customer_id": [10, 11, 11, 12, 13],
"amount": [50.0, 30.0, 30.0, -5.0, None],
"ordered_at": pd.to_datetime(
["2026-11-20", "2026-11-21", "2026-11-21", "2026-11-22", "2026-12-30"]
),
})
as_of = pd.Timestamp("2026-11-26")
checks = {
"duplicate_order_ids": int(orders["order_id"].duplicated().sum()),
"negative_amounts": int((orders["amount"] < 0).sum()),
"missing_amounts": int(orders["amount"].isna().sum()),
"future_dates": int((orders["ordered_at"] > as_of).sum()),
"days_since_latest": (as_of - orders["ordered_at"][orders["ordered_at"] <= as_of].max()).days,
}
for name, value in checks.items():
print(f"{name}: {value}")This prints one duplicate order id, one negative amount, one missing amount, one future date, and four days since the latest valid order. In production you would compare these numbers to thresholds and stop the pipeline or alert someone when one is exceeded.
Designing the customer profile
The output of the foundation is a customer profile: one row per customer_id that later steps read. A good profile has these properties.
- Point-in-time correctness. You can ask "what did we know about this customer on 1 October?" This matters for predictive models. If you train a churn model using data that was only available after the outcome, it looks accurate in testing and fails in production. This error is called data leakage.
- Documented definitions. "Active customer" must mean one thing everywhere. Write it down, version it, and store it in code.
- Consent fields next to the data. Store the consent status, its purpose, its source and its timestamp for each customer. Later chapters use these to decide what may be used for which purpose.
- Minimal fields. Keep only what a use case needs. Every extra field adds privacy risk and maintenance cost.
A simple layout has three layers:
| Layer | Contents | Who uses it |
|---|---|---|
| Raw | Events and records exactly as received | Engineers, for rebuilding and audit |
| Clean | Deduplicated, standardised, identity-resolved | Analysts and data scientists |
| Profile | One row per customer with derived values and consent | Segmentation, content and decisioning systems |
Batch and real-time paths
Not all data needs to arrive instantly. Decide per use case.
- Batch pipelines run on a schedule, such as nightly. They suit segment membership, RFM scores and reporting. They are cheaper and easier to debug.
- Real-time pipelines process events as they happen. They suit triggers such as an abandoned basket message or showing a different banner after a search.
Many programmes use both: nightly batch to compute stable segments, plus a small set of real-time signals that adjust content within a visit. Start with batch. Add real-time only for the cases where minutes matter to the result.
Common mistakes
- Building segments before agreeing on identity, which produces duplicated or merged customers.
- Using email as the key.
- Overwriting attributes, so history is lost and point-in-time questions cannot be answered.
- Mixing time zones or currencies.
- Treating missing as zero.
- Having no freshness check, so a broken feed goes unnoticed.
- Collecting every field available instead of the fields a use case needs.
Exercise
A clustering model suddenly reports that 40% of customers are in a "lapsed" segment, up from 15% last week. No campaign change explains it. Name two data foundation checks you would run first, and say what each might reveal.
Show answer
Run a freshness check on each source and a volume check on daily order events. If the order feed stopped or lagged, customers would look like they had stopped buying, which inflates the lapsed segment. A second useful check is identity resolution: a change in matching rules could have split customers into many new profiles with no history, or the mapping table may have failed to load. Either problem would be a data fault, not a real change in behaviour.
Exercise
Why should identity matching thresholds be set so that false splits are preferred over false merges?
Show answer
A false merge combines two different people, so one person can receive content based on another person's purchases or browsing, which can expose private information and feels wrong to the recipient. A false split only leaves one person with two thinner profiles, which weakens personalisation but does no harm. The cost of a merge error is higher, so the matching rule should be conservative.