Anomaly and Fraud Detection Questions
Detecting rare, abnormal, or adversarial events in data. Covers anomaly-detection techniques, fraud and risk modeling, handling extreme class imbalance, and the precision/recall and latency tradeoffs of real-time detection systems. Focuses on the modeling patterns unique to needle-in-a-haystack detection problems.
Your fraud model's investigation team can manually review at most 500 flagged cases per day, and a missed fraud case costs far more than a wasted review. Walk through how you would pick the model's operating threshold given that capacity constraint, and how your answer would change if the review team's capacity were cut in half overnight.
Sample Answer
Direct answer
Pick the threshold that flags exactly as many cases per day as your review team can actually handle, ranking transactions by model score and drawing the line at your daily capacity, rather than picking a threshold in the abstract and hoping the resulting volume happens to fit. If capacity is cut in half, you move the threshold higher, which mechanically improves precision (fewer of the flagged cases are wasted review time) at the direct cost of recall (you now miss more real fraud that would have been caught at the lower bar).
Structured elaboration
- Rank, then cut by capacity: sort all transactions by the model's predicted fraud probability and take the top N, where N is your daily review capacity. The threshold is then whatever score the Nth-ranked case has; you do not pick the threshold first and hope the volume works out.
- Why this beats a fixed cost-matrix threshold on its own: a pure cost-matrix threshold (minimizing an expected-cost formula) can recommend flagging far more or far fewer cases than your review team can physically process on a given day; a capacity-based cut guarantees the operational plan is executable, and you fold cost-asymmetry in by weighting WHICH cases get the queue slots (e.g., prioritizing higher-dollar-value flagged cases) rather than by moving the count.
- What happens under a capacity cut: halving capacity necessarily raises the threshold (since you can only take the top N/2 instead of top N by score). A higher threshold means the flagged set is a purer, higher-confidence subset, so precision goes up; but every case between the old and new threshold that was genuinely fraud is now missed, so recall goes down.
Worked example (executed)
Simulated 100,000 transactions/day at a 0.5% true fraud rate, with model scores that separate fraud from legitimate transactions imperfectly (a realistic overlapping-scores setup):
import numpy as np
rng = np.random.default_rng(0)
n = 100000
fraud_rate = 0.005
y = rng.binomial(1, fraud_rate, size=n)
scores = np.where(y == 1, rng.beta(4, 2, size=n), rng.beta(2, 5, size=n))
capacity = 500
threshold = np.sort(scores)[::-1][capacity - 1]
flagged = scores >= threshold
precision = y[flagged].mean()
recall = y[flagged].sum() / y.sum()
Executed result:
total transactions/day: 100000, true fraud/day: 515
threshold to flag exactly 500 cases/day: 0.7700
at that threshold: precision=0.360, recall=0.350, cases flagged=500
if capacity is cut to 250/day:
threshold=0.8138, precision=0.504, recall=0.245, cases flagged=250
recall drop from halving capacity: 0.105 absolute (30.0% relative)
Cutting capacity in half raised precision from 0.36 to 0.50 but dropped recall from 0.35 to 0.245, a 30% relative loss in the fraud actually caught, for exactly the reason described above: the marginal cases you can no longer afford to review are disproportionately real fraud, because the model ranks them above the new cutoff on legitimate grounds.
Trade-offs and pitfalls
A pure capacity cut treats every review-queue slot as equally valuable, but in practice you usually also want to weight the ranking by dollar exposure or severity, not raw fraud probability alone, so the queue prioritizes the cases where a miss is most costly. It's also worth explicitly flagging to stakeholders, in dollar terms, what a capacity cut costs in newly-missed fraud, since "recall dropped 30%" lands very differently from "this change will let through roughly $X more in fraud losses per month."
A fraud model's performance has been quietly degrading over several months as fraud patterns evolve, not because of a data-pipeline break but because fraudsters are behaving differently than they did when the model was trained. How would you tell the difference between this kind of adversarial pattern drift and an ordinary data-quality problem, and what would you do about it?
Sample Answer
Direct answer
Tell the difference by looking at WHERE the degradation concentrates: adversarial pattern drift (fraudsters behaving differently on purpose) tends to show up as a widening gap specifically on the fraud class, with legitimate-transaction scoring staying stable, while an ordinary data-quality problem tends to degrade performance more broadly and often coincides with an identifiable upstream change (a schema change, a broken feature pipeline, a missing data source) rather than a gradual, fraud-specific shift.
Structured elaboration
- Signature of adversarial drift: recall on confirmed fraud cases declines gradually over weeks or months while precision and overall data quality metrics look normal; the newly-missed fraud, once confirmed, often shares a specific new pattern (a slightly different transaction structure, a newly-favored evasion technique) rather than being randomly distributed across all fraud types. This looks like the model's learned decision boundary is being specifically and gradually outmaneuvered.
- Signature of an ordinary data-quality problem: performance degradation tends to be broader (affecting both fraud and legitimate scoring, or showing up as missing/null feature values rather than a shift in the values themselves), and usually coincides with a specific, identifiable event, a schema change in an upstream table, a broken ETL job, a new data source integration, rather than a smooth trend over time.
- Diagnostic approach: check feature-level data-quality metrics (null rates, value-range sanity checks) FIRST, since ruling out an ordinary pipeline problem is cheaper and faster than a deep adversarial-pattern investigation; if data quality checks pass clean, look specifically at the confirmed-fraud subset's feature distributions over time (not the whole population) for a fraud-specific drift signature, which is the more diagnostic signal for genuine adversarial adaptation.
- What to do about genuine adversarial drift: once confirmed, retrain on the most recent confirmed fraud examples specifically (rather than diluting them across a much larger historical dataset), consider whether a new feature is needed to capture the newly-observed evasion pattern directly, and treat this as an ongoing, recurring need rather than a one-time fix, since an adaptive adversary will likely shift again.
Trade-offs and pitfalls
It's tempting to jump straight to "the fraudsters have adapted" whenever performance degrades, since it's a more interesting explanation, but a mundane data-quality problem is often the actual, cheaper-to-fix cause; always rule out the boring explanation first. Conversely, don't dismiss a real adversarial shift as "normal model decay" and simply schedule a routine retrain without first understanding what specifically changed, since a routine retrain on stale features won't fix a gap the model's feature set fundamentally can't see.
Implement a function precision_at_k(y_true, y_score, k) that returns the precision among the top-k highest-scored cases. Explain why this metric maps naturally onto a fraud review queue that can only investigate a fixed number of cases per day.
Sample Answer
Direct answer
Sort all cases by predicted score, take the top k, and report the fraction of those top k that are actually true positives; this metric maps naturally onto a fraud review queue because a reviewer team with a fixed daily capacity effectively works exactly this way, they review the top-scored k cases each day, so precision at k directly measures how much of their limited attention is being well spent, rather than measuring performance at some abstract threshold the team may never actually operate at.
Structured elaboration and worked example (executed)
from typing import List
def precision_at_k(y_true: List[int], y_score: List[float], k: int) -> float:
assert len(y_true) == len(y_score)
assert 0 < k <= len(y_true)
order = sorted(range(len(y_score)), key=lambda i: y_score[i], reverse=True)
top_k = order[:k]
hits = sum(y_true[i] for i in top_k)
return hits / k
Executed on a small labeled example with 3 true positives out of 10 cases:
precision_at_k(k=1) = 1.0000
precision_at_k(k=3) = 1.0000
precision_at_k(k=5) = 0.6000
precision_at_k(k=10) = 0.3000
The top 3 scored cases (indices with scores 0.95, 0.9, and 0.85) were all 3 of the true fraud cases in this example, giving precision@3 of exactly 1.0. Expanding to the top 5 pulled in 2 more legitimate cases, dropping precision to 0.6, and at k=10 (the full set), precision necessarily converges to the overall base rate of positives, 3/10 = 0.3, which is a useful sanity check on the implementation: precision@k at k equal to the full dataset size must always equal the overall positive rate.
Complexity and edge cases
Sorting dominates the runtime at O(n log n) for n cases; a review-queue system reusing this same ranking every day at scale would typically maintain the scores in a pre-sorted or partially-sorted structure rather than re-sorting from scratch each time. Edge cases worth handling explicitly: k must be validated to be strictly positive and no larger than the number of cases available (both asserted above), and ties in score at the boundary of the top k need a deterministic tie-breaking rule (for example, sorting ties by transaction amount or timestamp) so the metric doesn't silently depend on an unstable sort order.
Trade-offs and pitfalls
Precision@k tells you nothing about recall, a model can have perfect precision@k while still missing the majority of total fraud that falls outside the queue's daily capacity, so it should always be reported alongside a recall or PR-AUC figure, not as a standalone success metric on its own.
What is model calibration, and why does it matter for a fraud risk score that is used to prioritize which cases a human reviews first? Describe one concrete check you would run in production to confirm the model stays calibrated.
Sample Answer
Direct answer
Model calibration means a predicted probability actually reflects the true likelihood of the event: among all cases the model scores at 0.8, roughly 80 percent should genuinely be fraud. This matters for review prioritization because a reviewer relies on the score to decide which cases deserve attention first, and an uncalibrated score can rank cases correctly relative to each other while still being systematically wrong in absolute terms, misleading anyone who reads the number at face value.
Structured elaboration
- Why ranking alone isn't enough: many models (tree ensembles especially) produce scores that rank cases in the right order but are not well-calibrated in absolute terms. Bagged and boosted tree ensembles specifically tend to compress scores toward the middle of the range rather than confidently near 0 or 1, because averaging over many trees washes out extreme confidence even when the true underlying risk is much higher or lower. A reviewer who reads a 0.6 score as only moderately concerning, when the true fraud rate among cases scored around 0.6 is actually closer to 90 percent, will underestimate urgency for a case that should be reviewed first.
- Why it matters more when combining signals: if a fraud score feeds into a downstream decision that combines it with a dollar-cost calculation (like the expected-cost threshold framing used elsewhere on this topic), an uncalibrated score silently distorts that calculation, even if the underlying ranking of cases is fine.
- A concrete production check: bucket recent scored transactions into score ranges (for example 0.0 to 0.1, 0.1 to 0.2, and so on), and for each bucket compare the average predicted score to the actual confirmed-fraud rate within that bucket once labels have had time to arrive. A well-calibrated model shows these two numbers tracking closely across buckets; a systematic gap (for example, the 0.8 to 0.9 bucket's actual fraud rate running at 0.5) is a clear, actionable calibration failure.
Trade-offs and pitfalls
Calibration checks need enough confirmed labels per bucket to be statistically meaningful, which is a real constraint on a rare-event problem: a bucket with only a handful of confirmed outcomes gives a noisy estimate of the true rate. It's also worth remembering that calibration and discrimination (how well the model separates fraud from legitimate cases at all) are different properties: a model can be well-calibrated but weak at discrimination, or the reverse, and fixing one does not automatically fix the other.
How would you distinguish a legitimate traffic or activity spike from a bot-driven or coordinated-attack spike, and separately, how would you design a detector for ad click-fraud at scale? Discuss the features and signals you would use for each, and how you would avoid blocking real users.
Sample Answer
Direct answer
Distinguish a legitimate traffic spike from a bot or coordinated-attack spike by looking at the DIVERSITY and BEHAVIORAL REALISM of the traffic, real spikes come from many distinct devices, IPs, and session patterns behaving the way genuine users actually behave, while bot-driven spikes concentrate on a narrow set of sources with unnaturally uniform or mechanically-repeated behavior; for ad click-fraud specifically, apply the same diversity-and-realism lens to click patterns, timing, and post-click engagement, since a real user who clicks an ad usually does something afterward, and a bot usually doesn't.
Structured elaboration
- Features for distinguishing legitimate vs bot traffic spikes: source diversity (number of distinct IPs, user agents, device fingerprints behind the spike, a real spike from genuine interest is far more diverse than a scripted one), session realism (do sessions show human-like variability in timing, scroll depth, or navigation, or an unnaturally uniform pattern), and referral/context plausibility (does the spike align with an identifiable, real external event, like a marketing campaign or a news mention, versus arriving with no identifiable cause).
- Ad click-fraud detection features: click timing patterns (clicks arriving at suspiciously regular intervals, or in impossibly fast succession from the same source), post-click engagement (a real user who clicks an ad usually spends at least some time on the landing page or takes some further action; a bot typically bounces instantly with zero engagement), and concentration (a small number of sources responsible for a disproportionate share of clicks on a specific ad or campaign).
- Model choice: a combination of rule-based thresholds for the most obvious cases (near-zero post-click engagement, extreme click concentration from one source) and a supervised or unsupervised anomaly model for subtler cases, trained on labeled examples of confirmed bot/click-fraud traffic where available, mirrors the broader rules-plus-ML pattern used elsewhere on this topic.
- Avoiding false positives against real users: a genuinely viral or campaign-driven spike can look superficially similar to a coordinated attack in raw volume terms, so weight the DIVERSITY and BEHAVIORAL signals described above more heavily than volume alone, and where possible, cross-reference against a known, legitimate external cause (an active marketing campaign, a press mention) before concluding a spike is illegitimate.
Trade-offs and pitfalls
Sophisticated bot operators increasingly mimic human-like session behavior specifically to evade diversity and realism checks, so no single feature family is a permanent solution; the realistic goal, as with adversarial evasion generally, is raising the cost and sophistication required to evade detection, not eliminating bot traffic once and for all. It's also worth being conservative before blocking real users outright; a lighter-touch first response (additional verification, or excluding suspicious traffic from ad billing without blocking the user experience) is often more appropriate than an immediate hard block.
Unlock Full Question Bank
Get access to all 41 Anomaly and Fraud Detection interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.