Enrich Card Transactions with Merchant Loyalty Points
Medium · Data Manipulation (SQL/Python) · Software Engineer · Technical Screen
Problem Statement
A loyalty platform receives partner store metadata as a flat file merchants.csv containing three string fields (merchant_name, merchant_code, category) alongside a relational table transactions(user_id INT, merchant_name TEXT, amount DECIMAL(10, 2), transacted_at TIMESTAMP).
Address the workflow below, and implement the core enrichment rule in Python for automated evaluation:
- Staging load: Show how to bulk-import
merchants.csvinto a SQL staging tablemerchants(merchant_name TEXT, merchant_code TEXT, category TEXT). - Transaction enrichment & point calculation: Produce one output record per transaction containing
user_id,merchant_code,category,base_points, andfinal_points(both point fields as integers):- Match
merchant_namecharacter-for-character (preserving letter case and spaces). If the samemerchant_nameappears multiple times inmerchants, use its first entry so a single transaction never fans out into multiple output rows. - Whenever a transaction's
merchant_nameis absent frommerchants, retain the transaction and fill bothmerchant_codeandcategorywith'UNKNOWN'. - Compute
base_pointsas the mathematical floor ofamount(the greatest integer less than or equal toamount, rounding toward negative infinity on negative refunds). - Compute
final_pointsafter flooring: award3 * base_pointswhencategoryequals'Restaurant', and1 * base_pointsfor every other category (including'UNKNOWN').
- Match
- SQL vs. application layer: Discuss when executing this lookup and conditional multiplier directly inside SQL (
LEFT JOIN+CASE) is preferable to fetching raw tables and transforming rows in application memory. - Data hygiene & fuzzy descriptors: Recommend indexes, staging cleanup steps, and practical strategies for reconciling inconsistent
merchant_namedescriptors.
For the automated judge, implement:
def join_transactions_with_merchant_points(
transactions: List[List], merchants: List[List]
) -> List[Dict]:
where each item in transactions is [user_id, merchant_name, amount, transacted_at], each item in merchants is [merchant_name, merchant_code, category], and the returned list contains one dictionary per transaction with keys "user_id", "merchant_code", "category", "base_points", and "final_points".
Examples
Example 1
Input:
transactions = [
[101, "Ramen House", 18.60, "2025-05-10T12:30:00"],
[204, "Fresh Market", 53.95, "2025-05-10T15:10:00"],
[101, "Pop-Up Bakery", 7.40, "2025-05-11T08:45:00"]
]
merchants = [
["Ramen House", "MRC-10", "Restaurant"],
["Fresh Market", "MRC-20", "Grocery"]
]
Output:
[
{"user_id": 101, "merchant_code": "MRC-10", "category": "Restaurant", "base_points": 18, "final_points": 54},
{"user_id": 204, "merchant_code": "MRC-20", "category": "Grocery", "base_points": 53, "final_points": 53},
{"user_id": 101, "merchant_code": "UNKNOWN", "category": "UNKNOWN", "base_points": 7, "final_points": 7}
]
"Ramen House" matches a 'Restaurant' partner, so 18.60 floors to 18 and triples to 54. "Fresh Market" is 'Grocery', earning 1x its floored value 53. "Pop-Up Bakery" has no entry in merchants, so it receives 'UNKNOWN' placeholders and 7 points.
Example 2
Input:
transactions = [
[12, "Bistro Verde", 0.85, "2025-06-01T11:00:00"],
[12, "Bistro Verde", 40, "2025-06-01T19:20:00"]
]
merchants = [
["Bistro Verde", "MRC-35", "Restaurant"]
]
Output:
[
{"user_id": 12, "merchant_code": "MRC-35", "category": "Restaurant", "base_points": 0, "final_points": 0},
{"user_id": 12, "merchant_code": "MRC-35", "category": "Restaurant", "base_points": 40, "final_points": 120}
]
Sub-dollar spend 0.85 floors to 0 (0 * 3 = 0), whereas the exact integer spend 40 floors to 40 and triples to 120.
Example 3
Input:
transactions = [
[8, "Book Nook", -4.20, "2025-07-15T09:15:00"],
[9, "Unlisted Kiosk", -0.25, "2025-07-15T10:00:00"]
]
merchants = [
["Book Nook", "MRC-50", "Bookstore"]
]
Output:
[
{"user_id": 8, "merchant_code": "MRC-50", "category": "Bookstore", "base_points": -5, "final_points": -5},
{"user_id": 9, "merchant_code": "UNKNOWN", "category": "UNKNOWN", "base_points": -1, "final_points": -1}
]
Flooring rounds negative refund amounts down toward negative infinity (-4.20 becomes -5, and -0.25 becomes -1), rather than truncating toward zero.
Constraints
0 <= len(transactions) <= 10^50 <= len(merchants) <= 10^5user_idis an integer;merchant_name,merchant_code,category, andtransacted_atare strings.amountis anintorfloat(positive, zero, or negative for refunds/adjustments).base_pointsandfinal_pointsin every output dictionary must have Python typeint.- Output row order may follow input transaction order (SQL evaluation ignores row ordering).
Step-by-step walkthrough
Understand the datasets and the four workflow parts
We have two inputs:
merchants(merchant_name, merchant_code, category)arriving as an external CSV filemerchants.csv.transactions(user_id, merchant_name, amount, transacted_at)stored in a relational table.
transactions merchants +---------+---------------+--------+ +--------------+---------------+------------+ | user_id | merchant_name | amount | | merchant_name| merchant_code | category | +---------+---------------+--------+ +--------------+---------------+------------+ | 101 | Ramen House | 18.60 | ---------> | Ramen House | MRC-10 | Restaurant | | 204 | Fresh Market | 53.95 | ---------> | Fresh Market | MRC-20 | Grocery | | 101 | Pop-Up Bakery | 7.40 | --(miss)-> fallback to ('UNKNOWN', 'UNKNOWN') | +---------+---------------+--------+ +--------------+---------------+------------+For every transaction row, we must emit
user_id,merchant_code,category,base_points, andfinal_points: -base_points = FLOOR(amount)as an integer. Floor always rounds down toward negative infinity (18.60 -> 18,0.85 -> 0, and-4.20 -> -5on refunds). -final_points = 3 * base_pointswhencategoryis'Restaurant', and1 * base_pointsfor every other category (including unmatched merchants). - Ifmerchant_namehas no exact match inmerchants(case and spaces included), keep the transaction and set bothmerchant_codeandcategoryto'UNKNOWN'.The prompt covers the end-to-end data-engineering workflow (staging ingestion, SQL
LEFT JOIN+CASEquery, SQL vs. application trade-offs, and indexing/cleaning/fuzzy matching), while the automated judge tests the exact join-and-points rule viajoin_transactions_with_merchant_points(transactions, merchants)in Python. Let's tackle each part systematically.Load the CSV into a SQL staging table
A staging table is a temporary landing table with permissive
TEXTcolumns where raw external files are loaded as-is before cleaning or enforcing strict constraints. Landing data in staging first prevents a single malformed row from aborting an entire ingestion run and lets you inspect and clean anomalies using SQL.In PostgreSQL, create the staging table and stream the file with a native bulk CSV loader:
-- Landing table with plain TEXT columns so raw CSV rows load cleanly. CREATE TABLE merchants ( merchant_name TEXT, merchant_code TEXT, category TEXT ); -- Bulk-load merchants.csv from the client, skipping the header line. \copy merchants FROM 'merchants.csv' WITH (FORMAT csv, HEADER true)Other SQL engines provide equivalent bulk loaders (
LOAD DATA INFILEin MySQL,.import --csvin SQLite,COPY INTOin Snowflake). Prefer a native CSV bulk loader over building row-by-rowINSERTstrings in a script: it streams data orders of magnitude faster, handles commas inside quoted names like"Noodles, Broth & Tea", and safely parses apostrophes likeLuigi's Trattoriawithout risking broken SQL quotes.Write the SQL transformation with LEFT JOIN and CASE
Why must we use
LEFT JOINinstead ofINNER JOIN? AnINNER JOINkeeps only rows that match on both sides, which would silently drop transactions at unlisted stores likePop-Up BakeryorSidewalk Florist. ALEFT JOINpreserves every row from the left table (transactions) and fills the right table's (merchants) columns withNULLwhenever no match exists.-- Deduplicate merchants by merchant_name first so a repeated CSV entry -- never fans out one transaction into multiple output rows. WITH unique_merchants AS ( SELECT merchant_name, MIN(merchant_code) AS merchant_code, MIN(category) AS category FROM merchants GROUP BY merchant_name ) SELECT t.user_id, -- On an unmatched LEFT JOIN row, m.merchant_name is NULL -> emit 'UNKNOWN'. CASE WHEN m.merchant_name IS NULL THEN 'UNKNOWN' ELSE m.merchant_code END AS merchant_code, CASE WHEN m.merchant_name IS NULL THEN 'UNKNOWN' ELSE m.category END AS category, -- FLOOR rounds toward -infinity; CAST converts DECIMAL/NUMERIC to INTEGER. CAST(FLOOR(t.amount) AS INTEGER) AS base_points, -- Multiply AFTER flooring; NULL category falls into ELSE 1 automatically. CAST(FLOOR(t.amount) AS INTEGER) * CASE WHEN m.category = 'Restaurant' THEN 3 ELSE 1 END AS final_points FROM transactions AS t LEFT JOIN unique_merchants AS m ON m.merchant_name = t.merchant_name;Notice three subtle details in that query: - Testing
m.merchant_name IS NULL: When aLEFT JOINfinds no match, the join keym.merchant_nameis guaranteed to beNULL. Checkingm.merchant_name IS NULL(orCOALESCE(m.merchant_code, 'UNKNOWN')once empty codes are cleaned) cleanly labels every unmatched merchant'UNKNOWN'. - Flooring before multiplying: We multiplyCAST(FLOOR(t.amount) AS INTEGER)by3, notFLOOR(3 * t.amount). For18.60,FLOOR(18.60) * 3 = 18 * 3 = 54, whereasFLOOR(3 * 18.60) = FLOOR(55.80) = 55. - SafeNULLhandling inCASE: When a merchant does not match,m.categoryisNULL. In SQL three-valued logic,NULL = 'Restaurant'evaluates toUNKNOWN(not true), so execution safely falls intoELSE 1.Mirror the LEFT JOIN in Python with a lookup dictionary
Now let's write the Python implementation tested by the judge. Scanning the
merchantslist from start to finish for every single transaction would takeO(T * M)time. Instead, we do the exact same thing a database hash join does: scanmerchantsonce to build a dictionary mappingmerchant_name -> (merchant_code, category), then look up each transaction inO(1)average time.Python
dictkeys compare strings character-for-character, so"luigi's trattoria"and"Luigi's Trattoria "will not match"Luigi's Trattoria", preserving the exact-match rule automatically. And by keeping the first row seen for any repeatedmerchant_name, we guarantee every transaction produces exactly one output dictionary.from typing import Any, Dict, List, Optional, Set, Tuple def build_merchant_lookup(merchants: List[List]) -> Dict[str, Tuple[str, str]]: """Build an exact-match map: merchant_name -> (merchant_code, category).""" # merchant_lookup: dict[str, tuple[str, str]], # e.g. {"Ramen House": ("MRC-10", "Restaurant"), "Fresh Market": ("MRC-20", "Grocery")}. merchant_lookup: Dict[str, Tuple[str, str]] = {} for merchant_name, merchant_code, category in merchants: # Keep the first row for any repeated merchant_name so a messy CSV # never duplicates transactions into multiple output rows. if merchant_name not in merchant_lookup: merchant_lookup[merchant_name] = (merchant_code, category) return merchant_lookupCalculate floored base points and category multipliers
Next, we loop through
transactionsin order, look up(merchant_code, category)with fallback("UNKNOWN", "UNKNOWN"), computebase_points = math.floor(amount), and multiply by3ifcategory == "Restaurant"(or1otherwise).Why use
math.floor(amount)instead ofint(amount)? Becauseint()truncates toward zero, whileFLOORrounds down toward negative infinity! On a negative refund like-4.20(Example 3): -int(-4.20)gives-4(wrong — truncates toward zero). -math.floor(-4.20)gives-5(correct — greatest integer<= -4.20), and returns a Pythonintdirectly.import math from typing import Any, Dict, List, Optional, Set, Tuple def join_transactions_with_merchant_points( transactions: List[List], merchants: List[List] ) -> List[Dict]: # Phase 1: Index merchants by exact merchant_name (mirrors a SQL hash LEFT JOIN). merchant_lookup = build_merchant_lookup(merchants) # Phase 2: Enrich each transaction in input order and compute integer reward points. enriched_rows: List[Dict] = [] for user_id, merchant_name, amount, _transacted_at in transactions: # Unmatched merchants still appear in the output with 'UNKNOWN' placeholders. if merchant_name in merchant_lookup: merchant_code, category = merchant_lookup[merchant_name] else: merchant_code = "UNKNOWN" category = "UNKNOWN" # math.floor rounds toward -infinity (e.g. 18.60 -> 18 and -4.20 -> -5), # whereas int(-4.20) would truncate toward zero and wrongly give -4. base_points = math.floor(amount) # Multiply AFTER flooring: Restaurant earns 3x base_points, all others earn 1x. multiplier = 3 if category == "Restaurant" else 1 final_points = base_points * multiplier enriched_rows.append({ "user_id": user_id, "merchant_code": merchant_code, "category": category, "base_points": base_points, "final_points": final_points, }) return enriched_rowsTrace Example 1 and negative refunds step by step
Let's trace Example 1 with
merchants = [["Ramen House", "MRC-10", "Restaurant"], ["Fresh Market", "MRC-20", "Grocery"]]:Step 1 — Build merchant_lookup: "Ramen House" -> ("MRC-10", "Restaurant") "Fresh Market" -> ("MRC-20", "Grocery") Step 2 — Process each transaction: Row 1: [101, "Ramen House", 18.60, ...] lookup hit -> code="MRC-10", category="Restaurant" base_points = floor(18.60) = 18, multiplier = 3 -> final_points = 54 Row 2: [204, "Fresh Market", 53.95, ...] lookup hit -> code="MRC-20", category="Grocery" base_points = floor(53.95) = 53, multiplier = 1 -> final_points = 53 Row 3: [101, "Pop-Up Bakery", 7.40, ...] lookup miss -> code="UNKNOWN", category="UNKNOWN" base_points = floor(7.40) = 7, multiplier = 1 -> final_points = 7And in Example 3,
[8, "Book Nook", -4.20, ...]matches("MRC-50", "Bookstore"), floors-4.20to-5, and earns-5final points, while[9, "Unlisted Kiosk", -0.25, ...]misses the lookup, floors-0.25to-1, and earns-1final point.Why SQL beats app post-processing, plus indexing and fuzzy matching
To address the architecture and data-hygiene parts in an interview, organize your points around three practical pillars:
1. Why execute
LEFT JOINandCASEinside SQL rather than post-processing in application memory? - Lower network I/O and memory footprint: The database returns only the compact 5-column result set rather than shipping two full raw tables across the wire into Python or Java processes. - Cost-based query optimization: Relational engines automatically choose an efficient join plan (hashing the smallermerchantscatalog in memory or probing a B-tree index) and execute compiled C/C++ loops over millions of ledger rows. - Single consistent source of truth: Encapsulating the rule in a SQL view or warehouse model ensures mobile APIs, finance reconciliation, and BI dashboards read identical reward numbers from one atomic snapshot. (Trade-off: if reward tiers evolve into stateful user caps or deeply nested rules, a versioned rules engine becomes easier to unit-test than a sprawlingCASEstatement.)2. Indexes and staging-table cleanup - Indexes: Create a
UNIQUEindex onmerchants(merchant_name)after deduplication — accelerating join probes and guaranteeing one transaction can never fan out into multiple output rows. Add an index ontransactions(transacted_at)so incremental batch jobs scan only newly arrived time windows. - Staging cleanup:TRIMleading/trailing whitespace, collapse internal runs of spaces, normalizecategorycasing/plurals ('restaurant','Restaurants'->'Restaurant'), reject blank names or codes, and route conflicting duplicate merchant names (same name mapped to two different codes) into a quarantine table for manual review.3. Reconciling inconsistent
merchant_namedescriptors - Step A — Deterministic normalization: Canonicalize both tables identically (lowercase, trim, strip punctuation and store IDs so"LUIGI'S TRATTORIA #042"and"Luigi's Trattoria"both normalize to"luigis trattoria") and join on the normalized key first. - Step B — Curated alias mapping: Maintainmerchant_aliases(raw_descriptor, merchant_code)for recurring payment-gateway prefixes ("TST* RAMEN HOUSE NYC"->"MRC-10") so known variants resolve deterministically inO(1)time. - Step C — Similarity scoring + human review + MCCs: Score remaining unmatched descriptors using trigram similarity (such as PostgreSQLpg_trgm) or edit distance, auto-link only above a strict high-precision cutoff, route borderline matches to a review queue that populatesmerchant_aliases, and combine descriptor signals with structured card Merchant Category Codes (MCCs) whenever available. Because false positives grant 3x points and carry direct financial cost, log every fuzzy match alongside its confidence score.Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple import math def build_merchant_lookup(merchants: List[List]) -> Dict[str, Tuple[str, str]]: """Build an exact-match map: merchant_name -> (merchant_code, category).""" # merchant_lookup: dict[str, tuple[str, str]], # e.g. {"Ramen House": ("MRC-10", "Restaurant"), "Fresh Market": ("MRC-20", "Grocery")}. merchant_lookup: Dict[str, Tuple[str, str]] = {} for merchant_name, merchant_code, category in merchants: # Keep the first row for any repeated merchant_name so a messy CSV # never duplicates transactions into multiple output rows. if merchant_name not in merchant_lookup: merchant_lookup[merchant_name] = (merchant_code, category) return merchant_lookup def join_transactions_with_merchant_points( transactions: List[List], merchants: List[List] ) -> List[Dict]: # Phase 1: Index merchants by exact merchant_name (mirrors a SQL hash LEFT JOIN). merchant_lookup = build_merchant_lookup(merchants) # Phase 2: Enrich each transaction in input order and compute integer reward points. enriched_rows: List[Dict] = [] for user_id, merchant_name, amount, _transacted_at in transactions: # Unmatched merchants still appear in the output with 'UNKNOWN' placeholders. if merchant_name in merchant_lookup: merchant_code, category = merchant_lookup[merchant_name] else: merchant_code = "UNKNOWN" category = "UNKNOWN" # math.floor rounds toward -infinity (e.g. 18.60 -> 18 and -4.20 -> -5), # whereas int(-4.20) would truncate toward zero and wrongly give -4. base_points = math.floor(amount) # Multiply AFTER flooring: Restaurant earns 3x base_points, all others earn 1x. multiplier = 3 if category == "Restaurant" else 1 final_points = base_points * multiplier enriched_rows.append({ "user_id": user_id, "merchant_code": merchant_code, "category": category, "base_points": base_points, "final_points": final_points, }) return enriched_rows✅ Submit now — all tests should pass.
Intuition & how it works
Imagine processing thousands of card receipts against a directory of partner stores to calculate loyalty points. Instead of flipping through the entire partner directory from page 1 for every single receipt, you first build an alphabetical tab index keyed by store name — a dictionary in Python, or a hash join in SQL (a join strategy where the database loads the smaller table into an in-memory hash table once and probes it for each row of the larger table in constant average time). As each receipt arrives, you look up its store name in one step: if it is in the index, you copy its merchant code and category; if it is missing, you keep the receipt anyway and stamp 'UNKNOWN' on both fields. That "keep every left-side row even when the right side has no match" rule is called a LEFT JOIN (a SQL join that preserves all rows from the left table and fills unmatched right-table columns with NULL). Finally, you drop fractional cents using floor rounding and triple the floored points whenever the category is 'Restaurant'.
A naive implementation fails in two ways. In Python, scanning all M merchants for each of the T transactions takes O(T * M) comparisons, turning 100,000 transactions across 10,000 merchants into a billion string checks. In SQL, reaching for a default INNER JOIN silently deletes every transaction whose merchant is absent from merchants.csv, losing customer spend instead of tagging it 'UNKNOWN'.
Let's walk through Example 1 with merchants = [["Ramen House", "MRC-10", "Restaurant"], ["Fresh Market", "MRC-20", "Grocery"]]:
- First, we index the two merchants: {"Ramen House": ("MRC-10", "Restaurant"), "Fresh Market": ("MRC-20", "Grocery")}.
- Transaction 1 (user 101, "Ramen House", 18.60) hits "Ramen House", floors 18.60 to base_points = 18, and triples it because "Restaurant" earns 3x -> final_points = 54.
- Transaction 2 (user 204, "Fresh Market", 53.95) hits "Fresh Market", floors 53.95 to base_points = 53, and keeps 1x -> final_points = 53.
- Transaction 3 (user 101, "Pop-Up Bakery", 7.40) misses the index, falls back to ("UNKNOWN", "UNKNOWN"), floors 7.40 to base_points = 7, and earns 1x -> final_points = 7.
Complexity
- Time:
O(M + T)average time in Python (and for a SQL hash join), whereMis the number of merchant rows andTis the number of transactions. We scan theMmerchants once to buildmerchant_lookup, and then scan theTtransactions once, doing oneO(1)average-time dictionary lookup and constant-time arithmetic per transaction. (In a SQL engine without hash joins, such as SQLite, an index lookup onmerchants(merchant_name)runs inO((M + T) log M)time.) - Space:
O(M + T)total space —O(M)to hold the unique merchants inmerchant_lookupplusO(T)to store the enriched output row for each transaction (O(M)auxiliary space if streaming rows out one by one).
Edge cases
- Unmatched merchant names: Transactions with no match in
merchantsare never dropped; they receivemerchant_code = 'UNKNOWN',category = 'UNKNOWN', and a1xmultiplier. - Empty
merchantsor emptytransactions: Iftransactionsis empty, the output is[]. Ifmerchantsis empty, every transaction becomes'UNKNOWN'and earns1xfloored points. - Case sensitivity and trailing spaces: Under exact matching,
"ramen house"and"Ramen House "do not match"Ramen House"and both fall back to'UNKNOWN'. - Negative amounts (refunds/chargebacks):
FLOORrounds toward negative infinity, not toward zero, so-4.20floors to-5and-0.25floors to-1. A-2.4refund at a'Restaurant'producesbase_points = -3andfinal_points = -9. - Sub-dollar and whole-dollar amounts:
0.85floors to0(0 * 3 = 0points even at a restaurant), while40stays40(120at a restaurant). - Duplicate
merchant_namerows inmerchants: Without deduplication, a SQLLEFT JOINemits two output rows for one transaction and double-awards points. Deduplicatingmerchantsbymerchant_name(and keeping the first row in Python) preserves the strict one-row-per-transaction contract.
Common mistakes
- Using
INNER JOINinstead ofLEFT JOIN:FROM transactions JOIN merchants ...drops every unmatched merchant row completely instead of labeling it'UNKNOWN'. - Using
ROUNDorint()truncation instead ofFLOOR:ROUND(53.95)gives54instead of53, and truncating toward zero (int(-4.20)in Python orCAST(-4.20 AS INTEGER)in SQLite) gives-4instead of-5. - Multiplying before flooring: Computing
FLOOR(amount * 3)on18.60yieldsFLOOR(55.80) = 55, whereas the specification definesbase_points = FLOOR(amount) = 18andfinal_points = 3 * base_points = 54. - Writing inverted
NULL-unsafeCASElogic in SQL: WritingCASE WHEN m.category <> 'Restaurant' THEN 1 ELSE 3 ENDawards3xpoints to unmatched'UNKNOWN'merchants! Why? Because whenm.categoryisNULL,NULL <> 'Restaurant'evaluates to SQLUNKNOWN(not true), falling straight intoELSE 3. Always test the positive conditionWHEN m.category = 'Restaurant' THEN 3 ELSE 1. - Ignoring database string collation rules: A collation is the set of rules a database uses to compare and sort text strings. MySQL's default
_ci(case-insensitive) collations treat'ramen house' = 'Ramen House'as true and some ignore trailing spaces, silently violating an exact-match requirement unless a case-sensitive binary collation is specified.
Follow-up questions
- How would you evolve the database schema so temporary category bonus campaigns (such as 5x points on Travel during a holiday window) require zero code deployments? Move multipliers out of hardcoded
CASEbranches into a rule tablecategory_promotions(category, multiplier, starts_at, ends_at)andLEFT JOINit onm.category = p.category AND t.transacted_at >= p.starts_at AND t.transacted_at < p.ends_at, falling back toCOALESCE(p.multiplier, 1). Launching a campaign becomes a data insert rather than a code release, and historical backfills automatically apply whichever multiplier was active at each transaction'stransacted_attimestamp. - How can an hourly scheduled pipeline enrich newly arrived transactions safely so retries never double-credit user points? Ensure every ledger event carries a unique
transaction_idprimary key at ingestion (since one customer can legitimately make two identical purchases in the same second). Track a watermark (the latest timestamp processed by the prior successful run), read a small overlap window before that watermark to catch late-arriving records, and write enriched rows via an upsert (INSERT ... ON CONFLICT (transaction_id) DO UPDATE). That makes each hourly run idempotent (safe to re-execute on the same input while producing the exact same final state). - Which automated validation checks should gate each batch run before points are posted to customer balances? Assert row-count conservation (
COUNT(*)of enriched rows equalsCOUNT(*)of input transactions — immediately catching accidentalINNER JOINdrops or duplicate-merchant fan-out), verifyfinal_pointsalways equalsbase_pointsor3 * base_points, and alert on spikes in the'UNKNOWN'merchant fraction. A sudden jump in'UNKNOWN'share typically indicates an upstreammerchants.csvformatting change or a payment processor altering descriptor prefixes.
Follow-up questions
- How would you evolve the database schema so temporary category bonus campaigns (such as 5x points on Travel during a holiday window) require zero code deployments?
- How can an hourly scheduled pipeline enrich newly arrived transactions safely so retries never double-credit user points?
- Which automated validation checks should gate each batch run before points are posted to customer balances?
Similar questions
- Isolate and Repair Failing Java Unit Tests
- Auditable Loyalty Points Engine and Ledger
- Idempotent Card Rewards and Monthly Qualification Engine
- Job Posting Engagement Metrics Excluding Non-Viewing Applicants
- Compute 7-Day DAU, D1 Retention, and Revenue Cohorts
- Class-Level 2024 Exam Summary with Zero-Filled Averages