Real-time fraud flags for card payments

A personal project: a streaming pipeline that scores every card payment as it arrives and sends the risky ones to a review queue, built to learn where streaming systems break.

Type
Personal project
Stack
Kafka, Spark Structured Streaming, Delta Lake, XGBoost, Docker
Focus
Data engineering and ML

How it works

  1. Generate payments

    A Python producer writes synthetic card payments to a Kafka topic, with a small share shaped like known fraud patterns.

  2. Score each payment

    Spark Structured Streaming joins each payment to the card’s recent history and scores it with an XGBoost model.

  3. Store and route

    Every scored payment lands in a Delta table; payments over the threshold also go to a review topic.

  4. Watch the pipeline

    Consumer lag, throughput and the share of flagged payments are tracked, so a stuck job shows up fast.

stream.py
payments = (spark.readStream.format("kafka")
    .option("subscribe", "payments")
    .load()
    .select(from_json(col("value").cast("string"), schema).alias("p"))
    .select("p.*")
    .withWatermark("event_time", "10 minutes"))

scored = (add_card_history(payments)
    .withColumn("risk", score(*FEATURES)))

(scored.writeStream.format("delta")
    .option("checkpointLocation", CHECKPOINTS)
    .toTable("payments_scored"))

Decisions I made. Each one is a trade-off, written down.

.withWatermark("event_time", "10 minutes")

Bounded state with watermarks

Events more than ten minutes late are dropped from the rolling windows. State stays small and the trade-off is written down.

features.py -> train.py, stream.py

One feature definition

The same feature code runs in training and in the stream, so the model never sees a feature computed two ways.

RISK_THRESHOLD = 0.82

A threshold in config

The flag threshold lives in config, outside the model, so reviewers can trade missed fraud against false alarms without a retrain.

What I would add next

  • Replay tests against recorded traffic
  • Exactly-once writes to the review queue
  • A drift check on the model’s inputs

Next project: Gives a retail team one source of truth

Orders, payments and ad spend loaded by Airflow, modelled in dbt on Snowflake, with tests on every run.