Score Multi-Product Borrowers Across Two Daily Logs
Medium · Data Manipulation (SQL/Python) · Software Engineer · Technical Screen
Problem Statement
Implement a log-processing pipeline that identifies repeat borrowers who use multiple loan products across two consecutive daily transaction feeds and ranks them with a caller-supplied scoring function.
You receive two transaction lists, day1_logs and day2_logs, together with a scoring callback trust_policy. Every entry in either list is a dictionary with four keys:
user_id(str): Borrower account identifier.loan_id(str): Transaction identifier (unique across records).loan_type(str): Product category label (such as"term_loan","split_4", or"credit_line").amount(float): Loan principal value.
A borrower qualifies for scoring when both criteria hold:
- At least one transaction for
user_idexists inday1_logsand at least one exists inday2_logs. - Combining that borrower's records across both days yields at least
2uniqueloan_typestrings.
For each qualifying borrower (and never for disqualified borrowers), assemble a summary dictionary and pass it to trust_policy(profile) -> float:
user_id(str): Borrower identifier.distinct_loan_types(set[str]): All uniqueloan_typelabels seen for this borrower across Day 1 and Day 2.total_amount(float): Exact sum ofamountacross both days for this borrower, rounded to2decimal places.day1_tx_count(int): Count of records for this borrower inday1_logs.day2_tx_count(int): Count of records for this borrower inday2_logs.
from typing import List, Dict, Any, Callable
def evaluate_returning_borrowers(
day1_logs: List[Dict[str, Any]],
day2_logs: List[Dict[str, Any]],
trust_policy: Callable[[Dict[str, Any]], float]
) -> List[Dict[str, Any]]:
...
Return a list of dictionaries—one per qualifying borrower—each containing strictly the three keys user_id, trust_score, and total_amount (where trust_score is the float returned by trust_policy(profile)). Order the output from highest trust_score to lowest, resolving equal scores by user_id in ascending lexicographical order ("a" before "b").
Examples
Example 1
day1_logs = [
{"user_id": "acct_maya", "loan_id": "tx_101", "loan_type": "term_loan", "amount": 400.0},
{"user_id": "acct_noah", "loan_id": "tx_102", "loan_type": "split_4", "amount": 80.0},
{"user_id": "acct_omar", "loan_id": "tx_103", "loan_type": "term_loan", "amount": 150.0},
]
day2_logs = [
{"user_id": "acct_maya", "loan_id": "tx_201", "loan_type": "split_4", "amount": 120.0},
{"user_id": "acct_noah", "loan_id": "tx_202", "loan_type": "split_4", "amount": 60.0},
]
def demo_policy(profile: Dict[str, Any]) -> float:
return round(len(profile["distinct_loan_types"]) * 15.0 + profile["total_amount"] * 0.05, 2)
evaluate_returning_borrowers(day1_logs, day2_logs, demo_policy)
# -> [{"user_id": "acct_maya", "trust_score": 56.0, "total_amount": 520.0}]
Walk-through: acct_omar has no Day 2 activity and is filtered out. acct_noah borrows on both days, yet uses "split_4" exclusively (1 unique product), so acct_noah is also filtered out. acct_maya borrows on both days across 2 unique products ("term_loan" and "split_4") with total_amount = 400.0 + 120.0 = 520.0, producing trust_score = 2 * 15.0 + 520.0 * 0.05 = 56.0.
Example 2
day1_logs = [
{"user_id": "acct_zoe", "loan_id": "tx_301", "loan_type": "split_4", "amount": 90.0},
{"user_id": "acct_zoe", "loan_id": "tx_302", "loan_type": "credit_line", "amount": 110.0},
{"user_id": "acct_ava", "loan_id": "tx_303", "loan_type": "term_loan", "amount": 150.0},
]
day2_logs = [
{"user_id": "acct_zoe", "loan_id": "tx_401", "loan_type": "split_4", "amount": 50.0},
{"user_id": "acct_ava", "loan_id": "tx_402", "loan_type": "credit_line", "amount": 100.0},
]
def flat_tier_policy(profile: Dict[str, Any]) -> float:
return float(len(profile["distinct_loan_types"]) * 20)
evaluate_returning_borrowers(day1_logs, day2_logs, flat_tier_policy)
# -> [
# {"user_id": "acct_ava", "trust_score": 40.0, "total_amount": 250.0},
# {"user_id": "acct_zoe", "trust_score": 40.0, "total_amount": 250.0},
# ]
Walk-through: acct_zoe already reaches 2 unique loan products on Day 1 and returns on Day 2 (day1_tx_count = 2, day2_tx_count = 1, total_amount = 250.0), so acct_zoe qualifies even though Day 2 repeats "split_4". acct_ava also qualifies (total_amount = 250.0). Both receive trust_score = 40.0, so "acct_ava" sorts ahead of "acct_zoe" alphabetically.
Constraints
0 <= len(day1_logs), len(day2_logs) <= 100,0000.01 <= amount <= 50,000.0(positivefloatvalues; guard against binary floating-point accumulation drift before roundingtotal_amountto2decimal places).- Every log dictionary has a unique
loan_id. - Either input list (or both) can be empty.
- Grouping and eligibility filtering must run in
O(N + M)expected time forN = len(day1_logs)andM = len(day2_logs), followed byO(K log K)sorting over theKqualifying borrowers (assumingO(1)pertrust_policycall).
Step-by-step walkthrough
Understand the eligibility rules and output shape
We receive two daily lists of loan transaction dictionaries (
day1_logsandday2_logs) along with a plug-in scoring functiontrust_policy(profile) -> float. Each transaction has four fields:user_id,loan_id,loan_type, andamount.A borrower is eligible if and only if both conditions hold:
- Returning across consecutive days: at least 1 transaction in
day1_logsand at least 1 transaction inday2_logs. - Product diversity: at least 2 distinct
loan_typevalues across all of their Day 1 and Day 2 records combined.
Watch out for two subtle cases right away:
Borrower Day 1 loan_types Day 2 loan_types Distinct union Qualifies? ---------- ---------------------------- ----------------- ----------------------------- ---------- acct_zoe ["split_4", "credit_line"] ["split_4"] {"split_4", "credit_line"} YES (both days, 2 products overall) acct_noah ["split_4"] ["split_4"] {"split_4"} NO (repeats of 1 product don't count) acct_omar ["term_loan"] [] {"term_loan"} NO (missing from Day 2)For each eligible borrower, we build a 5-field
profile, computetrust_score = trust_policy(profile), and return[{"user_id": ..., "trust_score": ..., "total_amount": ...}]sorted bytrust_scoredescending and tieduser_idascending.- Returning across consecutive days: at least 1 transaction in
Why the naive nested scan is too slow
A beginner's first instinct is often to collect all unique user IDs and, for each user, scan
day1_logsandday2_logsfrom start to finish to gather their transactions:Suppose len(day1_logs) = N = 100,000 and len(day2_logs) = M = 100,000: Up to (N + M) = 200,000 unique users x scanning (N + M) = 200,000 records per user = 40,000,000,000 (~4 x 10^10) dictionary checks -> seconds or minutes in Python!Instead of re-scanning the lists for every user, we want to touch each log record once. Grouping records in a hash map (a Python
dictkeyed byuser_id) turns per-record lookup and update intoO(1)expected work, dropping total aggregation time fromO((N + M)^2)toO(N + M).Aggregate each day in one O(N) pass
Should we throw Day 1 and Day 2 into a single dictionary or build one dictionary per day? Building one dictionary per day (
day1_statsandday2_stats) keeps the code clean and bug-free:- Checking whether a borrower appeared on both days becomes a single
if user_id not in day2_stats:key lookup. day1_tx_countandday2_tx_countstay naturally separated without extraif day == 1branches.- Storing
loan_typesin a Pythonsetautomatically collapses duplicate loan types on the same day.
from typing import List, Dict, Any, Callable def aggregate_day(logs: List[Dict[str, Any]]) -> Dict[str, Dict[str, Any]]: """Aggregate one day's transactions per user in a single O(len(logs)) pass.""" # stats: maps user_id -> {"loan_types": set, "amounts": list, "tx_count": int} stats: Dict[str, Dict[str, Any]] = {} for record in logs: user_id = record["user_id"] if user_id not in stats: stats[user_id] = { "loan_types": set(), "amounts": [], "tx_count": 0, } user_entry = stats[user_id] user_entry["loan_types"].add(record["loan_type"]) user_entry["amounts"].append(record["amount"]) user_entry["tx_count"] += 1 return stats- Checking whether a borrower appeared on both days becomes a single
Sum loan amounts accurately and build the borrower profile
Once a
user_idappears in bothday1_statsandday2_stats, we combine their loan categories with a set union:combined_loan_types = day1_entry["loan_types"] | day2_entry["loan_types"]. Only iflen(combined_loan_types) >= 2do we build the profile.Financial totals require care with floating-point arithmetic. Because computers store floats in base 2 rather than base 10,
0.1 + 0.2 + 0.3evaluates to0.6000000000000001, and a naivetotal += amountloop can even give slightly different last bits depending on transaction order. We solve both issues cleanly:math.fsum(...)tracks exact intermediate carries so the sum is accurate to the last bit and independent of log order.round(exact_total, 2)rounds the final sum to 2 decimal places as required by the specification (handling both float representation noise like0.6000000000000001 -> 0.6and sub-cent inputs like1.234 + 2.345 = 3.579 -> 3.58).
import math def build_profile( user_id: str, day1_entry: Dict[str, Any], day2_entry: Dict[str, Any], combined_loan_types: set, ) -> Dict[str, Any]: """Construct the borrower summary dictionary passed into trust_policy(profile).""" all_amounts = day1_entry["amounts"] + day2_entry["amounts"] exact_total = math.fsum(all_amounts) rounded_total = round(exact_total, 2) return { "user_id": user_id, "distinct_loan_types": combined_loan_types, "total_amount": rounded_total, "day1_tx_count": day1_entry["tx_count"], "day2_tx_count": day2_entry["tx_count"], }Decouple scoring and sort with a mixed-direction key
Notice that
evaluate_returning_borrowersnever hardcodes a scoring formula — it calls the injectedtrust_policy(profile)function only for eligible borrowers. Keeping data aggregation separate from scoring policy means risk engineers can swap a heuristic formula for a machine-learning scorer without touching the log-processing code, and unit tests can pass a mock function to verify the exact profile passed in. We also readtotal_amount = profile["total_amount"]before callingtrust_policy(profile)so even an external policy that mutates its input dictionary cannot corrupt our output.Finally, we need to sort results by
trust_scoredescending, breaking ties byuser_idascending ("a"before"b"). Passingreverse=Trueon(score, user_id)would flip both fields and break ties backwards ("b"before"a"). Instead, we negate the numeric score in an ascending sort key:Suppose "a", "b", and "c" are tied at trust_score = 20.0, while "d" has trust_score = 35.0: Result row ranking_key = (-trust_score, user_id) Sorted position --------------------------- ------------------------------------- --------------- {"user_id": "d", score: 35} (-35.0, "d") 1st (most negative -score) {"user_id": "a", score: 20} (-20.0, "a") 2nd ("a" < "b" < "c") {"user_id": "b", score: 20} (-20.0, "b") 3rd {"user_id": "c", score: 20} (-20.0, "c") 4thdef ranking_key(result: Dict[str, Any]) -> tuple: """Sort highest trust_score first (-score), breaking ties by user_id ascending.""" return (-result["trust_score"], result["user_id"])Trace Example 1 step by step
Let's trace Example 1 with
demo_policy(p) = round(len(p["distinct_loan_types"]) * 15.0 + p["total_amount"] * 0.05, 2):Input logs: Day 1: (acct_maya, tx_101, "term_loan", 400.0), (acct_noah, tx_102, "split_4", 80.0), (acct_omar, tx_103, "term_loan", 150.0) Day 2: (acct_maya, tx_201, "split_4", 120.0), (acct_noah, tx_202, "split_4", 60.0) Phase 1 — per-day dictionaries: day1_stats = { "acct_maya": {"loan_types": {"term_loan"}, "amounts": [400.0], "tx_count": 1}, "acct_noah": {"loan_types": {"split_4"}, "amounts": [80.0], "tx_count": 1}, "acct_omar": {"loan_types": {"term_loan"}, "amounts": [150.0], "tx_count": 1}, } day2_stats = { "acct_maya": {"loan_types": {"split_4"}, "amounts": [120.0], "tx_count": 1}, "acct_noah": {"loan_types": {"split_4"}, "amounts": [60.0], "tx_count": 1}, } Phase 2 & 3 — intersect, check diversity, build profile, and score: acct_maya -> in both days; types = {"term_loan"} | {"split_4"} (size 2 >= 2 -> QUALIFIES) profile = {"user_id": "acct_maya", "distinct_loan_types": {"term_loan", "split_4"}, "total_amount": 520.0, "day1_tx_count": 1, "day2_tx_count": 1} score = 2 * 15.0 + 520.0 * 0.05 = 56.0 acct_noah -> in both days; types = {"split_4"} | {"split_4"} = {"split_4"} (size 1 < 2 -> SKIPPED) acct_omar -> missing from day2_stats -> SKIPPED Phase 4 — sorted output: [{"user_id": "acct_maya", "trust_score": 56.0, "total_amount": 520.0}]Complete solution
from typing import List, Dict, Any, Callable import math def aggregate_day(logs: List[Dict[str, Any]]) -> Dict[str, Dict[str, Any]]: """Aggregate one day's transactions per user in a single O(len(logs)) pass.""" # stats: maps user_id -> { # "loan_types": set of str (e.g. {"term_loan", "split_4"}), # "amounts": list of float (e.g. [400.0, 120.0]), # "tx_count": int (number of transactions on this day), # } stats: Dict[str, Dict[str, Any]] = {} for record in logs: user_id = record["user_id"] if user_id not in stats: stats[user_id] = { "loan_types": set(), "amounts": [], "tx_count": 0, } user_entry = stats[user_id] user_entry["loan_types"].add(record["loan_type"]) user_entry["amounts"].append(record["amount"]) user_entry["tx_count"] += 1 return stats def build_profile( user_id: str, day1_entry: Dict[str, Any], day2_entry: Dict[str, Any], combined_loan_types: set, ) -> Dict[str, Any]: """Construct the borrower summary dictionary passed into trust_policy(profile).""" # math.fsum computes an exact floating-point sum so record order never changes the total, # and round(..., 2) eliminates binary float artifacts like 0.1 + 0.2 + 0.3 = 0.6000000000000001. all_amounts = day1_entry["amounts"] + day2_entry["amounts"] exact_total = math.fsum(all_amounts) rounded_total = round(exact_total, 2) return { "user_id": user_id, "distinct_loan_types": combined_loan_types, "total_amount": rounded_total, "day1_tx_count": day1_entry["tx_count"], "day2_tx_count": day2_entry["tx_count"], } def ranking_key(result: Dict[str, Any]) -> tuple: """Sort highest trust_score first (-score), breaking ties by user_id ascending.""" # Negating trust_score lets a single ascending sort order scores high-to-low while # keeping user_id in A-to-Z lexicographical order (unlike reverse=True, which flips both). return (-result["trust_score"], result["user_id"]) def evaluate_returning_borrowers( day1_logs: List[Dict[str, Any]], day2_logs: List[Dict[str, Any]], trust_policy: Callable[[Dict[str, Any]], float] ) -> List[Dict[str, Any]]: # Phase 1: summarize each day independently in O(N + M) expected time. day1_stats = aggregate_day(day1_logs) day2_stats = aggregate_day(day2_logs) # Phase 2: filter to borrowers active on BOTH days with >= 2 distinct loan types overall. # results: list of {"user_id": str, "trust_score": float, "total_amount": float} results: List[Dict[str, Any]] = [] for user_id, day1_entry in day1_stats.items(): if user_id not in day2_stats: continue day2_entry = day2_stats[user_id] # Set union combines distinct loan categories across Day 1 and Day 2 together. combined_loan_types = day1_entry["loan_types"] | day2_entry["loan_types"] if len(combined_loan_types) < 2: continue # Phase 3: build the profile, save total_amount before calling the external policy, # and score only eligible borrowers. profile = build_profile(user_id, day1_entry, day2_entry, combined_loan_types) total_amount = profile["total_amount"] score = trust_policy(profile) results.append({ "user_id": user_id, "trust_score": score, "total_amount": total_amount, }) # Phase 4: sort the K eligible borrowers in O(K log K) time. results.sort(key=ranking_key) return results✅ Submit now — all tests should pass.
Intuition & how it works
Picture a lending clerk reviewing Monday's and Tuesday's paper receipt stacks to find loyal borrowers who use more than one credit product. Instead of picking one customer's name and flipping through all 200,000 receipts from top to bottom over and over, the clerk makes one pass through Monday's stack to jot down a mini-folder per customer (products used, dollar amounts, receipt count), makes one pass through Tuesday's stack to do the same, and then checks only customers who have a folder on both days and at least two unique loan types across their two folders combined. Each qualifying folder is handed to a separate scoring rulebook (trust_policy), and the winning summaries are sorted from highest score to lowest.
The naive approach — looping over every unique user_id and scanning day1_logs and day2_logs inside the loop — takes O((N + M)^2) time, reaching tens of billions of operations when N = M = 100,000. Beginners also get tripped up by floating-point arithmetic (0.1 + 0.2 + 0.3 produces 0.6000000000000001 in standard binary floats) and by sorting with reverse=True, which accidentally reverses alphabetical tie-breaking on user_id.
Walk through Example 1 (acct_maya takes a 400.0 "term_loan" on Day 1 and a 120.0 "split_4" loan on Day 2; acct_noah takes "split_4" loans of 80.0 and 60.0 on Days 1 and 2; acct_omar takes 150.0 on Day 1 only):
1. Per-day hash maps: day1_stats records acct_maya ({"term_loan"}, [400.0], count 1), acct_noah ({"split_4"}, [80.0], count 1), and acct_omar; day2_stats records acct_maya ({"split_4"}, [120.0], count 1) and acct_noah ({"split_4"}, [60.0], count 1).
2. Intersection & diversity check: acct_omar is absent from day2_stats. Both acct_maya and acct_noah appear on both days, and taking the set union (combining two sets while discarding duplicates) gives acct_maya {"term_loan", "split_4"} (size 2 >= 2, qualifies) and acct_noah {"split_4"} (size 1 < 2, excluded).
3. Profile & scoring: acct_maya gets total_amount = round(fsum([400.0, 120.0]), 2) = 520.0 and trust_score = 2 * 15.0 + 520.0 * 0.05 = 56.0, returning [{"user_id": "acct_maya", "trust_score": 56.0, "total_amount": 520.0}].
Complexity
Let N = len(day1_logs), M = len(day2_logs), U be the number of unique users, and K be the number of eligible returning borrowers (K <= min(N, M)).
- Time —
O(N + M + K log K)expected (assumingO(1)pertrust_policycall):- Scanning
day1_logsandday2_logsonce performs one hash map (dictionary withO(1)average key lookup) operation, oneset.add, and one listappendper transaction, costingO(N + M)expected time. - Iterating through
day1_statschecksuser_id in day2_statsinO(1)average time per user; across all returning users, unioningloan_typessets and summingamountswithmath.fsumvisits at mostN + Mstored items in total (O(N + M)). - Calling
trust_policyrunsKtimes (once per eligible user), and sorting theKoutput dictionaries takesO(K log K)comparisons.
- Scanning
- Space —
O(N + M):- Storing per-user
amountslists andloan_typessets across both days holds at mostN + Mfloats andN + Mloan-type strings in memory. (If memory is tight and record-order-exact summation before rounding is not needed, accumulating a runningtotal += amountfloat per user shrinks space toO(U * T)forUusers andTdistinct loan types.)
- Storing per-user
Edge cases
- Empty
day1_logs, emptyday2_logs, or both empty: Nouser_idcan exist in both dictionaries, so the loop finishes immediately,trust_policyis called0times, and[]is returned. - Multiple loans of the same type across both days: Three
"term_loan"records across Day 1 and Day 2 collapse to a 1-element set{"term_loan"}, disqualifying the borrower. - All product diversity occurs on a single day: A borrower with
"split_4"+"credit_line"on Day 1 and"split_4"again on Day 2 still has union size2and does qualify, because diversity is defined across combined records from both days. - IEEE-754 floating-point drift and sub-cent amounts: IEEE-754 floating-point drift (tiny rounding errors caused by storing base-10 decimals in base-2 binary floats) turns
0.1 + 0.2 + 0.3into0.6000000000000001;math.fsumfollowed byround(..., 2)returns exact0.6, and sums like1.234 + 2.345 = 3.579round cleanly to3.58. - Tied
trust_scorevalues: Ties sort in ascending lexicographical order ("a"before"b","u10"before"u2"), handled cleanly by(-result["trust_score"], result["user_id"]). - External
trust_policymutating its input dict: Savingtotal_amount = profile["total_amount"]before invokingtrust_policy(profile)protects the output row even if a caller's policy modifiesprofilein place.
Common mistakes
- Checking
len(day1_types) >= 2 and len(day2_types) >= 2or requiring Day 2's type to differ from Day 1's: Disqualifies a valid borrower who took two loan types on Day 1 and returned with one of those types on Day 2. - Scanning
day2_logsas a list (any(r["user_id"] == u for r in day2_logs)) inside a loop: Turns anO(N + M)pass into anO(N * M)bottleneck (~10^10checks at100,000logs/day). - Sorting with
results.sort(key=lambda r: (r["trust_score"], r["user_id"]), reverse=True):reverse=Trueinverts both tuple elements, breaking ties byuser_iddescending ("c", "b", "a") instead of ascending ("a", "b", "c"). - Rounding individual transactions before summing, or rounding
trust_score: Rounding per transaction accumulates cent errors on fractional fees (1.234 + 2.345rounded early gives1.23 + 2.35 = 3.58, whereas1.004 + 1.004gives2.00instead of2.01), and the specification leavestrust_scorerounding strictly up totrust_policy. - Calling
trust_policybefore filtering out ineligible users: Wastes compute (especially whentrust_policycalls an ML model or external service) and breaks tests verifying that only eligible profiles reach the policy. - Returning extra profile fields in the final output: Each output dictionary must contain only
user_id,trust_score, andtotal_amount.
Alternative approaches
- Single combined hash map with day flags: Maintain one dictionary keyed by
user_idstoringday1_tx_count,day2_tx_count,loan_types, andamounts, then filter withday1_tx_count >= 1 and day2_tx_count >= 1 and len(loan_types) >= 2. Asymptotically identical (O(N + M)time and space) with slightly fewer hash lookups when most users return, though two per-day maps keepaggregate_daycompletely reusable across any number of days. - Fixed-point
Decimalarithmetic: Converting amounts viaDecimal(str(amount))performs exact base-10 arithmetic without binary float representation artifacts, at roughly 10–20x higher CPU cost per addition thanmath.fsumon native floats.
Follow-up questions
- If each day's transaction feed grows beyond single-node RAM, how would you redesign this pipeline in SQL or Spark? Tag Day 1 rows with
log_day = 1and Day 2 rows withlog_day = 2viaUNION ALL, then run a single distributedGROUP BY user_id(which hash-partitions records byuser_idacross cluster workers in one shuffle without any expensive raw-log join). Store monetary columns as exactDECIMAL(12, 2)and evaluatetrust_policyas a vectorized UDF (or in Python on the filtered qualifying output, which is typically much smaller than raw logs):
sql
SELECT
user_id,
COUNT(DISTINCT loan_type) AS distinct_type_count,
ROUND(SUM(amount), 2) AS total_amount,
SUM(CASE WHEN log_day = 1 THEN 1 ELSE 0 END) AS day1_tx_count,
SUM(CASE WHEN log_day = 2 THEN 1 ELSE 0 END) AS day2_tx_count
FROM (
SELECT 1 AS log_day, user_id, loan_type, amount FROM day1_logs
UNION ALL
SELECT 2 AS log_day, user_id, loan_type, amount FROM day2_logs
) AS combined_logs
GROUP BY user_id
HAVING SUM(CASE WHEN log_day = 1 THEN 1 ELSE 0 END) >= 1
AND SUM(CASE WHEN log_day = 2 THEN 1 ELSE 0 END) >= 1
AND COUNT(DISTINCT loan_type) >= 2;
- What changes are needed if upstream retries produce duplicate loan_id records within or across the two daily feeds? Enforce idempotency (processing a retried event multiple times produces the exact same state as processing it once) by tracking seen
loan_idstrings in aseen_loan_idsset across Day 1 first and Day 2 second. If aloan_idfrom Day 1 reappears in Day 2 due to a retry across midnight, attributing it solely to its earliest timestamp prevents a single-day borrower from falsely qualifying as a two-day returning borrower; if a duplicateloan_idarrives with a differentuser_idoramount, flag or log a data-integrity anomaly rather than silently dropping it. In SQL or Spark, applyROW_NUMBER() OVER (PARTITION BY loan_id ORDER BY event_timestamp ASC) = 1before grouping byuser_id. - Suppose the scoring callback needs 30-day rolling borrower metrics instead of just two days — how would you structure storage and pre-aggregation to stay fast? Avoid re-scanning 30 days of raw transaction logs on every run; instead maintain a daily rollup table (pre-aggregated summary rows keyed by
(user_id, activity_date, loan_type)storingtx_countandamount_sum). A 30-day borrower profile then sums at most30 * Ttiny summary rows per user (forTloan types), or updates a sliding 30-day state inO(T)time by adding DayDand subtracting DayD - 30— storing per-type integer counts ({"split_4": 4, "term_loan": 1}) rather than plain sets so a loan type is removed only when its 30-day count drops to zero, and serving precomputed profiles from a low-latency feature store (a key-value database of ready-to-use model/policy inputs keyed byuser_id).
Follow-up questions
- If each day's transaction feed grows beyond single-node RAM, how would you redesign this pipeline in SQL or Spark?
- What changes are needed if upstream retries produce duplicate loan_id records within or across the two daily feeds?
- Suppose the scoring callback needs 30-day rolling borrower metrics instead of just two days — how would you structure storage and pre-aggregation to stay fast?
Similar questions
- Per-Loan Payment Summary Metrics
- Event Log Filtering, Deduplication, and Debugging
- Chronological Loan Repayment Waterfall
- Lender Profit on Simple-Interest Loans
- Evaluating New Products and Merchant Segments for a Consumer Lender
- Minimum Transfers for Group Debt Settlement
More Affirm interview questions
- Evaluating New Products and Merchant Segments for a Consumer Lender Medium
- Presenting Your Most Consequential Engineering Initiative Medium
- Daily-Window Installment Loan Repayment System Medium Pro
- High-Card Game Engine with Carryover Pots Easy Pro
- Hiring Manager Screen: Complex Systems, Schedule Pressure, and Cross-Functional Execution Medium Pro
- Event Log Filtering, Deduplication, and Debugging Medium Pro
- Diagnosing a Quarterly Rise in Portfolio Delinquency Medium Pro
- Two-Player and N-Player High-Card Simulation Hard Pro
- Chronological Loan Repayment Waterfall Medium Pro
- Per-Loan Payment Summary Metrics Medium Pro