Transaction Fraud Pipeline with Behavioral Rules
Data Structure DesignAuto-graded · 18 test casesLast updated
Build a stateful stream processor that validates payment records, detects velocity and spending anomalies, and produces fixed-width audit logs.
Problem
Build a fraud detection system that processes a stream of payment records, applies validation and risk checks, and outputs a formatted audit trail.
Each input string represents one transaction in CSV format with exactly five comma-separated fields:
transaction_id,user_id,amount_cents,currency,timestamp_iso
Rule Evaluation
Check each transaction against the following rules in the order listed. When multiple rules are violated, report only the first matching rule:
-
INVALID_FORMAT: The record fails structural validation if any of these conditions hold:- The record does not contain exactly 5 comma-separated fields
amount_centsis not a positive integer greater than zero (must match regex[0-9]+and convert to a value> 0)timestamp_isodoes not conform to strict ISO-8601 UTC formatYYYY-MM-DDTHH:MM:SSZor represents an impossible date (e.g., February 30)
-
UNSUPPORTED_CURRENCY: The currency field is not exactly one ofUSD,EUR, orGBP(case-sensitive). -
HIGH_VELOCITY: The user already has 2 or more approved transactions within the past 60 seconds, inclusive. Specifically, if the current transaction occurs at timet, count how many previously approved transactions for the same user occurred at timeprev_twheret - 60 <= prev_t <= t. -
AMOUNT_SPIKE: The transaction amount exceeds three times the user's historical average of all previously approved transactions. This check only applies when the user has at least 2 prior approved transactions.
If no rule is violated, mark the transaction APPROVED with reason OK, and update the user's approval history (timestamp and amount).
Transactions appear in strictly increasing order by timestamp.
Output Format
Return a list of fixed-width strings, one per input record. Each line contains three columns separated by exactly two spaces:
- TX_ID: Left-aligned, width 10 (truncate if longer)
- STATUS: Left-aligned, width 8 (
APPROVEDorDECLINED) - REASON: Left-aligned, width 20 (
OKfor approved, otherwise the rule name)
Constraints
- 1 ≤ number of records ≤ 10,000
transaction_idanduser_id: alphanumeric strings, up to 32 charactersamount_cents: integer up to 10⁹- Transactions are sorted in strictly ascending order by
timestamp_iso
Examples
Example 1
Input: process_transaction_stream(['tx_01,user_a,1000,USD,2023-01-01T00:00:00Z', 'tx_02,user_a,1200,USD,2023-01-01T00:00:15Z', 'tx_03,user_a,1100,USD,2023-01-01T00:00:30Z', 'tx_04,user_a,5000,USD,2023-01-01T00:02:00Z'])
Output: ['tx_01 APPROVED OK ', 'tx_02 APPROVED OK ', 'tx_03 DECLINED HIGH_VELOCITY ', 'tx_04 DECLINED AMOUNT_SPIKE ']
Hints
Hint 1
Maintain per-user state: a sliding window of approved timestamps and a running sum/count for the average. Declined transactions never contribute to either.
Hint 2
Use a deque for the velocity window. Since timestamps arrive in order, you can pop expired entries from the left without rescanning.
Hint 3
To avoid floating-point precision issues in the spike check, compare integers: amount * count > 3 * sum.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem requires stateful stream processing with rule-based validation. The key insight is to maintain just enough per-user state to evaluate the rules efficiently without rescanning history.
Core Strategy
Process records sequentially. For each user, track:
- A deque of approved transaction timestamps for the 60-second velocity window
- A running sum and count of all approved transaction amounts for the average calculation
Evaluate rules in the exact order specified, stopping at the first violation. Only approved transactions update user state—declined transactions are ignored.
Rule Implementation
1. INVALID_FORMAT
- Split on commas and verify exactly 5 fields
- Validate
amount_centswith a strict regex[0-9]+(rejects decimals, signs, whitespace) and ensure the parsed integer is positive - Validate timestamp format with regex
[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z, then parse withstrptimeto catch impossible dates - Convert to epoch seconds for efficient numeric comparisons
2. UNSUPPORTED_CURRENCY
- Simple set membership test against
{"USD", "EUR", "GBP"}
3. HIGH_VELOCITY
- Prune timestamps older than
current_time - 60from the left of the deque (they're permanently expired since timestamps arrive in order) - Count remaining timestamps in the window
- Decline if count ≥ 2
4. AMOUNT_SPIKE
- Only applies when the user has 2+ prior approvals
- Compare using integer arithmetic:
amount * count > 3 * sumavoids floating-point issues
If all checks pass: append timestamp to the window, add amount to sum, increment count, and output APPROVED.
Why It Works
- Correctness: Rules are checked in priority order with early exit, ensuring only the highest-priority violation is reported
- Efficiency: The deque acts as a sliding window—each timestamp is added once and removed once, giving amortized O(1) per transaction
- Order guarantee: Since inputs arrive sorted by timestamp, we can safely discard old timestamps without maintaining a sorted structure
Complexity
- Time: O(N) where N is the number of records. Each record is processed once, and deque operations are amortized O(1)
- Space: O(U) where U is the number of unique users. Each user's deque holds at most 2 timestamps (a third would trigger HIGH_VELOCITY). Output adds O(N).
Implementation
import calendar
import re
from collections import defaultdict, deque
from datetime import datetime
from typing import List
def process_transaction_stream(records: List[str]) -> List[str]:
# Validation patterns
amount_regex = re.compile(r"[0-9]+")
timestamp_regex = re.compile(r"[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z")
valid_currencies = {"USD", "EUR", "GBP"}
velocity_window_sec = 60
# Per-user state
user_timestamps = defaultdict(deque) # deque of epoch seconds
user_total_amount = defaultdict(int)
user_approved_count = defaultdict(int)
results = []
def parse_timestamp(ts_str):
"""Parse strict ISO timestamp, return epoch seconds or None."""
if not timestamp_regex.fullmatch(ts_str):
return None
try:
dt = datetime.strptime(ts_str, "%Y-%m-%dT%H:%M:%SZ")
return calendar.timegm(dt.timetuple())
except ValueError:
return None
def format_output(tx_id, status, reason):
"""Format a single audit line."""
return f"{tx_id[:10]:<10} {status:<8} {reason:<20}"
for record in records:
parts = record.split(",")
tx_id = parts[0] if parts else ""
# Rule 1: INVALID_FORMAT
if len(parts) != 5:
results.append(format_output(tx_id, "DECLINED", "INVALID_FORMAT"))
continue
tx_id, user_id, amount_str, currency, timestamp_str = parts
if not amount_regex.fullmatch(amount_str):
results.append(format_output(tx_id, "DECLINED", "INVALID_FORMAT"))
continue
amount = int(amount_str)
if amount <= 0:
results.append(format_output(tx_id, "DECLINED", "INVALID_FORMAT"))
continue
epoch_time = parse_timestamp(timestamp_str)
if epoch_time is None:
results.append(format_output(tx_id, "DECLINED", "INVALID_FORMAT"))
continue
# Rule 2: UNSUPPORTED_CURRENCY
if currency not in valid_currencies:
results.append(format_output(tx_id, "DECLINED", "UNSUPPORTED_CURRENCY"))
continue
# Rule 3: HIGH_VELOCITY
timestamps = user_timestamps[user_id]
cutoff = epoch_time - velocity_window_sec
# Prune expired timestamps from the window
while timestamps and timestamps[0] < cutoff:
timestamps.popleft()
if len(timestamps) >= 2:
results.append(format_output(tx_id, "DECLINED", "HIGH_VELOCITY"))
continue
# Rule 4: AMOUNT_SPIKE
count = user_approved_count[user_id]
if count >= 2:
total = user_total_amount[user_id]
# Check: amount > 3 * (total / count)
# Integer-safe: amount * count > 3 * total
if amount * count > 3 * total:
results.append(format_output(tx_id, "DECLINED", "AMOUNT_SPIKE"))
continue
# APPROVED: update user state
timestamps.append(epoch_time)
user_total_amount[user_id] += amount
user_approved_count[user_id] += 1
results.append(format_output(tx_id, "APPROVED", "OK"))
return results