Transactions per minute
Oct 6, 5-minute average
Project 10 · Real-time ML
Every card authorization is published to Kafka. A Spark Structured Streaming job keeps rolling features for each card, merchant and device, such as spend in the last ten minutes and how many merchants a card has used, and pushes them to a Feast feature store backed by Redis. The scoring service reads those features in a few milliseconds, scores the transaction and answers before the payment is approved. High scores become alerts for analysts, and their decisions flow back as labels to measure precision and recall every day.
Oct 6, 5-minute average
Sent to review or declined
Transactions by score, log scale
Oct 6
Daily, from analyst decisions and chargebacks
Last 30 days, threshold 0.80
Score, the feature that contributed most, and the analyst's decision
Feast feature views and how old their online values are
From authorization to decision in about 46 ms at p95, with the same features online and in training.
01 · Authorize
Payment gateway
Each card authorization goes to Kafka with amount, merchant, device and location, keyed by card.
02 · Compute features
Spark Structured Streaming
Sliding windows per card, merchant and device: counts, sums, distinct merchants and velocity, updated every 5 seconds.
03 · Serve features
Feast + Redis
Streaming and daily batch features in one registry; online lookups take about 3 ms.
04 · Score
Model service
A gradient-boosted model scores each transaction with its features before the payment is approved.
05 · Act
Rules + review queue
0.90 and above declines, 0.80 to 0.90 goes to an analyst, below 0.80 approves.
06 · Learn
Labels + Grafana
Analyst decisions and chargebacks become labels; precision and recall are tracked daily and drive retraining.
One event, one feature view and one score record: the whole life of a decision.
payments.authorizationsKafka topic · Avro · keyed by cardtxn_idstringcard_idstringmerchant_id / mccstring / intamount_usddecimal(12,2)device_id / lat / lonstring / doubleevent_tstimestampcard_txn_rollingFeast feature view · Redis online · TTL 2 hcard_identitytxn_count_10m / txn_count_1hint64amount_sum_10mfloatdistinct_merchants_10mint64km_from_last_txnfloatevent_timestamptimestampfraud.scoresIceberg table · one row per decisiontxn_idstringscore / decisiondouble / stringapprove, review or declinemodel_versionstringfraud-v14featuresmap<string,double>label / labeled_atboolean / timestampThe streaming features, their Feast definitions, and the scoring service.
Spark Structured Streaming: ten-minute sliding windows per card, pushed to Feast every five seconds.
from feast import FeatureStore
from feast.data_source import PushMode
from pyspark.sql import functions as F
from pyspark.sql.avro.functions import from_avro
store = FeatureStore(repo_path="feature_repo")
SCHEMA = open("schemas/authorization.avsc").read()
txns = (
spark.readStream.format("kafka")
.option("kafka.bootstrap.servers", "kafka:9092")
.option("subscribe", "payments.authorizations")
.load()
.select(from_avro(F.expr("substring(value, 6, length(value) - 5)"), SCHEMA).alias("t"))
.select("t.*")
.withColumn("event_ts", F.expr("timestamp_millis(event_time_ms)"))
)
rolling = (
txns.withWatermark("event_ts", "2 minutes")
.groupBy(F.window("event_ts", "10 minutes", "1 minute"), "card_id")
.agg(
F.count("*").alias("txn_count_10m"),
F.sum("amount_usd").cast("float").alias("amount_sum_10m"),
F.approx_count_distinct("merchant_id").alias("distinct_merchants_10m"),
)
.select("card_id", F.col("window.end").alias("event_timestamp"),
"txn_count_10m", "amount_sum_10m", "distinct_merchants_10m")
)
def push_to_feast(batch, batch_id):
rows = batch.toPandas()
if rows.empty:
return
# Several windows per card can update in one batch; the newest one is what scoring needs.
latest = rows.sort_values("event_timestamp").drop_duplicates("card_id", keep="last")
store.push("card_txn_rolling_push", latest, to=PushMode.ONLINE_AND_OFFLINE)
(rolling.writeStream
.outputMode("update")
.foreachBatch(push_to_feast)
.trigger(processingTime="5 seconds")
.option("checkpointLocation", "s3://fraud-features/checkpoints/card_txn_rolling")
.start())
Feast definitions: the card entity, a push source fed by the stream, and the feature view the model reads.
from datetime import timedelta
from feast import Entity, FeatureView, Field, FileSource, PushSource
from feast.types import Float32, Int64
card = Entity(name="card", join_keys=["card_id"])
# Offline copy of the pushed features, for point-in-time correct training sets
card_rolling_offline = FileSource(
name="card_txn_rolling_offline",
path="s3://fraud-features/card_txn_rolling/",
timestamp_field="event_timestamp",
)
card_rolling_push = PushSource(name="card_txn_rolling_push", batch_source=card_rolling_offline)
card_txn_rolling = FeatureView(
name="card_txn_rolling",
entities=[card],
ttl=timedelta(hours=2),
schema=[
Field(name="txn_count_10m", dtype=Int64),
Field(name="amount_sum_10m", dtype=Float32),
Field(name="distinct_merchants_10m", dtype=Int64),
],
source=card_rolling_push,
online=True,
tags={"owner": "fraud-data", "freshness_sla": "5s"},
)
The scoring service: online features from Feast, a gradient-boosted model, and the decision thresholds.
import time
import xgboost as xgb
from fastapi import FastAPI
from feast import FeatureStore
from pydantic import BaseModel
store = FeatureStore(repo_path="feature_repo")
model = xgb.Booster(model_file="models/fraud-v14.json")
FEATURES = [
"card_txn_rolling:txn_count_10m",
"card_txn_rolling:amount_sum_10m",
"card_txn_rolling:distinct_merchants_10m",
"card_profile:amount_avg_30d",
"merchant_risk:chargeback_rate_90d",
"device_history:cards_seen_24h",
]
NAMES = [f.split(":")[1] for f in FEATURES]
class Authorization(BaseModel):
txn_id: str
card_id: str
merchant_id: str
device_id: str
amount_usd: float
km_from_last_txn: float
app = FastAPI()
@app.post("/score")
def score(txn: Authorization) -> dict:
started = time.perf_counter()
values = store.get_online_features(
features=FEATURES,
entity_rows=[{"card_id": txn.card_id, "merchant_id": txn.merchant_id, "device_id": txn.device_id}],
).to_dict()
row = [txn.amount_usd, txn.km_from_last_txn] + [values[name][0] or 0.0 for name in NAMES]
risk = float(model.predict(xgb.DMatrix([row], feature_names=["amount_usd", "km_from_last_txn", *NAMES]))[0])
decision = "decline" if risk >= 0.90 else "review" if risk >= 0.80 else "approve"
return {
"txn_id": txn.txn_id,
"score": round(risk, 4),
"decision": decision,
"model_version": "fraud-v14",
"latency_ms": round((time.perf_counter() - started) * 1000, 1),
}
At 03:05 a bot started testing stolen card numbers with $1 purchases at one online store. Velocity features flagged the pattern within minutes, the flag rate peaked at 1.9%, and the merchant was rate-limited at 03:41.
Retrained on Sep 24 with device features, the model's precision rose from about 0.66 to 0.72 at the same recall, which means hundreds fewer false alarms a week for analysts.
The feature lookup takes about 3 ms and the model about 4 ms; the rest is network and serialisation. The budget for a decision is 100 ms.
customer_profile features were 26 hours old after an upstream delay. Streaming features carry most of the signal, so scores stayed stable while the batch caught up.
About the data. Every number on this page is sample data from a seeded generator written for this project. It is shaped to behave like a real workload, with daily peaks, late events and the odd incident, but it does not come from any employer or client. Download it as transactions_5min.csv or read data.json.