Payment fraud detection is deciding, inside the checkout request, whether to approve a payment, challenge it, send it to a person, or block it. You do it with three tools that are better together than apart:
- Rules are conditions you write: "block if the CVV failed", "review orders over $1,000 from a new account". Fast, explainable, and only as smart as the last fraud you saw.
- A fraud score is a number that says how risky a payment looks, computed from many signals at once. Stripe Radar, for example, gives each card payment scores from 0 to 99 for the chance of a fraudulent dispute and of an early fraud warning (Stripe). You don't act on the score directly; you set thresholds on it.
- Machine learning is how most scores get made: a model trained on labeled outcomes (this payment became a fraud dispute, that one didn't) that weighs signals no human would combine by hand.
The question is never "rules or ML". It's which decisions you hand to each.
Rules vs scores vs ML
| Rules | Fraud score (bought) | Your own ML model | |
|---|---|---|---|
| What it is | Conditions you write | A vendor's model output, plus thresholds you set | A model trained on your labeled payments |
| Good at | Known patterns, business policy, emergencies | Fraud seen across many merchants, from day one | Fraud specific to your product |
| Fails at | Anything new. Fraudsters learn the threshold and stay under it | Explaining itself; patterns unique to you | Cold starts. It needs labeled fraud you don't have yet |
| Cost of a mistake | Visible: you can read the rule that blocked a customer | Invisible unless you track false positives | Silent drift as fraud changes |
| Who owns it | Whoever writes rules, forever | The vendor, mostly | A data team |
For most SaaS and ecommerce businesses the right order is: your processor's score first, a handful of rules on top for things the score can't know (your refund policy, your trial abuse, your high-value SKUs), and your own model only once you have enough labeled fraud to train one and someone to retrain it. Chapter 19's ML material, excerpted below, is what that last step involves.
What goes into a fraud score
The signals are roughly the same whoever computes them:
| Signal | What it catches |
|---|---|
| Velocity | Many cards, attempts or declines from one email, IP, device or customer |
| Card checks | Failed CVV, failed AVS, prepaid or newly seen cards (AVS and CVV codes) |
| Geography | Card country, IP country and billing country that don't agree |
| Device and network | A device seen on past fraud, anonymous proxies, hosting-provider IPs |
| Behavior | Checkout completed faster than a person types, no browsing before buying |
| History | Account age, past disputes, deviation from this customer's usual amount |
The decision comes from thresholds, and they belong to you even when the score doesn't. A typical ladder: approve below one line, ask for 3D Secure in a middle band, send a narrow band above that to manual review, block the top. The thresholds have asymmetric costs. Blocking a good customer loses the sale and the customer; approving a fraudster costs the sale plus the chargeback fee. Tune toward whichever is costing you more, and measure both.
Velocity checks
A velocity check counts how often something happened in a time window and acts when the count is too high. It's the cheapest fraud signal you can build and the one that catches card testing, where a script runs hundreds of cards through one checkout.
Count distinct things, not just attempts:
- Cards per IP, per email, per customer, per device. A real person has one or two cards. A tester has hundreds.
- Declines per IP or card in the last hour. Testers decline a lot; customers retry once or twice.
- Accounts created per IP per day. Testers rotate customers before they rotate infrastructure.
- Amount per card per day. Catches a stolen card being drained after the test charge worked.
Here's a sliding-window counter on Redis that counts distinct members, so the same card retried ten times counts once:
import time
import redis
r = redis.Redis()
def velocity(key: str, member: str, window_seconds: int) -> int:
# Distinct members seen under key in the window, this one included
now = time.time()
zkey = f"vel:{key}:{window_seconds}"
pipe = r.pipeline()
pipe.zadd(zkey, {member: now})
pipe.zremrangebyscore(zkey, 0, now - window_seconds)
pipe.zcard(zkey)
pipe.expire(zkey, window_seconds)
_, _, count, _ = pipe.execute()
return count
def velocity_signals(ip: str, email: str, card_fingerprint: str) -> list[str]:
reasons = []
if velocity(f"ip:{ip}:cards", card_fingerprint, 3600) > 3:
reasons.append("more than 3 cards from this IP in an hour")
if velocity(f"email:{email}:cards", card_fingerprint, 86400) > 2:
reasons.append("more than 2 cards on this email in a day")
return reasons
Key on the card fingerprint your processor gives you (card.fingerprint on a Stripe PaymentMethod), never the card number. The thresholds above are a starting point, not a recommendation; set yours from a week of your own traffic, then check what they would have blocked.
On Stripe you may not need to build this. Radar's rule language has velocity attributes such as card_count_for_ip_address_hourly, card_count_for_email_daily and declined_charges_per_ip_address_hourly, and their counts exclude the payment being processed (Stripe, attributes). Note the windows are bucketed: "hourly" can mean up to 3,900 seconds. Stripe Radar rules covers which ones are worth writing.
Where people go wrong
- Blocking on one signal. A VPN, a foreign card or a failed AVS check alone describes plenty of good customers. Fraud trips several signals at once.
- Measuring only fraud. If you don't track false positives, every tuning change looks like a win. Count blocked payments that came back and succeeded, and support tickets about declines.
- Labels from chargebacks only. Fraud disputes arrive weeks late. Early fraud warnings and refunds-for-fraud are faster labels.
- No feedback loop. Rules written during an attack stay forever. Review them quarterly and delete the ones that no longer match anything.
What you're detecting in the first place: card-not-present, account takeover, synthetic identities and friendly fraud. From chapter 19.
Common Fraud Types
Card Not Present (CNP) fraud is what you'll see most online: stolen card details run through your checkout, account takeovers using credentials harvested from breaches, and friendly fraud where the legitimate cardholder disputes a valid charge after receiving the goods.
Card present fraud still exists despite EMV - counterfeit cards built from stolen magnetic stripe data, lost or stolen cards used before they're reported, and skimming devices on terminals or ATMs capturing track data.
Account fraud targets the identity layer rather than the card: identity theft using stolen personal information, synthetic identity fraud combining real and fake data into a believable new persona, and business email compromise (BEC) targeting B2B payments through impersonation.
Emerging fraud is where things get interesting - AI-generated identities and deepfakes defeating video KYC, cryptocurrency mixers laundering proceeds, and buy now, pay later (BNPL) abuse exploiting weaker underwriting.
The model step: the features that matter, why a supervised and an unsupervised model run side by side, and how the ensemble decides. From chapter 19.
Machine Learning Fraud Models
Machine learning fraud models catch patterns that rules can't express, but only when you train and maintain them well. Treat any accuracy figure, including a vendor's, as meaningless until you've measured it on your own labelled data, because fraud is rare enough that a model that approves everything is "99% accurate". The non-negotiables: at least 10,000 labeled transactions for training, a 1:10 to 1:20 fraud-to-legitimate ratio, monthly retraining (or sooner when patterns shift), and an ensemble such as Random Forest plus Isolation Forest so known fraud and novel fraud both get caught. Inference has to finish in 50-100ms or your customers will feel it at checkout. Feature engineering matters more than model choice: velocity metrics, deviation from the customer's average amount, device fingerprint changes, geographic impossibilities, and behavioral timing all carry more signal than raw transaction data. Skip retraining and the model decays as fraudsters adapt, so track precision and recall monthly and retrain when they slip.
Implementation: src/examples/19-fraud/ml_fraud_detector.py
Key Components: - MLFraudDetector: Dual-model ensemble (Random Forest + Isolation Forest) - Feature Engineering: 15+ behavioral and contextual signals - Explainable AI: Feature importance and contribution analysis
ML Fraud Detection Pattern (Conceptual):
# Ensemble ML approach (conceptual)
def predict_fraud_probability(transaction_features):
# Extract engineered features
features = {
'amount': transaction.amount,
'velocity_1h': count_transactions(email, hours=1),
'velocity_24h': count_transactions(email, hours=24),
'amount_deviation': deviation_from_average(customer),
'device_risk_score': device_reputation(fingerprint),
'country_risk_score': country_risk(ip_country),
'hour_of_day': transaction.hour,
'customer_age_days': days_since_signup(customer)
}
# Random Forest (supervised learning)
rf_probability = random_forest.predict_proba(features)[0, 1]
# Isolation Forest (unsupervised anomaly detection)
anomaly_score = isolation_forest.decision_function(features)[0]
anomaly_probability = convert_to_probability(anomaly_score)
# Ensemble prediction (weighted average)
fraud_probability = (
rf_probability * 0.70 + # 70% weight
anomaly_probability * 0.30 # 30% weight
)
return {
'fraud_probability': fraud_probability,
'random_forest': rf_probability,
'anomaly_detection': anomaly_probability,
'top_features': get_feature_importance(features),
'decision': 'BLOCK' if fraud_probability > 0.85 else
'REVIEW' if fraud_probability > 0.50 else 'APPROVE'
}
The complete implementation includes model training, incremental learning, cross-validation, and explainable AI for regulatory compliance. See src/examples/19-fraud/README.md.
Why ML beats pure rules:
Rule-based systems only catch patterns you've already seen. ML learns subtle patterns from millions of transactions that no human would notice. The MLFraudDetector runs two complementary models. Random Forest is supervised - it learns from labeled fraud and legitimate examples, building decision trees that ask things like "amount over $500, new device, 3 AM" and combining 100 trees into predictions that don't overfit. Isolation Forest is unsupervised - it's trained only on legitimate transactions and flags anything that doesn't fit the normal pattern, which is how you catch novel fraud techniques you've never seen before.
Random Forest catches known fraud with high precision; Isolation Forest catches the new stuff. The ensemble weighting (70% RF, 30% IF) balances precision against discovery.
The extract_ml_features function turns raw transaction data into signals the model can use. Temporal features (hour_of_day, day_of_week, customer_age_days) capture that fraudsters work off-hours and new accounts are riskier than established ones. Velocity features (velocity_1h, velocity_24h) let the model find subtle patterns that fixed thresholds miss. Behavioral features include amount_deviation (how far off is this purchase from the customer's norm?), device_risk_score, and email_domain_risk (disposable providers carry more risk). Geographic features like country_risk_score need careful handling to avoid discrimination, but the signal is real.
The update_model method retrains on new fraud cases so the model adapts as fraudsters do. The explain_prediction method shows exactly which features drove the score - essential for explainable-AI compliance, customer service, model debugging, and stakeholder trust.
A couple of mechanical details that matter. StandardScaler keeps features with different scales (dollars vs. velocity counts) from dominating each other. class_weight='balanced' prevents the model from just predicting "not fraud" for everything - fraud is typically under 1% of transactions, and without rebalancing the model learns the trivial answer.
A traditional rule might say "block if amount > $1000 AND new device." The fraudster uses $999 on an aged device and walks through. ML learns non-linear boundaries that adapt automatically.
The same idea from the ML side: three engines in parallel, a 0-1 risk score, and the threshold warning every team learns late. From chapter 35.
Traditional fraud rules are brittle: "Block transactions over $5,000 from new accounts." Fraudsters learn the rule and stay just under the limit. Machine learning takes a different approach: instead of hard rules, models learn complex patterns that are nearly impossible to game.
Modern risk assessment runs three engines in parallel.
Fraud detection models use XGBoost and neural networks across 100+ features per transaction: velocity (frequency versus the customer's baseline), geolocation (impossible-travel detection), device fingerprinting, and amount patterns. Their edge over rule-based systems is fewer false positives at the same catch rate, which you have to measure on your own traffic; published accuracy figures mostly reflect how rare fraud is.
Anomaly detection with isolation forests and autoencoders catches transactions that "don't look right" even when they don't match known fraud. The autoencoder learns normal patterns, then flags high reconstruction error - unusual in ways it can't explain.
Behavioral analysis tracks biometrics the customer doesn't see: typing rhythm, navigation patterns, time-of-day habits. When the behavior suddenly shifts - new device, odd hour, new recipient - the score climbs even if individual features look clean.
The composite risk score (0-1) determines action: approve instantly (<0.1), step-up authentication (0.1-0.5), manual review (0.5-0.8), or block (>0.8). False positive rates stay below 2% while catching fraud that rule-based systems miss entirely.
Tune your risk score thresholds carefully - they have asymmetric costs. A false positive (blocking a legitimate customer) costs 2-5x the transaction value in lost lifetime value. A false negative (approving fraud) costs the transaction amount plus $15-$100 in chargeback fees. Start conservative (a lower block threshold), measure your false positive rate, and adjust from there. A 0.05 threshold adjustment can shift millions of dollars between approved and blocked.
And why the score isn't coming from an LLM any time soon. From the same chapter.
Where Classical ML Still Wins
LLMs are the wrong tool for several payments problems, and they'll stay the wrong tool for a while:
- Real-time fraud scoring. A classical model runs in under 10ms at a marginal cost of around $0.0001 per call. An LLM call typically takes 500-2000ms and costs $0.01-0.05. At 1,000 transactions per second, the cost gap alone is the difference between a P&L item and a rounding error.
- Tabular structured data. Gradient-boosted trees beat LLMs on most tabular benchmarks. If your input is rows and columns, don't reach for a transformer.
- Regulated decisions with explainability requirements. Credit scoring, AML decisions, and adverse action notices need deterministic, auditable reasoning. Stochastic next-token prediction isn't what regulators want to read in your model documentation.
Questions
What is a fraud score?
A number that estimates how likely a payment is to be fraudulent, computed from signals such as velocity, card checks, geography, device and account history. Stripe Radar, for example, scores payments from 0 to 99. Merchants set thresholds on the score to approve, challenge, review or block.
What are velocity checks in fraud detection?
Counts of how often something happens in a time window, such as distinct cards used from one IP address in an hour, or declines on one email in a day. A count above the threshold adds risk or blocks the payment. They are the main defense against card testing.
Is rule-based or machine learning fraud detection better?
Neither alone. Rules are fast, explainable and good for known patterns and business policy, but fraudsters learn the thresholds. Machine learning finds patterns no one wrote down but needs labeled fraud data and retraining. Most businesses use a processor's ML score with a small set of rules on top.
How do I detect payment fraud as a small business?
Start with your processor's built-in fraud score and checks, block failed CVV checks, add velocity limits on cards per IP and per email, request 3D Secure for risky payments, and track both fraud disputes and false declines so you can tune the thresholds.
What signals are used to detect payment fraud?
Velocity of cards, attempts and declines; CVV and AVS results; mismatches between card, IP and billing country; device and network reputation; behavior during checkout; and account history such as age and past disputes.