Duplicates and entity resolution: how to make one customer one record

TL;DR

Difficulty: Advanced

Duplicate customer records quietly distort the customer count, the repeat rate, lifetime value and acquisition cost.

  • Exact duplicates (double loads, redelivered webhooks) go with a natural key and a fixed tie breaker, never with DISTINCT.
  • Near duplicates need match keys (lower case email, the Gmail key for Gmail only, E.164 phones, name and Eircode keys), blocking, similarity measures and the Fellegi Sunter match weights.
  • Set the threshold from the cost of each mistake: merging two people is far worse than missing one, so the doubtful middle goes to a person.
  • Merge through a mapping table, never by deleting, let an opt out anywhere apply to the person, and restate every metric. In the example, 68,400 customers become 66,280 people and the repeat rate rises from 24.0% to 26.8%.

Ask how many customers a shop has and you get a number at once. Ask how many of them are the same person counted twice, and nobody knows. This chapter shows how to find out, step by step and with the maths written out, and how to merge records so that the result is right, explainable and reversible.

One person, three records, and nobody noticed

Ask a shop owner how many customers they have and you get a number straight away. Ask how many of those are the same person counted twice, and the room goes quiet. The honest answer is almost always "some", and the number matters more than it looks: it sits underneath the customer count, the repeat rate, lifetime value, acquisition cost and every email you send.

This chapter answers one question: how do I make sure one customer is one record? The work has a name. Removing rows that are literally the same is deduplication. Deciding that two different looking rows describe the same real person is record linkage, and when the goal is one clean record per person, people call the whole job entity resolution. The entity is the real thing (a person, a company, a product). The records are what your systems wrote down about it.

There are two kinds of duplicate, and they need different tools. Exact duplicates are the same row twice, usually because a load ran twice or a message arrived twice. They are easy to remove, and the only skill is removing them deterministically, so that the same input always gives the same output. Near duplicates are different rows about the same person: a different spelling, a different email, an old address. Finding them takes normalising, comparing, scoring and deciding, and it can go wrong in two directions. You can miss a match, or you can merge two different people. The second mistake is far worse, and much of this chapter is about avoiding it.

The chapter on when to clean data and when to leave it alone put duplicate customers on the list of problems that need cleaning in the pipeline, because the source cannot stop all of them. Here is how.

Example: Siobhán Byrne appears three times

Shannonside Home is the invented online homeware shop in Limerick (shannonsidehome.example) that this series follows. Niamh owns it. Callum builds the shop on Ruby on Rails and Solidus and looks after its data. The shop has five years of order history, and its report says it has had 68,400 customers, counting every account and every guest checkout email that placed at least one order.

Callum's profiling (from the chapter on finding out how dirty your data really is) flagged that 3.1% of those customer records are duplicates. One of them is Siobhán Byrne, an invented customer:

RecordSourceEmail as storedNameEircodePhoneOrders
user:20417account, imported from the old platform in 2021Siobhan.Byrne@gmail.com (trailing space)Siobhan Byrne (the old platform dropped the fada)V94 X7K2(empty)2
guest:siobhanbyrne+sale@gmail.comguest checkout, 2023siobhanbyrne+sale@gmail.comSiobhán Byrnev94x7k2087 555 01231
guest:s.byrne@limerickdental.exampleguest checkout from work, 2025s.byrne@limerickdental.exampleSiobhán ByrneV94 X7K2+353 87 555 01231

To the shop these are three customers: two of them one time buyers, one a repeat buyer. In reality they are one woman who has ordered four times. She gets the newsletter at two addresses, she counted as a new customer twice after her first order, and any lifetime value model sees three short histories instead of one long one. By the end of the chapter, all three rows point at one customer, with the decision written down and reversible.

Exact duplicates: the same row twice

An exact duplicate is a row that should exist once and exists twice or more. In a data pipeline they come from a handful of places:

  • Retries. A job loads a file, times out before it records success, and the scheduler runs it again.
  • Messages delivered more than once. Webhooks and message queues usually promise "at least once", not "exactly once". Stripe says so plainly: a webhook endpoint "might occasionally receive the same event more than once", and the fix it recommends is to log the event IDs you have processed and skip the ones you have already seen1.
  • Overlapping extracts. A daily export that covers "the last three days" to be safe hands you each row three times.
  • Joins. Joining orders to payments when an order has two payment rows doubles the order. This is not a duplicate in the data but in the query, and the chapter on SQL traps every data engineer must know covers it.

The tool for exact duplicates is a natural key: the column or columns that identify a real world thing in the source, such as a Stripe balance transaction ID, an order number, or the 3PL's shipment number plus line number. You keep one row per key, and you decide in advance which row wins when the copies differ. "Pick any" is not a rule. It makes the output depend on the order the database happens to read the rows in, which changes between runs.

Two habits make this safe. First, every raw row carries load metadata: when it was loaded (_loaded_at), from which file (_source_file) and in which batch (_batch_id). Second, the tie breaker always ends in something unique, so two copies can never tie.

SELECT DISTINCT * is not deduplication. It only removes rows that agree in every column, so two copies that differ only in their load time both survive, and it hides the question of which copy should win.

Example: the Stripe file that loaded twice

On 3 November the job that loads Stripe balance transactions for October timed out after writing its rows and was retried. The raw table now holds 4,082 rows for October instead of 2,041, and the settlement total in the finance report has doubled.

The natural key is Stripe's balance transaction id. Callum keeps the most recently loaded copy and breaks any tie on the batch ID. In PostgreSQL:

-- PostgreSQL: one row per Stripe balance transaction, the latest load wins
select *
from (
  select
    t.*,
    row_number() over (
      partition by t.id
      order by t._loaded_at desc, t._batch_id desc
    ) as rn
  from raw.stripe_balance_transactions as t
) as ranked
where rn = 1;

row_number() numbers the rows inside each group of identical id values, in the order given. The newest copy gets 1, and the outer query keeps only the ones. PostgreSQL also has a shorter form, DISTINCT ON, which keeps the first row of each group according to the ORDER BY2. The same rule, shorter:

-- PostgreSQL: the same rule with DISTINCT ON
select distinct on (id) *
from raw.stripe_balance_transactions
order by id, _loaded_at desc, _batch_id desc;

In BigQuery the same rule is written with QUALIFY, which filters on a window function without a subquery3. In BigQuery SQL:

-- BigQuery: keep the latest copy of each balance transaction
select *
from raw.stripe_balance_transactions
qualify row_number() over (
  partition by id
  order by _loaded_at desc, _batch_id desc
) = 1;

The result: 2,041 rows, the settlement total back to its true value, and the raw table untouched, so the double load stays visible for anyone who needs to see what happened. Callum then adds a test so the next double load fails loudly instead of quietly. In dbt Core the generic unique and not_null tests sit under data_tests in the model's properties file4. For the staging model:

models:
  - name: stg_stripe__balance_transactions
    columns:
      - name: balance_transaction_id
        data_tests:
          - unique
          - not_null

Near duplicates need record linkage, not a DISTINCT

Siobhán's three rows share no key at all. The emails differ, the phone is missing on one, the Eircode is written two ways. No GROUP BY brings them together. This is the record linkage problem: decide, for pairs of records, whether they describe the same person.

There are two families of approach:

  • Deterministic linkage uses rules. "Two records are the same person if their normalised emails are equal." Rules are fast, easy to explain and easy to test. They miss anything the rule did not foresee.
  • Probabilistic linkage scores the evidence. Agreeing on a rare surname counts for more than agreeing on a common one, agreeing on a phone number counts for a lot, disagreeing on email counts against a match but not decisively. The score becomes a probability, and a threshold turns it into a decision.

In practice you run both, in that order: fast, certain rules first, then the probabilistic model on what is left. Every stage depends on the inputs being comparable, so the first real step is normalisation.

Normalise before you compare

Normalising means turning each value into a standard form so that two spellings of the same thing become equal. The standardising chapter later in this series covers it for every kind of value. Here the focus is narrower: the fields that identify a person, and the traps that are specific to matching.

One rule runs through all of it. The normalised value is a match key, a new column used for comparing. It never overwrites what the customer typed, and it is never used to send anything.

Email addresses: case, whitespace and the Gmail question

The safe part is easy: trim leading and trailing whitespace and convert to lower case. Strictly speaking, the email standard says the part before the @ "MUST BE treated as case sensitive", but it also says that relying on that "impedes interoperability and is discouraged"5. Real mail services do not hand out addresses that differ only in case, and lower casing is the normal practice. Devise, the sign in library behind Solidus accounts, lower cases and trims the email on accounts by default6.

The less safe part is provider specific. Gmail ignores dots in the part before the @, so siobhan.byrne@gmail.com and siobhanbyrne@gmail.com reach the same inbox7. Gmail also delivers siobhanbyrne+sale@gmail.com to siobhanbyrne@gmail.com, a feature people use to sort their mail8. Two warnings follow:

  • This applies to Gmail addresses only. Google says itself that for work or school accounts on Google, dots do change the address7. Other providers have their own rules, and many treat dots and plus signs as ordinary characters. Never strip dots from @leedsdental.example.
  • Even for Gmail, the canonical form is a matching key, not a fact about the customer. Two people can never share a Gmail inbox by dots alone, so for Gmail it is a strong signal. It is still not a reason to change the address you write to.

Example: four spellings of one inbox

Callum builds two keys from each email in PostgreSQL. email_norm is trimmed and lower case. email_match_key additionally applies the Gmail rules, and only to gmail.com:

-- PostgreSQL: two match keys from one raw email
select
  record_key,
  email_raw,
  lower(btrim(email_raw)) as email_norm,
  case
    when split_part(lower(btrim(email_raw)), '@', 2) = 'gmail.com' then
      replace(split_part(split_part(lower(btrim(email_raw)), '@', 1), '+', 1), '.', '')
      || '@gmail.com'
    else lower(btrim(email_raw))
  end as email_match_key
from stg_customer_records;

Reading the Gmail branch from the inside out: split_part(..., '@', 1) takes the part before the @, split_part(..., '+', 1) cuts everything from the first plus sign, and replace(..., '.', '') removes the dots. For Siobhán and two invented addresses:

email_rawemail_normemail_match_key
Siobhan.Byrne@gmail.com siobhan.byrne@gmail.comsiobhanbyrne@gmail.com
siobhanbyrne+sale@gmail.comsiobhanbyrne+sale@gmail.comsiobhanbyrne@gmail.com
s.byrne@limerickdental.examples.byrne@limerickdental.examples.byrne@limerickdental.example
J.Okafor+wren@outlook.examplej.okafor+wren@outlook.examplej.okafor+wren@outlook.example

The first two rows now share a match key. The third is untouched because it is not Gmail, and so is the fourth, plus sign and all. Across all 68,400 records, equal email_norm alone links 1,184 surplus records (mostly guest checkouts by people who also have an account), and the Gmail key adds another 96.

Phone numbers to E.164

E.164 is the international numbering plan of the International Telecommunication Union (ITU): a plus sign, the country code, then the national number without its leading zero, at most 15 digits in all9. It turns "087 555 0123", "+353 (0)87 555 0123" and "00353 87 5550123" into one value. Do not write your own parser for it. Google's libphonenumber knows the numbering rules of every country, and the Python port phonenumbers exposes it10.

Two details matter for matching. Parse with a default region taken from the order's country, because a number without a country code means nothing on its own. And remember that "valid" means "fits the numbering plan", not "rings someone". German numbers, for example, vary in length, so a short German number can pass.

Example: one function, every way of writing an Irish mobile number

The numbers below are invented for the example.

import phonenumbers
from phonenumbers import NumberParseException, PhoneNumberFormat


def to_e164(raw: str | None, default_region: str) -> str | None:
    """Return the number in E.164, or None when it is empty or not valid."""
    if raw is None or not raw.strip():
        return None
    try:
        number = phonenumbers.parse(raw, default_region)
    except NumberParseException:
        return None
    if not phonenumbers.is_valid_number(number):
        return None
    return phonenumbers.format_number(number, PhoneNumberFormat.E164)


def test_every_spelling_gives_one_value():
    for raw in ["087 555 0123", "+353 (0)87 555 0123", "00353 87 5550123", "87 555 0123"]:
        assert to_e164(raw, "IE") == "+353875550123"


def test_rubbish_becomes_none_not_a_guess():
    assert to_e164("087 555", "IE") is None
    assert to_e164("n/a", "IE") is None
    assert to_e164("", "IE") is None

All four spellings come out as +353875550123. The fragment, the "n/a" and the empty string come out as None, never as a guess. This matters for the about 2% of Shannonside Home's orders with a missing or invalid phone: in matching, a missing value is no evidence either way, and the model treats it that way later in this chapter.

Names: case, accents, umlauts, fadas and apostrophes

Names are where matching gets cultural, and where a careless rule does real harm. The typical differences between two records of the same person:

  • Case and spacing: "siobhán byrne", "SIOBHÁN BYRNE".
  • Accents dropped by a keyboard or an old system: "Zoë" and "Zoe", "Siobhán" and "Siobhan". Irish names in particular arrive with and without the fada.
  • German umlauts written out: "Müller" and "Mueller", "Strauß" and "Strauss". The convention of writing ü as ue is standard in German when the letter is not available, so both forms are the same name.
  • Apostrophes and spaces in prefixes: "O'Brien", "OBrien", "O Brien".
  • Initials and nicknames: "S. Byrne", "Kate" for "Catherine".

A name key should collapse the first four kinds and leave the fifth to the similarity measures below. Pick one transliteration and use it everywhere. PostgreSQL's unaccent extension removes accents using a rules file11, and its default rules map ü to u and ß to ss12. That turns "Müller" into "muller" while "Mueller" stays "mueller", so in SQL you replace the umlauts first and then remove the remaining accents. Python's standard library can do the same:

import re
import unicodedata

UMLAUTS = str.maketrans({"ä": "ae", "ö": "oe", "ü": "ue"})


def name_key(name: str | None) -> str | None:
    """A matching key for a personal name. Never shown, never stored as the name."""
    if not name or not name.strip():
        return None
    s = unicodedata.normalize("NFKC", name).casefold()  # casefold turns ß into ss
    s = s.translate(UMLAUTS)
    s = unicodedata.normalize("NFKD", s)                 # split letters from accents
    s = "".join(c for c in s if not unicodedata.combining(c))
    s = re.sub(r"[^a-z ]", "", s)                        # drop apostrophes and the like
    return re.sub(r"\s+", " ", s).strip()


assert name_key("Siobhán O'Brien") == "siobhan obrien"
assert name_key("Jürgen Müller") == name_key("Juergen Mueller") == "juergen mueller"
assert name_key("  SIOBHÁN   Byrne ") == "siobhan byrne"

Two limits are worth knowing. No string rule links an Irish form and its anglicised form, such as "Ó Súilleabháin" and "O'Sullivan": that takes a lookup table or other evidence. And a name key is a key, not a correction. The customer's name stays exactly as they wrote it, fada included.

Eircodes and addresses

Ireland has a gift for record linkage: the Eircode. It has seven characters, a three character routing key for the area and a four character unique identifier, and each Eircode is unique to a postal address13. Upper case it and remove the space: "v94x7k2", "V94 X7K2" and "V94 X7K2" all become V94X7K2. Two records with the same Eircode point at the same address, which makes it a very strong field, much stronger than postal codes in many other countries. Older records often have no Eircode at all, and then the address lines have to carry the load. Full address matching (townlands, "Apt 2" versus "2", house names) is harder, and the standardising chapter later in this series deals with it. For linking people, Eircode plus name plus phone is usually enough.

Example: Siobhán's three records after normalising

record_keyemail_match_keyname_keyeircode_keyphone_e164
user:20417siobhanbyrne@gmail.comsiobhan byrneV94X7K2(none)
guest:siobhanbyrne+sale@gmail.comsiobhanbyrne@gmail.comsiobhan byrneV94X7K2+353875550123
guest:s.byrne@limerickdental.examples.byrne@limerickdental.examplesiobhan byrneV94X7K2+353875550123

The first two now link deterministically on the email key. The third shares the name, the Eircode and the phone with the second, but not the email. Whether that is enough is a question for the probabilistic model.

Blocking: you cannot compare everyone with everyone

To find near duplicates you compare pairs of records. The number of pairs grows with the square of the number of records:

P=n(n−1)2P = \frac{n(n-1)}{2}

where PP is the number of distinct pairs and nn the number of records. Each record is paired with the n−1n-1 others, and dividing by two counts each pair once. Foundations: probability covers counting pairs and combinations.

Blocking is the fix. You only compare records that share something quick to check: the same Eircode key, the same phone, the same surname and first initial. Each such rule is a blocking rule, and the candidate pairs are the union of the pairs each rule produces. A good set of rules cuts the pairs by many orders of magnitude while keeping almost every true match, because a true duplicate nearly always agrees on at least one of several strong fields. The textbook treatment, with many more indexing techniques, is Peter Christen's Data Matching14.

The risk of blocking is quiet: a pair that no rule brings together is never compared, so the model cannot find it. That is why you use several rules, each on a different field, rather than one strict rule.

Example: from 2.3 billion pairs to 186,400

Shannonside Home has n=68,400n = 68{,}400 customer records:

P=68,400×68,3992=2,339,245,800P = \frac{68{,}400 \times 68{,}399}{2} = 2{,}339{,}245{,}800

So PP is about 2.3 billion pairs. Callum blocks on four rules: the same eircode_key, the same phone_e164, the same email_match_key, and the same surname key plus the first letter of the first name. Together they produce 186,400 candidate pairs, which is

186,4002,339,245,800=0.0000797\frac{186{,}400}{2{,}339{,}245{,}800} = 0.0000797

or 0.008%0.008\% of all pairs. Siobhán's third record is in the candidates twice over, once through the Eircode rule and once through the phone rule, so even if one field had been mistyped she would still have been compared.

How alike are two strings?

Exact equality is too strict for names: "Whitaker" and "Whittaker", a surname found on both sides of the Irish Sea, are one typo apart. String similarity measures put a number on "almost the same". Two of them do most of the work in record linkage.

Levenshtein distance

The Levenshtein distance between two strings is the smallest number of single character insertions, deletions and substitutions that turns one into the other15. It is a distance, so 0 means identical. Its weakness for names is that it ignores length: one edit in a four letter name is a much bigger difference than one edit in a twelve letter one. You can divide by the length of the longer string to get a normalised similarity.

Example: three Levenshtein distances

  • "whitaker" to "whittaker": insert one t. Distance 1.
  • "mueller" to "muller": delete one e. Distance 1. (With the raw umlaut, "müller" to "mueller" is 2: substitute ü with u, then insert e. Transliterating first brings it to 0.)
  • "catherine" to "kathryn": distance 4. These may well be the same person, but no edit distance will say so. Nicknames and name variants need a lookup, not arithmetic.

The Jaro similarity and Winkler's prefix bonus

Matthew Jaro designed a similarity for the 1985 United States census matching, and William Winkler of the US Census Bureau extended it with a bonus for strings that start the same way, because typing errors are rarer at the start of a name16. Both give a similarity between 0 and 1, where 1 means identical.

sJ=13(m∣a∣+m∣b∣+m−tm)s_J = \frac{1}{3}\left(\frac{m}{|a|} + \frac{m}{|b|} + \frac{m - t}{m}\right)

where sJs_J is the Jaro similarity of strings aa and bb, ∣a∣|a| and ∣b∣|b| are their lengths, mm is the number of matching characters (the same character, no further apart than half the longer length minus one), and tt is half the number of matching characters that appear in a different order. If m=0m = 0, then sJ=0s_J = 0. Foundations: ratios and rates explains the fractions inside it.

sW=sJ+ℓ p (1−sJ)s_W = s_J + \ell \, p \, (1 - s_J)

where sWs_W is the Jaro Winkler similarity, ℓ\ell the length of the common prefix (counted up to 4 characters), and pp the prefix weight, 0.1 by default in most libraries, including RapidFuzz17. The bonus closes part of the gap between sJs_J and 1, more for a longer shared start.

Example: Whitaker and Whittaker, by hand

Take aa = "whitaker" (∣a∣=8|a| = 8) and bb = "whittaker" (∣b∣=9|b| = 9). Every letter of "whitaker" finds its partner in "whittaker" within the allowed distance, so m=8m = 8. They appear in the same order, so t=0t = 0.

sJ=13(88+89+8−08)=13(1+0.8889+1)=0.9630s_J = \frac{1}{3}\left(\frac{8}{8} + \frac{8}{9} + \frac{8 - 0}{8}\right) = \frac{1}{3}(1 + 0.8889 + 1) = 0.9630

Both start with "whit", so ℓ=4\ell = 4, and with p=0.1p = 0.1:

sW=0.9630+4×0.1×(1−0.9630)=0.9630+0.0148=0.9778s_W = 0.9630 + 4 \times 0.1 \times (1 - 0.9630) = 0.9630 + 0.0148 = 0.9778

So sW=0.9778s_W = 0.9778, and RapidFuzz's JaroWinkler.similarity("whitaker", "whittaker") returns the same value. A threshold around 0.92 for surnames treats this as agreement, while "whitaker" and "whitehead" (0.85) stay apart.

Which measure for which field

FieldCompare withWhy
EmailExact on the normalised key, then exact on the Gmail keyA one letter difference in an email is a different inbox
PhoneExact on E.164A one digit difference is a different line
SurnameJaro Winkler, thresholds such as 0.92 and 0.88Typos, doubled letters, transliteration leftovers
First nameJaro Winkler plus a nickname table if you have oneShort strings, nicknames, initials
EircodeExact on the key, optionally the same routing key as a weaker levelAn Eircode identifies one address
Address lineToken based or Jaro Winkler on a standardised formWord order and abbreviations vary

PostgreSQL ships Levenshtein and other measures in the fuzzystrmatch extension18, which is enough for a first rule based pass inside the database.

The Fellegi Sunter model in plain words

In 1969 Ivan Fellegi and Alan Sunter published the theory that most record linkage still runs on19. Its idea is simple enough to explain to a shop owner. For each field, ask two questions:

  • If these two records really are the same person, how often would this field agree? That is the m probability.
  • If they are two different people, how often would this field agree just by chance? That is the u probability.

A field where agreement is likely for true matches and rare by chance is strong evidence. The ratio m/um/u (a Bayes factor) says how much more likely the observation is under "same person" than under "different people". Taking the logarithm to base 2 turns it into a match weight that you can add up across fields. Splink's documentation writes the model exactly this way20.

wagree=log⁡2mu,wdisagree=log⁡21−m1−uw_{\text{agree}} = \log_2\frac{m}{u}, \qquad w_{\text{disagree}} = \log_2\frac{1-m}{1-u}

where wagreew_{\text{agree}} is the weight a field adds when it agrees, wdisagreew_{\text{disagree}} the weight it adds (usually a negative number) when it disagrees, mm the probability of agreement among true matches and uu the probability of agreement among non matches. A missing value adds 0: no evidence either way. Foundations: logarithms explains why logarithms turn multiplying into adding.

The total adds a starting point, the prior: how likely is it that two records picked at random are the same person?

W=log⁡2λ1−λ+∑iwi,Pr⁡(match)=2W1+2WW = \log_2\frac{\lambda}{1-\lambda} + \sum_{i} w_i, \qquad \Pr(\text{match}) = \frac{2^{W}}{1 + 2^{W}}

where WW is the total match weight of a pair, λ\lambda the prior probability that two random records match, wiw_i the weight from field ii (agree, disagree or 0 when missing), and Pr⁡(match)\Pr(\text{match}) the resulting probability that the pair is the same person. Foundations: probability covers the step from odds to probability.

Three refinements matter in practice:

  • The model assumes the fields are independent given the match status. They are not quite: people who share an Eircode often share a surname (families). Summing weights then double counts some evidence. This is the main reason to check results by hand rather than trust the probabilities blindly.
  • Term frequency adjustments. Agreeing on "Murphy" is weaker evidence than agreeing on "Kennefick", because the u probability depends on how common the value is. Splink can adjust for each value's frequency.
  • Nobody hands you m. The u probabilities can be estimated by comparing random pairs, which are almost all non matches. The m probabilities are usually estimated with the expectation maximisation (EM) algorithm, which alternates between guessing which pairs match and re estimating the probabilities from those guesses. The Ministry of Justice built Splink around exactly this approach, the Fellegi Sunter model estimated with expectation maximisation, and notes that the same model has long been used by the US Census Bureau and the UK's Office for National Statistics21.

Example: the weights for Shannonside Home's fields

First the prior. Callum's final result (worked through below) has 1,830 people with two records and 145 with three. A person with two records forms one matching pair, a person with three forms three pairs, so there are 1,830+3×145=2,2651{,}830 + 3 \times 145 = 2{,}265 matching pairs among the 2,339,245,800:

λ=2,2652,339,245,800=9.68×10−7,log⁡2λ1−λ=−19.98\lambda = \frac{2{,}265}{2{,}339{,}245{,}800} = 9.68 \times 10^{-7}, \qquad \log_2\frac{\lambda}{1-\lambda} = -19.98

So every pair starts at −19.98-19.98, about 20 points below even odds. That is the arithmetic form of a simple truth: two random customers are almost never the same person, so it takes strong evidence to say they are.

The m and u values below are the kind the model estimates (they are invented for the example, and rounded):

Field (agreement level)muWeight if agreeWeight if disagree
Email key equal0.800.000112.97−2.32-2.32
Surname, Jaro Winkler at least 0.920.950.0047.89−4.32-4.32
First name, Jaro Winkler at least 0.920.920.016.52−3.63-3.63
Eircode key equal0.850.000510.73−2.74-2.74
Phone E.164 equal0.600.0000513.55−1.32-1.32

Read the email row: among true duplicates the email key agrees only 80% of the time (people use several addresses), so disagreeing costs just 2.32 points. Among different people it almost never agrees, so agreeing is worth 12.97. Read the phone row: m is only 0.60 because the phone is often missing or changed, so a disagreement says little (−1.32-1.32), while an agreement is very strong.

Working through one weight: for the Eircode, wagree=log⁡2(0.85/0.0005)=log⁡2(1,700)=10.73w_{\text{agree}} = \log_2(0.85 / 0.0005) = \log_2(1{,}700) = 10.73.

Example: three pairs scored

Pair A, Siobhán's second and third records: email disagrees, surname, first name, Eircode and phone agree.

WA=−19.98−2.32+7.89+6.52+10.73+13.55=16.39W_A = -19.98 - 2.32 + 7.89 + 6.52 + 10.73 + 13.55 = 16.39

Turned into a probability with WA=16.39W_A = 16.39:

Pr⁡(match)=216.391+216.39=0.99999\Pr(\text{match}) = \frac{2^{16.39}}{1 + 2^{16.39}} = 0.99999

The model is as sure as it can be: Pr⁡(match)\Pr(\text{match}) is above 0.9999, although the emails differ.

Pair B, Siobhán's account and an order by Ciarán Byrne at the same Eircode: email disagrees, surname agrees, first name disagrees, Eircode agrees, phone missing on one side (0).

WB=−19.98−2.32+7.89−3.63+10.73+0=−7.31,Pr⁡(match)=0.0063W_B = -19.98 - 2.32 + 7.89 - 3.63 + 10.73 + 0 = -7.31, \qquad \Pr(\text{match}) = 0.0063

Same household, different person: Pr⁡(match)\Pr(\text{match}) is below 1%. The model keeps them apart, which is exactly right.

Pair C, the account of Aoife Walsh (another invented customer) and a 2024 guest order by "Aoife Walsh" at the same Eircode from awalsh@outlook.example, no phone on either: email disagrees, surname, first name and Eircode agree, phone missing.

WC=−19.98−2.32+7.89+6.52+10.73+0=2.84,Pr⁡(match)=22.841+22.84=0.877W_C = -19.98 - 2.32 + 7.89 + 6.52 + 10.73 + 0 = 2.84, \qquad \Pr(\text{match}) = \frac{2^{2.84}}{1 + 2^{2.84}} = 0.877

With Pr⁡(match)=0.877\Pr(\text{match}) = 0.877 it is probably the same person, but a 12% chance that it is someone else, for example a mother and daughter with the same name at the same address. This pair is for a human to look at.

Thresholds: a false merge costs far more than a missed one

The model gives a probability. The business needs a decision. Two mistakes are possible, and they do not cost the same:

  • A missed merge (two records of one person kept apart) inflates the customer count, deflates the repeat rate and lifetime value, and sends the newsletter twice. Annoying, measurable, fixable later.
  • A false merge (two different people joined into one) is worse. One person's order history, address or phone number becomes attached to another. If that joined record ever reaches the shop, an account page or a "your recent orders" email, you have disclosed one customer's personal data to another. You have also broken the accuracy principle of data protection law (more on that below), and you have corrupted both people's histories.

Because the costs differ, the threshold should not sit at 50%. Merge when the expected cost of merging is lower than the expected cost of not merging:

(1−p) Cfalse<p Cmiss⟺p>CfalseCfalse+Cmiss(1 - p)\,C_{\text{false}} < p\,C_{\text{miss}} \quad\Longleftrightarrow\quad p > \frac{C_{\text{false}}}{C_{\text{false}} + C_{\text{miss}}}

where pp is the match probability of the pair, CfalseC_{\text{false}} the cost of merging two different people and CmissC_{\text{miss}} the cost of leaving one person as two records. The left side compares the expected cost of merging (wrong with probability 1−p1-p) with the expected cost of not merging (wrong with probability pp). Foundations: expected value explains expected cost.

Between "merge automatically" and "keep apart" sits a third zone: clerical review, where a person looks at the pair. Fellegi and Sunter built this into the original theory, with two thresholds and a review band in the middle19.

Example: setting the threshold at Shannonside Home

Niamh and Callum put rough numbers on the two mistakes. A false merge that reaches a customer means an apology, a check of what was disclosed and possibly a breach assessment: they estimate €400 of time and risk. A missed merge costs a duplicate newsletter and a slightly wrong report, about €4 a year. So:

p>400400+4=0.990p > \frac{400}{400 + 4} = 0.990

A probability of 0.990 is odds of about 100 to 1, which is a match weight of log⁡2(100)=6.64\log_2(100) = 6.64. Callum sets the rules:

  • Weight above 6.64: link automatically.
  • Weight from 0 to 6.64 (probability 50% to 99%): clerical review.
  • Weight below 0: keep apart.

Here is how the 186,400 candidate pairs from blocking spread across the weights. The vertical axis is logarithmic, each gridline ten times the one below, so that the small bands stay visible:

Invented example. Of 186,400 candidate pairs, 171,200 score under minus 10, 11,850 between minus 10 and minus 5, 2,376 between minus 5 and 0, 214 between 0 and 6.6 and go to clerical review, 212 between 6.6 and 10, and 548 over 10. The 760 pairs above 6.6 are linked automatically. Tap or click to open full screen and move around

The shape is typical: a mountain of obvious non matches, a small hill of obvious matches, and a thin valley between them. The 760 automatic pairs remove 709 surplus records (some pairs fall inside the same three record person). The 214 review pairs take Callum and Niamh one afternoon: for each pair they see both records side by side, the order history and the delivery notes, and they answer same, different or unsure. They confirm 131, reject 71 and mark 12 as unsure, which stay apart. Pair C turns out to be one Aoife: the 2024 order carries the same delivery note as her account orders, "leave with number 14".

The matching pipeline, start to finish

Put together, the steps form one pipeline that runs every night on the new and changed records:

Tap or click to open full screen and move around

And here is where Shannonside Home's 2,120 surplus records were found:

Invented example. Equal normalised email links 1,184 surplus records, the Gmail key adds 96, automatic probabilistic links add 709 and clerical review confirms 131, for 2,120 in total, 3.1% of 68,400 customer records. Tap or click to open full screen and move around

More than half come from the plain email rule. That is worth remembering: before anyone installs a record linkage library, lower(btrim(email)) already finds most of the problem.

  • SQL in the warehouse handles exact duplicates, normalisation and deterministic rules. PostgreSQL's fuzzystrmatch adds Levenshtein for simple fuzzy rules18.
  • RapidFuzz is a fast Python library of string measures (Levenshtein, Jaro Winkler and more)17. It is the right size for scoring pairs inside blocks when you have thousands of records and simple rules.
  • Splink is a free, open source Python library for probabilistic record linkage, built by the UK Ministry of Justice and used to link people across courts, prisons and probation data21. It implements the Fellegi Sunter model with expectation maximisation and term frequency adjustments, runs on DuckDB on a laptop or on Spark and other engines for larger data, and produces explainable weights for every pair22.

Example: RapidFuzz inside Eircode blocks

For a first look, Callum compares names within each Eircode with RapidFuzz. The records come from the staging model as a Parquet file:

from itertools import combinations

import pandas as pd
from rapidfuzz.distance import JaroWinkler

records = pd.read_parquet("stg_customer_records.parquet")

pairs = []
for eircode, block in records.dropna(subset=["eircode_key"]).groupby("eircode_key"):
    rows = block.to_dict("records")
    for a, b in combinations(rows, 2):
        score = JaroWinkler.similarity(a["name_key"] or "", b["name_key"] or "")
        if score >= 0.92:
            pairs.append({
                "record_key_a": a["record_key"],
                "record_key_b": b["record_key"],
                "eircode_key": eircode,
                "name_similarity": round(score, 4),
            })

candidates = pd.DataFrame(pairs)
print(len(candidates))

This finds name lookalikes at the same Eircode, which is useful and quick. It cannot weigh evidence across fields or tell a rare surname from a common one. For that, Callum moves to Splink.

The staging model provides one row per customer record with a unique_id column (Splink's default identifier), the name split into first_name and surname keys, and the other match keys. The code follows the structure of Splink's own getting started guide[^splinkstart]:

import pandas as pd
import splink.comparison_library as cl
from splink import DuckDBAPI, Linker, SettingsCreator, block_on

df = pd.read_parquet("stg_customer_records.parquet")

db_api = DuckDBAPI()
records = db_api.register(df, dataset_display_name="customer_records")

settings = SettingsCreator(
    link_type="dedupe_only",
    comparisons=[
        cl.NameComparison("first_name"),
        cl.JaroWinklerAtThresholds("surname", [0.92, 0.88]),
        cl.EmailComparison("email_norm"),
        cl.ExactMatch("eircode_key").configure(term_frequency_adjustments=True),
        cl.ExactMatch("phone_e164").configure(term_frequency_adjustments=True),
    ],
    blocking_rules_to_generate_predictions=[
        block_on("eircode_key"),
        block_on("phone_e164"),
        block_on("email_match_key"),
        block_on("surname", "first_initial"),
    ],
)

linker = Linker(records, settings)

# The prior: how likely two random records are the same person
linker.training.estimate_probability_two_random_records_match(
    [block_on("email_match_key")], recall=0.6
)
# u probabilities from random pairs, which are almost all non matches
linker.training.estimate_u_using_random_sampling(max_pairs=1e7)
# m probabilities with expectation maximisation, two passes on different blocks
linker.training.estimate_parameters_using_expectation_maximisation(block_on("eircode_key"))
linker.training.estimate_parameters_using_expectation_maximisation(block_on("surname", "first_name"))

predictions = linker.inference.predict(threshold_match_weight=0)
clusters = linker.clustering.cluster_pairwise_predictions_at_threshold(predictions, 0.99)
clusters.as_duckdbpyrelation().write_parquet("customer_clusters.parquet")

A few lines need explaining:

  • estimate_probability_two_random_records_match estimates the prior from pairs that a strict rule says are matches, scaled up by how many true matches you think that rule catches (recall). Callum guesses 0.6, because the email rule finds about 1,280 of the final 2,120.
  • The two EM passes use different blocking rules on purpose. A field used to block in a pass agrees in every pair of that pass, so its m probability cannot be learned there. The second pass learns what the first could not.
  • predict(threshold_match_weight=0) keeps every pair with a weight of 0 or more: the automatic links and the review band.
  • The clustering threshold of 0.99 is the business threshold from the cost calculation. Pairs between 0.5 and 0.99 go to the review queue instead.

The model scores pairs. Customers are groups. Turning links into groups means treating the records as points and the accepted links as lines, and taking every set of connected points as one person (a connected component). The danger is chaining: A links to B, B links to C, so A and C end up together even if they share nothing.

Two defences work. Check the size of every cluster, because real people rarely have more than three or four records, and review any bigger cluster by hand. And make sure that shared values are recognised as weak evidence, which is what term frequency adjustments do.

Example: the cluster of seven

The first Splink run at Shannonside Home produces one cluster of seven records. All seven ordered with the phone number of the same dental practice, the practice mobile each of them typed into the checkout, among them Siobhán's two guest orders. The shared phone links them pairwise into a chain. With term frequency adjustments switched on for phone_e164, a number shared by seven records counts for much less than a private mobile, the chain breaks, and the seven come out as six people: Siobhán, whose two orders stay linked because her name and Eircode agree as well, and five colleagues with one record each. Callum also adds a rule to the nightly checks: any cluster larger than four records goes to review before it is accepted.

Survivorship: building the golden record

Once you know which records belong together, you need one record that represents the person: the golden record. For every attribute, a survivorship rule decides which value survives. The rules are business decisions, so Niamh signs them off, and they are written down with a version number like every other cleaning rule.

AttributeRuleReason
Customer IDA new stable ID per cluster, never one of the source IDsSource IDs can disappear in a later merge
EmailThe account email if there is an account, otherwise the most recent order's emailThe account email is the one the customer logs in with
NameFrom the account, otherwise the most recent orderAccounts are edited by the customer
PhoneThe most recent valid E.164 numberPhones change, old ones get reassigned
Eircode and addressFrom the most recent completed orderPeople move
First and last order dateEarliest and latest across all recordsThe whole history belongs to the person
Order count and revenueSum across all recordsSame
Marketing permissionAny opt out on any record applies to the personThe safe direction, explained below

Example: Siobhán's golden record

AttributeValueTaken from
customer_idcus_7f3a91new
emailsiobhan.byrne@gmail.comaccount user:20417
nameSiobhán Byrneaccount
phone_e164+353875550123guest order from 2025
eircodeV94 X7K2guest order from 2025
first_order_at14 March 2021account
last_order_at9 June 2025guest order from 2025
orders42 + 1 + 1 across her three records
marketing_opt_outtrueshe unsubscribed at the work address in 2025

In SQL, PostgreSQL's ordered array_agg with a FILTER expresses survivorship compactly:

-- PostgreSQL: one golden record per customer cluster
select
  m.customer_id,
  (array_agg(r.email_norm order by (r.record_key like 'user:%') desc, r.last_order_at desc))[1]
    as email,
  (array_agg(r.name_raw order by (r.record_key like 'user:%') desc, r.last_order_at desc))[1]
    as name,
  (array_agg(r.phone_e164 order by r.last_order_at desc)
     filter (where r.phone_e164 is not null))[1] as phone_e164,
  (array_agg(r.eircode_key order by r.last_order_at desc)
     filter (where r.eircode_key is not null))[1] as eircode_key,
  min(r.first_order_at) as first_order_at,
  max(r.last_order_at)  as last_order_at,
  sum(r.orders)         as orders,
  bool_or(r.marketing_opt_out) as marketing_opt_out,
  count(*)              as source_records
from customer_identity_map as m
join stg_customer_records as r using (record_key)
group by m.customer_id;

(record_key like 'user:%') desc sorts account records before guest records, and the [1] takes the first value after sorting. bool_or is true if any record has opted out, which implements "an opt out anywhere applies to the person".

Keep every merge reversible

Never merge customer records by overwriting or deleting rows in the shop database or the raw layer. Merge with a mapping table: one row per source record, saying which customer it belongs to, how that was decided, by whom and under which rule version. The golden record is then a model built on top of the mapping. Undoing a wrong merge means changing a row in the mapping and rebuilding, not reconstructing lost data. The chapter on cleaning pipelines later in this series explains why the raw layer is never overwritten, and the chapter on versioning covers keeping the history of every change.

-- PostgreSQL: the identity map and the manual decisions that override the model
create table customer_identity_map (
  record_key    text primary key,
  customer_id   text not null,
  match_method  text not null check (match_method in
                  ('exact_email', 'gmail_key', 'probabilistic', 'clerical', 'singleton')),
  match_weight  numeric(6,2),
  decided_by    text not null,         -- model version or the reviewer's initials
  rule_version  text not null,
  decided_at    timestamptz not null default now()
);

create table customer_match_overrides (
  record_key_a  text not null,
  record_key_b  text not null,
  decision      text not null check (decision in ('never_link', 'always_link')),
  reason        text not null,
  decided_by    text not null,
  decided_at    timestamptz not null default now(),
  primary key (record_key_a, record_key_b)
);

The overrides table is what makes clerical review stick. Every nightly run applies the overrides after the model, so a pair a person rejected is never linked again, whatever the model thinks next time.

Example: undoing a wrong merge

In February a customer emails Niamh: her account page shows an order she never placed. Callum looks it up. Two records, "Emma Ryan" at a shared student house in Limerick, both with the same landline, were linked automatically with a weight of 7.1, just above the threshold. They are two different people. He inserts one row into customer_match_overrides with never_link and the reason, reruns the clustering, and the golden records split back into two. Nothing had been deleted, so nothing has to be reconstructed. Because a false merge reached a customer, Niamh also records it in her data protection log and checks whether it needs reporting, and Callum lowers the term frequency weight of shared landlines.

What deduplication does to your numbers

Removing duplicates changes the numbers that decisions rest on, and not all of them move in a flattering direction. That is the point: they move towards the truth. Before publishing the change, write down every metric it affects and by how much, and tell the people who use them. The chapter on reporting on cleaned data later in this series covers restatements in depth.

Example: Shannonside Home before and after

Over five years Shannonside Home took 97,200 orders. At the average order value of €84, that is €8,164,800 of revenue including VAT. Of the 68,400 customer records, 16,416 had two or more orders, a repeat rate of 24.0%.

After matching, the 2,120 surplus records merge into their 1,975 people (1,830 with two records, 145 with three). Every one of those people has at least two orders, so all 1,975 are repeat customers. Before the merge, 610 of their records were already repeat buyers on their own. So:

repeat customers after=16,416−610+1,975=17,781\text{repeat customers after} = 16{,}416 - 610 + 1{,}975 = 17{,}781

and the customer count falls to 68,400−2,120=66,28068{,}400 - 2{,}120 = 66{,}280. The repeat rate becomes

17,78166,280=0.268\frac{17{,}781}{66{,}280} = 0.268

so 26.8%26.8\%, up from 24.0%24.0\%. The other metrics:

MetricBeforeAfterChange
Customers (five years)68,40066,280−3.1%-3.1\%
Repeat rate24.0%26.8%+2.8 points
Orders per customer1.421.47+3.2%
Revenue per customer€119.37€123.19+3.2%
New customers in October1,3001,252−3.7%-3.7\%
Acquisition cost per new customer€12.69€13.18+3.8%

Revenue per customer: 8,164,800/68,400=119.378{,}164{,}800 / 68{,}400 = 119.37 before and 8,164,800/66,280=123.198{,}164{,}800 / 66{,}280 = 123.19 after. The last two rows are the uncomfortable ones. Matching shows that 48 of October's 1,300 "new" customers had bought before under another email. With €16,500 of ad spend, acquisition cost per new customer rises from 16,500/1,300=12.6916{,}500 / 1{,}300 = 12.69 to 16,500/1,252=13.1816{,}500 / 1{,}252 = 13.18. The ads did not get worse: the old number was flattered by returning customers counted as new.

Invented example. Percentage change of each metric after merging 2,120 duplicate records: customers minus 3.1%, new customers in October minus 3.7%, orders per customer plus 3.2%, revenue per customer plus 3.2%, acquisition cost per new customer plus 3.8%, and the repeat rate plus 11.7% in relative terms, from 24.0% to 26.8%. Tap or click to open full screen and move around

The repeat rate moves most, in relative terms by 26.8/24.0−1=11.7%26.8 / 24.0 - 1 = 11.7\%, because duplicates hit it twice: they inflate the denominator and they turn repeat buyers into one time buyers. Lifetime value models feel the same effect. A model of repeat purchase such as the one in how to know who is still a customer when nobody cancels learns from each customer's order history, and a history split across three records looks like three people who each bought once and vanished. If you bid on lifetime value rather than cost per click, deduplication changes the values your campaigns optimise for.

Measuring the matcher: precision and recall

A matcher is a classifier, and it needs the same honesty as any model. Two numbers describe it:

precision=TPTP+FP,recall=TPTP+FN\text{precision} = \frac{TP}{TP + FP}, \qquad \text{recall} = \frac{TP}{TP + FN}

where TPTP (true positives) is the number of linked pairs that really are the same person, FPFP (false positives) the linked pairs that are not, and FNFN (false negatives) the true duplicate pairs the matcher missed. Precision answers "when it links, is it right?", recall answers "of the real duplicates, how many did it find?". Foundations: ratios and rates covers these kinds of ratios.

Precision is measured by checking a random sample of links by hand. Recall is harder, because you need duplicates you know about independently. Customer service tickets are a good source: "I have two accounts, can you merge them?"

Example: Callum's test set

Callum draws 190 random automatic links and checks each by hand: 188 are right, 2 are wrong. From two years of customer service tickets he collects 200 confirmed duplicate pairs, and the matcher found 188 of them.

precision=188188+2=0.989,recall=188188+12=0.940\text{precision} = \frac{188}{188 + 2} = 0.989, \qquad \text{recall} = \frac{188}{188 + 12} = 0.940

A precision of 0.9890.989 is what the cost threshold asked for. A recall of 94% means some duplicates remain, so the honest statement in the report is "at least 3.1% of records were duplicates". Callum keeps both test sets and reruns them after every change to the rules, as part of the test gate for the pipeline.

The law: accuracy, purpose and the merged profile

This section is general information, not legal advice. Shannonside Home is an Irish business, so the GDPR applies directly, alongside the Data Protection Act 2018. Entity resolution touches the law in several places:

  • Accuracy. Article 5(1)(d) requires personal data to be "accurate and, where necessary, kept up to date", with every reasonable step taken to erase or rectify inaccurate data without delay23. The Data Protection Commission (DPC) puts it plainly: controllers must make sure personal data are accurate and, where necessary, kept up to date, and fix or delete inaccurate data promptly24. Duplicates make data misleading (two customers where there is one), and false merges make it plainly wrong. Both are accuracy problems, which is a good argument for doing this work carefully rather than not at all.
  • Purpose limitation. Article 5(1)(b) says data collected for one purpose must not be used in a way incompatible with it23. Linking records is not neutral: joining order data, newsletter behaviour and customer service tickets into one profile creates something none of the original collections described. Ask whether customers would reasonably expect that combination, say in the privacy notice that you link records, and link only the sources the purpose needs.
  • Marketing objections. Under Article 21(3), once someone objects to direct marketing, their data may no longer be used for it23. That is why an opt out on any of a person's records should apply to the person in the golden record. Copying a consent from one email address to another is the dangerous direction: permission was given for the address it was given for.
  • Access and erasure. A good identity map makes it easier to answer a subject access request completely and to erase a person everywhere, because you can find every record that belongs to them. A false merge does the opposite: an access request could disclose someone else's orders.

Example: should the tickets join the profile?

Niamh wants customer service tickets linked to the golden record, so that the service desk sees a customer's full order history. Callum links them by email key, for that purpose only: the support view reads the link, the marketing segments do not. The privacy notice gains one sentence saying that orders and support requests are linked to help with enquiries. The newsletter segments stay built from orders and email engagement only.

Stop the duplicates at the source

Cleaning in the pipeline is necessary, because some duplicates are created by customers and cannot be prevented. Many are created by the shop itself, though, and those cost less to stop where they start. The chapter on when to clean data and when to leave it alone makes the general case.

  • Normalise the guest checkout email when it is saved, not only the account email. Devise covers accounts, but the email on a guest order is a separate column.
  • At checkout, when a guest enters an email that has an account, offer to sign in. That alone prevents the most common duplicate.
  • On account creation, look up earlier guest orders with the same normalised email and offer to attach them, with the customer's confirmation.
  • Keep any legacy import from the old platform behind the same normalisation as new data. Siobhán's trailing space came from an import that bypassed the model.

Example: one line in the shop, one test

Rails has a built in way to normalise an attribute on assignment, normalizes25. Callum adds it to Solidus's order model in an initializer, test first:

# spec/models/spree/order_email_spec.rb
require "rails_helper"

RSpec.describe Spree::Order do
  it "stores a guest email trimmed and in lower case" do
    order = Spree::Order.new(email: "  Siobhan.Byrne@Gmail.com ")
    expect(order.email).to eq("siobhan.byrne@gmail.com")
  end
end
# config/initializers/order_email_normalization.rb
Rails.application.config.to_prepare do
  Spree::Order.normalizes :email, with: ->(email) { email.strip.downcase }
end

The test fails, he adds the initializer, the test passes, and the change goes through the release gate like any other. In the warehouse nothing changes: the pipeline still normalises every email, because five years of old rows were written before this line existed.

A checklist for one customer, one record

StepDone when
Exact duplicatesEvery raw table has a natural key, a deterministic tie breaker and a unique test
Match keysEmail, Gmail key (Gmail only), E.164 phone, name key and Eircode key exist as separate columns
BlockingSeveral rules on different fields, candidate pairs counted, true pairs known to be inside
Scoringm and u estimated, weights inspected per field, term frequencies on for shared values
ThresholdDerived from the cost of a false merge versus a missed merge, with a review band
ReviewA queue, a person, and an overrides table that every run respects
ClustersSize checked, large clusters reviewed
Golden recordSurvivorship rules written down, signed off and versioned, opt out wins
ReversibilityIdentity map, no deletes, any merge undone by one row
MeasurementPrecision and recall on kept test sets, rerun on every change
ReportingEvery affected metric restated with before and after
SourceShop normalises emails and offers sign in to returning guests

Conclusion

One customer, one record sounds like tidying. It is really a sequence of decisions, each of which can be made carefully or carelessly. Remove exact duplicates with a natural key and a tie breaker, never with DISTINCT. Normalise into match keys and leave the original values alone, and treat the Gmail rules as Gmail rules. Block so that comparing becomes affordable, measure similarity with Jaro Winkler and exact keys, and score the evidence with the Fellegi Sunter weights, which a shop owner can follow line by line. Set the threshold from what each mistake costs, because merging two people is far worse than missing one, and give the doubtful middle to a person. Keep every merge in a mapping table so that it can be undone, let an opt out anywhere apply everywhere, and restate the numbers honestly, including the ones that look worse. At Shannonside Home that work turned 68,400 customers into 66,280 people, and the repeat rate from 24.0% into the 26.8% it always was.

If you suspect your customer count includes the same people twice, book the free workshop: we look at your customer data together and size the problem, and the first two weeks of work are on me.

Sources

  1. 1.

    Stripe, Receive Stripe events in your webhook endpoint, section Handle duplicate events, Stripe Documentation, https://docs.stripe.com/webhooks

  2. 2.

    PostgreSQL Global Development Group, SELECT, section DISTINCT Clause, PostgreSQL documentation (current version), https://www.postgresql.org/docs/current/sql-select.html

  3. 3.

    Google Cloud, Query syntax, section QUALIFY clause, BigQuery documentation, https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax

  4. 4.

    dbt Labs, About data tests property (data_tests), dbt Developer Hub, https://docs.getdbt.com/reference/resource-properties/data-tests

  5. 5.

    J. Klensin, RFC 5321: Simple Mail Transfer Protocol, Internet Engineering Task Force, October 2008, section 2.4, https://www.rfc-editor.org/rfc/rfc5321

  6. 6.

    Devise, initializer template (config.case_insensitive_keys and config.strip_whitespace_keys, default :email), GitHub, https://github.com/heartcombo/devise/blob/main/lib/generators/templates/devise.rb

  7. 7.

    Google, Dots don't matter in Gmail addresses, Gmail Help, https://support.google.com/mail/answer/7436150

  8. 8.

    Google, Send emails from a different address or alias, Gmail Help, https://support.google.com/mail/answer/12096

  9. 9.

    International Telecommunication Union, Recommendation ITU T E.164: The international public telecommunication numbering plan, November 2010, https://www.itu.int/rec/T-REC-E.164-201011-I/en

  10. 10.

    David Drysdale, python-phonenumbers, a Python port of Google's libphonenumber, GitHub, https://github.com/daviddrysdale/python-phonenumbers

  11. 11.

    PostgreSQL Global Development Group, unaccent, a text search dictionary that removes diacritics, PostgreSQL documentation (current version), https://www.postgresql.org/docs/current/unaccent.html

  12. 12.

    PostgreSQL source code, contrib/unaccent/unaccent.rules, GitHub, https://github.com/postgres/postgres/blob/master/contrib/unaccent/unaccent.rules

  13. 13.

    Eircode, What is Eircode?, eircode.ie, https://www.eircode.ie/what-is-eircode

  14. 14.

    Peter Christen, Data Matching: Concepts and Techniques for Record Linkage, Entity Resolution, and Duplicate Detection, Springer, 2012, https://link.springer.com/book/10.1007/978-3-642-31164-2

  15. 15.

    RapidFuzz, Levenshtein, RapidFuzz documentation, https://rapidfuzz.github.io/RapidFuzz/Usage/distance/Levenshtein.html

  16. 16.

    William E. Winkler, String Comparator Metrics and Enhanced Decision Rules in the Fellegi Sunter Model of Record Linkage, U.S. Bureau of the Census, 1990, ERIC ED325505, https://files.eric.ed.gov/fulltext/ED325505.pdf

  17. 17.

    RapidFuzz, JaroWinkler, RapidFuzz documentation, https://rapidfuzz.github.io/RapidFuzz/Usage/distance/JaroWinkler.html

  18. 18.

    PostgreSQL Global Development Group, fuzzystrmatch, determine string similarities and distance, PostgreSQL documentation (current version), https://www.postgresql.org/docs/current/fuzzystrmatch.html

  19. 19.

    Ivan P. Fellegi and Alan B. Sunter, A Theory for Record Linkage, Journal of the American Statistical Association, volume 64, number 328, pages 1183 to 1210, 1969, https://www.jstor.org/stable/2286061

  20. 20.

    Ministry of Justice Analytical Services, The Fellegi Sunter model, Splink documentation, https://moj-analytical-services.github.io/splink/topic_guides/theory/fellegi_sunter.html

  21. 21.

    Ministry of Justice, Splink: MoJ's open source library for probabilistic record linkage at scale, in Joined up data in government: the future of data linking methods, GOV.UK, 2020, https://www.gov.uk/government/publications/joined-up-data-in-government-the-future-of-data-linking-methods/splink-mojs-open-source-library-for-probabilistic-record-linkage-at-scale

  22. 22.

    Ministry of Justice Analytical Services, Getting started, Splink documentation, https://moj-analytical-services.github.io/splink/getting_started.html

  23. 23.

    Regulation (EU) 2016/679 (General Data Protection Regulation), Articles 5 and 21, Official Journal of the European Union, EUR Lex, https://eur-lex.europa.eu/eli/reg/2016/679/oj

  24. 24.

    Data Protection Commission, Principles of Data Protection, dataprotection.ie, https://www.dataprotection.ie/en/individuals/data-protection-basics/principles-data-protection

  25. 25.

    Ruby on Rails, ActiveRecord::Normalization::ClassMethods, normalizes, Rails 8.0 API documentation, https://api.rubyonrails.org/v8.0/classes/ActiveRecord/Normalization/ClassMethods.html

Shelter

I’m running the London Marathon for Shelter. Sunday 25 April 2027

My personal fundraiser. Shelter, the National Campaign for Homeless People Limited, registered charity 263710 (England and Wales) and SC002327 (Scotland), registered with the Fundraising Regulator.