Finding Duplicate Transactions in a Payment Dataset
Machine LearningModel answerLast updated
Design a system to detect, classify, and quantify duplicate records in a payment transaction dataset, handling both exact matches and fuzzy near-duplicates.
You are working with a large payment transaction dataset and notice that some records may represent the same underlying event more than once.
Address the following:
Part 1 — Root causes What real-world scenarios produce records that look like duplicates? Group them by cause: pipeline behavior, transaction lifecycle, and legitimate repetition. For each group, explain why the distinction matters downstream.
Part 2 — Defining "duplicate" What makes two records the same transaction versus two genuinely separate transactions? Define a precise, operational criterion. Account for cases where two records differ in small ways — different formatting, mismatched timestamps, slight merchant name variations — but may still represent a single event.
Part 3 — Detection and quantification Describe a practical pipeline for finding duplicates at scale. Cover:
- How to normalize records before comparison
- How to avoid O(n²) pairwise comparison
- How to score candidate pairs and decide whether they match
- How to measure the duplicate rate in a meaningful way — not just row counts, but in terms of business impact
Your answer should be structured and concrete. Mention the trade-offs in any choices you make, and identify at least one common mistake candidates make when approaching this problem.
Hints
Hint 1
Before jumping to code, ask what 'same transaction' means in the context of the business. An authorization and its settlement share the same purchase but should not be merged — they serve different analytical purposes.
Hint 2
Pairwise comparison across all records won't scale. Think about what fields you can use as a blocking key to restrict comparisons to a small, high-recall candidate set before scoring.
Hint 3
A raw row-level duplicate rate can be misleading. Consider weighting by transaction amount — a 1% row duplication rate concentrated on large transactions can inflate reported spend by 5% or more.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Framing the problem
The most common mistake in this type of question is treating deduplication as a one-liner — df.drop_duplicates() — and moving on. The harder and more important part is defining what "duplicate" means before writing any code. Different definitions yield very different outcomes, and the wrong one silently corrupts downstream analytics or destroys fraud signal.
Part 1 — Where duplicate-looking records come from
Group causes into three buckets so you can reason about each separately.
Pipeline and ingestion artifacts (true duplicates)
These are the records you actually want to remove:
- At-least-once delivery: a queue consumer or API client retries after a timeout, writing the same event twice.
- Overlapping backfills: a reprocessed day gets appended instead of replacing the original records.
- Join fan-out: joining to a lookup table with duplicate keys multiplies rows without anyone noticing.
- Multiple source feeds: the same transaction arrives from both the card network feed and the bank ledger, with different IDs and slightly different formatting.
- Formatting drift: the same event appears as
12.50in one feed and1250(minor units) in another, or with UTC vs local time, or as"STARBUCKS #423"vs"Starbucks 423".
Transaction lifecycle stages (related but not duplicates)
A single purchase often generates multiple records: an authorization, then a capture, then a clearing or settlement. These records share a purchase but belong to different lifecycle stages. Merging them loses information. Fraud models need the authorization; spend reporting needs the settled amount. The right operation here is linking, not deduplication.
Reversals, refunds, and chargebacks also look like duplicates because they share the merchant and amount — but they are distinct economic events.
Legitimate repeated transactions (not duplicates)
Two identical coffees bought five minutes apart are not duplicates. Neither is a monthly subscription charge. A cardholder who retries after a decline produces two records, but only the approved one is a purchase — both are real events that fraud teams care about. Silently dropping one destroys signal.
Part 2 — Defining a true duplicate
A working definition: a true duplicate is a record that represents the same real-world economic event at the same lifecycle stage as another record in the dataset.
Operationalize this as a confidence ladder:
| Tier | Matching rule | Confidence |
|---|---|---|
| T1 — Exact | All columns identical after loading | Certain |
| T2 — Key | Same transaction ID, or same (network reference, auth code, card token) | Very high |
| T3 — Normalized | Identical after standardizing amount, currency, time zone, and merchant string | High |
| T4 — Fuzzy | Same card and amount, similar merchant, timestamps within a small window Δ, but different or missing IDs | Probabilistic |
Before locking in this definition, confirm with stakeholders:
- Which ID fields are reliably populated, and which are sometimes null or regenerated?
- What are the retry intervals in the upstream pipelines? That shapes the time window Δ.
- Is a false merge (losing a real transaction) worse than a missed duplicate (double-counting spend)? This determines where to set thresholds.
Part 3 — Detection pipeline
Step 1 — Normalize. Standardize before any comparison. Convert amounts to integer minor units, align to a single currency, convert timestamps to UTC, lowercase merchant names, strip punctuation and processor prefixes (SQ *, PAYPAL *), and standardize transaction type codes. Keep raw columns alongside normalized ones so every decision is auditable.
Step 2 — Exact and key-based passes. Hash the normalized row and separately hash the business key. Flag any hash collisions. This is O(n) and catches T1–T3 with no false positives.
Step 3 — Blocking for near-duplicates. Comparing all pairs is O(n²) and infeasible at scale. Instead, define a block key — for example (card_token, amount_minor, currency) — so you only compare records within the same block. Within each block, sort by timestamp and compare neighbors within a rolling window Δ. This reduces the search space to roughly O(n log n).
Step 4 — Score candidate pairs. For each candidate pair inside a block, compute features: time delta, merchant string similarity (Jaro-Winkler or token-set ratio work well), MCC match, terminal ID match, auth code match, and whether records come from different source systems. Start with transparent threshold rules. If precision is insufficient, move to a supervised classifier trained on a few hundred hand-labeled pairs, or a probabilistic Fellegi–Sunter model.
import pandas as pd
from rapidfuzz.fuzz import token_set_ratio
def find_near_duplicates(df, window_s=120, merch_thresh=85):
d = df.copy()
d["ts"] = pd.to_datetime(d["ts"], utc=True)
d["amt"] = (d["amount"].round(2) * 100).astype("int64")
d["merch_norm"] = (
d["merchant"].str.lower()
.str.replace(r"[^a-z ]", "", regex=True)
.str.strip()
)
d = d.sort_values(["card_token", "amt", "ts"]).reset_index()
pairs = []
for _, group in d.groupby(["card_token", "amt", "currency"]):
rows = group.to_dict("records")
for i, a in enumerate(rows):
for b in rows[i + 1:]:
delta = (b["ts"] - a["ts"]).total_seconds()
if delta > window_s:
break # rows are sorted, no later pair will qualify
if (a["txn_type"] == b["txn_type"] and
token_set_ratio(a["merch_norm"], b["merch_norm"]) >= merch_thresh):
pairs.append((a["index"], b["index"]))
return pairs # pass into union-find to build clusters
Step 5 — Cluster and pick a survivor. Duplicate relationships can chain (A matches B, B matches C), so build a graph from matched pairs and take connected components using union-find. Apply a time-span cap or require each member to match the cluster's canonical record to prevent over-merging. For the surviving record, prefer the most advanced lifecycle stage, then the most complete fields, then the earliest ingestion timestamp.
Part 4 — Quantifying the duplicate rate meaningfully
Report by tier, not just in aggregate. T1 exact duplicates and T4 fuzzy matches have very different causes and very different confidence levels. Mixing them into one number hides what's actually wrong.
Weight by amount, not just by row count. If retries concentrate on large transactions, a 0.5% row duplication rate can translate to 3–4% spend inflation. Always report a dollar-weighted rate alongside the row-level rate.
Use the time-delta histogram to calibrate Δ. For same-card, same-amount pairs, plot the distribution of time gaps between records. Pipeline duplicates accumulate near 0 s or at known retry intervals (30 s, 60 s). Legitimate repeats spread broadly. Compare against a baseline of same-card, different-amount pairs — the excess mass at short gaps over that baseline estimates true duplicate volume and reveals a natural cutoff for Δ.
Validate precision and recall with hand-labeled samples. Audit a stratified sample of flagged pairs across tiers and score buckets to estimate precision with confidence intervals. Audit a sample of near-misses (unflagged pairs just below threshold) to estimate recall. Report how sensitive your counts are to Δ and the similarity threshold — if the numbers change dramatically with small threshold adjustments, your definition is unstable and needs sharper criteria before production use.