Project 10 · Real-time ML

Real-Time Fraud Detection Pipeline

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.

  • Apache Kafka
  • Spark Structured Streaming
  • Feast
  • Redis
  • Grafana
Sample data Tuesday, Oct 6, 2026 · model quality over the last 30 days Download data (CSV)

Transactions per minute

Oct 6, 5-minute average

Flag rate

Sent to review or declined

Risk score distribution

Transactions by score, log scale

Flag rate by merchant category

Oct 6

Precision and recall

Daily, from analyst decisions and chargebacks

Confusion matrix

Last 30 days, threshold 0.80

Recent alerts

Score, the feature that contributed most, and the analyst's decision

Feature store

Feast feature views and how old their online values are

How it works

From authorization to decision in about 46 ms at p95, with the same features online and in training.

  1. 01 · Authorize

    Payment gateway

    Each card authorization goes to Kafka with amount, merchant, device and location, keyed by card.

  2. 02 · Compute features

    Spark Structured Streaming

    Sliding windows per card, merchant and device: counts, sums, distinct merchants and velocity, updated every 5 seconds.

  3. 03 · Serve features

    Feast + Redis

    Streaming and daily batch features in one registry; online lookups take about 3 ms.

  4. 04 · Score

    Model service

    A gradient-boosted model scores each transaction with its features before the payment is approved.

  5. 05 · Act

    Rules + review queue

    0.90 and above declines, 0.80 to 0.90 goes to an analyst, below 0.80 approves.

  6. 06 · Learn

    Labels + Grafana

    Analyst decisions and chargebacks become labels; precision and recall are tracked daily and drive retraining.

  • Same features online and offline. Feast serves the feature definitions used in training, with point-in-time joins offline and Redis online, so the model sees the same numbers in production.
  • Fresh features, bounded latency. Streaming features reach Redis about a second after a transaction. If the store is slow, the service scores with batch features rather than delay the payment.
  • Thresholds are business decisions. The 0.80 and 0.90 cut-offs trade analyst workload against missed fraud. The confusion matrix shows that trade-off in numbers.
  • Feedback closes the loop. Every alert outcome and chargeback is joined back to its score. That join produces the daily precision and recall, and the training labels.

Data model

One event, one feature view and one score record: the whole life of a decision.

payments.authorizationsKafka topic · Avro · keyed by card
txn_idstring
Unique per authorization
card_idstring
Tokenised card; never the card number
merchant_id / mccstring / int
Merchant and its category code
amount_usddecimal(12,2)
Converted at authorization time
device_id / lat / lonstring / double
Where the request came from
event_tstimestamp
Authorization time
card_txn_rollingFeast feature view · Redis online · TTL 2 h
card_identity
Join key
txn_count_10m / txn_count_1hint64
Transactions in the window
amount_sum_10mfloat
Spend in the last ten minutes
distinct_merchants_10mint64
A burst of merchants is a classic fraud signal
km_from_last_txnfloat
Distance from the previous transaction
event_timestamptimestamp
End of the window the values describe
fraud.scoresIceberg table · one row per decision
txn_idstring
The authorization
score / decisiondouble / string
Risk score and approve, review or decline
model_versionstring
For example fraud-v14
featuresmap<string,double>
The values used, for audits and debugging
label / labeled_atboolean / timestamp
Filled in later from analysts and chargebacks

Key code

The 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())

Engineering notes

The 3 a.m. card-testing attack

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.

Model v14 cut false alarms

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.

46 ms at p95

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.

One late batch, no drama

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.