Sub topic 16
Fraud and risk checks
This chapter assumes you have read the earlier chapters on the payment lifecycle, idempotency, and the payment state machine. You should be comfortable reading short Python snippets and thinking about latency in a request path.
Why risk checks belong in the payment path
A payment system can be correct about money and still lose it. Fraud losses come from stolen cards, account takeover, and "friendly fraud", where a real cardholder disputes a purchase they made. Each of these ends in a chargeback, which costs the merchant the sale, a dispute fee, and sometimes the right to accept cards.
Risk checks decide whether to let a payment continue. They sit in front of the authorization step and use data your system already holds: the token, amount, device, IP address, and the merchant's history. The card network and issuer run their own fraud checks as well. Yours add context only you have, such as how long the customer has had an account.
The working model: signals, rules, scores, decisions
A risk engine turns signals into one of a small set of decisions. Keep these four parts separate.
- Signals are facts about the request. Examples are the card token, IP address, billing country, device fingerprint, amount, and email age.
- Features are signals aggregated over time, such as "number of attempts with this card token in the last ten minutes". These are called velocity counts.
- Rules and models turn features into a score or a hard verdict. Rules are explicit and auditable. A machine-learning model can add a probability but is harder to explain.
- Decisions are what the payment flow acts on. The common set is allow, review, challenge, and decline.
| Decision | Meaning | Effect on the payment |
|---|---|---|
| Allow | Risk is low | Continue to authorization |
| Challenge | Risk is moderate | Ask for extra proof, such as 3-D Secure, then continue |
| Review | Risk is unclear | Hold the payment for a human or a slower check |
| Decline | Risk is high | Move the payment to a failed state without calling the PSP |
Use the PCI scope you chose in the previous chapter here too. Risk code should work with tokens and derived features, not raw card numbers. Hashing the token or using the PSP's card fingerprint gives you a stable key for counting without widening your compliance scope.
Where the check runs
Run hard rules first. A blocklist lookup is cheap and needs no model. Score only the requests that pass. Every branch writes an audit record, because you will need to explain later why a payment was declined.
A small rule-based scorer
The code below keeps a sliding-window counter per card token and combines three rules into a score. It runs as written with Python 3.
import time
from collections import defaultdict, deque
BLOCKLIST = {"tok_stolen_001"}
class VelocityCounter:
"""Counts events per key inside a sliding time window."""
def __init__(self, window_seconds):
self.window = window_seconds
self.events = defaultdict(deque)
def record(self, key, now=None):
now = time.time() if now is None else now
q = self.events[key]
q.append(now)
while q and q[0] <= now - self.window:
q.popleft()
return len(q)
def decide(payment, attempts_in_window):
if payment["card_token"] in BLOCKLIST:
return "decline", 100, ["blocklist"]
score, reasons = 0, []
if attempts_in_window > 5:
score += 40
reasons.append("card_velocity")
if payment["amount_minor"] > 100_000:
score += 20
reasons.append("large_amount")
if payment["billing_country"] != payment["ip_country"]:
score += 25
reasons.append("country_mismatch")
if score >= 80:
return "decline", score, reasons
if score >= 40:
return "review", score, reasons
return "allow", score, reasons
counter = VelocityCounter(window_seconds=600)
payment = {
"card_token": "tok_abc",
"amount_minor": 150_000,
"billing_country": "US",
"ip_country": "RO",
}
for _ in range(6):
attempts = counter.record(payment["card_token"])
print(decide(payment, attempts))This prints ('decline', 85, ['card_velocity', 'large_amount', 'country_mismatch']). The reasons list matters as much as the verdict. It feeds the audit log, support tooling, and your tuning.
Design decisions that cause trouble
Fail open or fail closed
If the risk service times out, you must choose. Failing closed declines the payment and protects against fraud, but it turns a risk outage into a payment outage. Failing open keeps revenue flowing but lets fraud through. A common compromise is to fail open for small amounts and established customers, and fail closed for large amounts or new accounts. Give the risk call a short deadline, and record every fallback so you can measure it.
Idempotency and counters
Retries are expected in a payment system, so a retry must not count as a second attempt. If your velocity counter increments on every request, a client that retries a timed-out call can trip its own velocity rule. Key the counter update by the idempotency key, so a replay returns the stored decision instead of re-scoring. This also keeps the decision stable. A payment declined at 10:00 should not be approved on retry at 10:01 because the score drifted.
Record the decision before acting on it
Persist the decision and its reasons with the payment before you call the PSP. Then the state machine can move from created to failed on a decline with the cause attached. If the process crashes after scoring, the stored decision is reused and the work is not repeated.
Cost of false positives
Declining a good customer loses a sale and may lose the customer. Measure both error types. A rule set that blocks every fraudulent payment but also declines 5% of legitimate ones is usually worse than a looser one. Track the approval rate, the chargeback rate, and the review queue size together.
Common errors
- Using raw card numbers as counter keys. This pulls risk storage into PCI scope. Use a token or the PSP's fingerprint.
- Counting only successes. Card testing attacks make many small attempts, and most of them fail. Count attempts, not approvals.
- Hard-coded thresholds with no history. Store the score, the reasons, and the later outcome (chargeback or not). Without that history you cannot tune rules.
- Scoring after authorization. Money may already be held. Check before the PSP call, and keep a second, slower check for asynchronous signals.
- No path for a late chargeback. Chargebacks arrive weeks later. Feed them back as labels, and add the card or device to the blocklist if it fits your policy.
Rules versus models
Rules are fast to ship, easy to explain to a regulator, and simple to switch off when they misfire. Models find patterns that rules miss, but they need labeled data, monitoring for drift, and a way to explain a decline. A practical path starts with rules and velocity checks. Add a model as one more signal in the score once you have enough labeled history. Keep the hard rules and the decision thresholds outside the model, so operators can change them without a retraining cycle.
Exercise
A client sends a payment, the risk service scores it 45 (review), and the response times out before the client sees it. The client retries with the same idempotency key. Describe how your design should handle the retry, and name one problem that appears if you skip this design.
Show answer
Look up the payment by merchant and idempotency key and return the stored decision (review, with its reasons) without re-scoring and without incrementing the velocity counter. If you skip this, the retry counts as a new attempt, so the client can trip its own velocity rule. The score can also drift between attempts, so the same payment gets a different decision on retry.