HomeCase studiesReal-Time Financial Fraud Detection Pipeline Using Kafka...

Case study · Frankfurt, Germany

Real-Time Financial Fraud Detection Pipeline Using Kafka Streaming and Scikit-learn Scoring

Real-Time Transaction Risk & AML

Payment processors and digital banks cannot afford multi-second scoring delays or opaque black-box declines when screening instant SEPA transfers and card authorizations. Built for a payment risk team in Frankfurt, we engineered a real-time financial fraud detection platform combining Kafka event streaming, Python microservices, and calibrated Scikit-learn ensembles. Transactions receive deterministic rule checks, sliding-window Redis velocity features, and explainable risk scores within strict authorization budgets, while analysts triage flagged alerts inside a dedicated web workbench.

Industry
Real-Time Transaction Risk & AML
Solution
A low-latency transaction risk and AML platform combining synchronous Python/Scikit-learn scoring APIs, Kafka stream feature pipelines, and a compliance analyst triage console.
Platforms
Web & API
Stack
Python · Scikit-learn · Kafka · FastAPI · PostgreSQL · Redis
Location
Frankfurt, Germany · delivered remotely
Role
Engineering, with the team behind for mobile and QA

Delivered remotely for a business based in Frankfurt, Germany. Names withheld by agreement.

Project Overview

Instant payment rails in Europe leave almost no margin between clearing speed and financial crime exposure. Once a SEPA Instant Credit Transfer settles, funds are irrevocable within seconds, forcing payment institutions in Frankfurt to evaluate device posture, beneficiary risk, and historical account velocity before authorization completes. At the same time, overly aggressive static thresholds lock out legitimate corporate payroll runs and cross-border retail purchases, driving costly manual review backlogs.

We designed and shipped a real-time financial fraud detection platform built around Apache Kafka, Python, and Scikit-learn. The platform separates ultra-fast pre-authorization screening from deep asynchronous AML graph enrichment, giving payment switches decisive allow/challenge/block verdicts in milliseconds while feeding compliance analysts transparent, evidence-backed case queues.

Payment Risk & AML Bottlenecks

Conventional batch-oriented anti-fraud setups fail across four operational dimensions when applied to modern payment streams:

  • Batch-window blind spots: Nightly SQL scans detect account-takeover rings hours after mule accounts have already drained funds.
  • Opaque decline reasons: Uncalibrated black-box scores leave compliance officers unable to explain adverse decisions during regulatory audits or customer disputes.
  • Training-serving divergence: Separate SQL definitions for offline model training and Java/Python runtime rules produce silent drift in production feature distributions.
  • Risky rule deployments: Pushing an untested threshold or retrained classifier directly into live traffic risks halting legitimate payment volume.

Architectural Strategy

Our guiding principle was dual-path scoring with unified feature semantics. A synchronous FastAPI scoring endpoint evaluates incoming payment requests against hot Redis velocity aggregates, deterministic sanctions/velocity rules, and serialized Scikit-learn pipelines. Every authorization attempt simultaneously emits an immutable event onto Kafka topics.

Downstream Python stream workers consume Kafka partitions to update sliding-window counters in Redis, run slower counterparty-network anomaly checks for AML structuring, and write full feature snapshots into ClickHouse. Analysts reviewing cases in the web console work directly off PostgreSQL alert queues whose dispositions (confirmed_fraud, false_positive, escalated_sar) flow back onto a Kafka feedback topic to continuously label future Scikit-learn retraining cycles.

Core Capabilities

  • Sub-Second Pre-Authorization Scoring: Evaluates card, wallet, and SEPA transfer payloads using Redis sliding windows and Scikit-learn ensembles before settlement.
  • Hybrid Rule + ML Decisioning: Combines deterministic compliance vetoes (sanctions hits, velocity caps) with calibrated probability scores for nuanced behavioral anomalies.
  • Shadow Model Evaluation: Replays live Kafka traffic through candidate Scikit-learn artifacts alongside the production champion without impacting customer payments.
  • Explainable Analyst Case Workbench: Surfaces exact rule triggers, top Scikit-learn feature contributors, and historical IBAN/device link graphs for rapid human triage.
  • Closed-Loop Feedback Labeling: Captures chargebacks, scam reports, and analyst verdicts on Kafka to prevent model staleness as attack vectors evolve.

Technical Architecture

The scoring topology bridges synchronous request-response authorization with asynchronous event-driven state management. When a payment gateway posts an authorization payload to FastAPI, the service fetches pre-computed behavioral aggregates from Redis (1h, 24h, 7d counters, distinct beneficiary counts, geolocation jumps) via a single pipelined read, executes the Scikit-learn Pipeline (ColumnTransformer + calibrated gradient boosted trees + Isolation Forest outlier score), and applies ordered policy rules.

Flow: Payment Switch → FastAPI Synchronous Scorer (Redis Online Features + Scikit-learn Pipeline) → Verdict & Kafka Event Publish → Kafka Consumers (Window Aggregators + AML Graph Workers) → ClickHouse Telemetry + PostgreSQL Alert Queue → Analyst Web Workbench

Because Kafka retains ordered, partitioned transaction logs keyed by account and instrument ID, stateful feature workers compute rolling metrics without lock contention. Shadow-scoring consumers attach to the same Kafka topic independently, logging counterfactual verdicts to ClickHouse for precision-recall benchmarking.

Technology Stack

Category Technology detail
Event Backbone Apache Kafka carrying transaction authorizations, enrichment streams, and analyst feedback
Scoring Service Python FastAPI serving synchronous risk evaluation and shadow-model telemetry
ML Risk Models Scikit-learn calibrated gradient boosting and Isolation Forest anomaly pipelines
Online Feature Store Redis sorted sets and HyperLogLogs tracking sub-second card/IBAN velocity windows
Case & Rule Store PostgreSQL managing alert queues, rule thresholds, and audit-logged analyst dispositions
Analytical Warehouse ClickHouse storing multi-year transaction logs for feature backfills and AML pattern queries
Explainability Layer Deterministic rule reasons paired with per-feature contribution weights on every alert
Analyst Workbench Web console displaying entity graphs, velocity timelines, and one-click SAR export packets
Model Governance Versioned Scikit-learn artifact registry with automated drift checks and shadow replay

Engineering Trade-offs & Solutions

Engineering Challenge Solution & Trade-off
Heavy graph queries during authorization breach strict payment latency SLAs Pre-materialized account-level velocity and counterparty-novelty signals in Redis via async Kafka workers, keeping live scoring O(1) at the cost of sub-second eventual consistency on cross-account links.
Extreme class imbalance causes Scikit-learn classifiers to emit uncalibrated probabilities Applied stratified temporal splits with isotonic/Platt probability calibration inside Scikit-learn pipelines, trading minor training complexity for threshold-stable risk scores across rule tiers.
Analysts distrust ML alerts without clear behavioral evidence Paired each score with deterministic reason codes extracted from feature-threshold deviations and tree-path contributions, slightly increasing payload size while accelerating compliance review.
Rebuilding sliding windows after a Redis restart loses recent velocity context Configured Kafka compacted state snapshots alongside deterministic ClickHouse warm-start jobs so Redis feature buckets rebuild rapidly without blind scoring gaps.

Compliance, Auditability & Data Protection

Operating financial risk infrastructure under European supervisory expectations demands full decision reproducibility. Every verdict logged to PostgreSQL and ClickHouse captures the exact Scikit-learn model SHA, feature vector snapshot, rule-set version, and threshold outcome at the millisecond of decision.

Sensitive payment identifiers—IBANs, card PAN tokens, and beneficiary names—are tokenized or salted-hashed prior to analytical warehousing in ClickHouse, restricting raw PII decryption solely to authorized AML investigators inside the authenticated case workbench. Role-based permissions enforce dual-control approval before any production risk rule or model promotion takes effect.

Streaming Scale & Resilience

Traffic surges during retail holidays or coordinated credential-stuffing attacks stress both API scoring nodes and downstream stream consumers. FastAPI workers load serialized Scikit-learn artifacts into memory at startup to avoid per-request disk I/O and execute vectorized NumPy transformations efficiently across stateless replicas.

Kafka topic partitioning by source account distributes stateful Redis updates evenly across worker pods while preserving strict per-account event ordering. Automated consumer-lag alerts monitor backpressure so temporary ClickHouse maintenance never interferes with synchronous payment authorization throughput.

Operational Outcomes

Unifying synchronous Python scoring with Kafka-driven feature pipelines transformed transaction risk operations from reactive batch cleanup into proactive real-time defense:

  • Immediate pre-settlement intervention: High-risk transfers and automated velocity attacks trigger step-up authentication or blocks before irrevocable payment rails clear.
  • Transparent regulatory readiness: Every automated decline and manual AML investigation preserves an exact lineage of features, rule versions, and analyst notes.
  • Safe model iteration: Shadow-mode Kafka replay lets data scientists validate new Scikit-learn detectors on live traffic behavior before switching enforcement traffic.
  • Reduced analyst friction: Consolidated entity timelines and ranked reason codes eliminate multi-tab database lookups during fraud case triage.

01 — Questions

asked about this kind of project

Why pair Scikit-learn models with Kafka instead of running deep neural networks in the authorization path?

Tabular payment risk relies heavily on calibrated velocity, device-novelty, and counterparty-graph features where Scikit-learn tree ensembles and anomaly detectors deliver strong precision with deterministic sub-10ms CPU inference and transparent feature attribution for BaFin/AML audits.

How do you prevent training-serving skew between historical ClickHouse features and real-time Redis counters?

Both offline training pipelines and online Kafka consumers invoke the exact same Python feature-transformation definitions. Historical training sets reconstruct point-in-time sliding windows strictly prior to each transaction timestamp so offline validation mirrors live scoring.

What happens if the ML scoring service experiences a spike or timeout during payment peak hours?

The synchronous FastAPI gateway enforces tight timeouts and degrades gracefully to deterministic velocity and sanctions rules stored locally in-memory and Redis. Payment rails never hang waiting on non-essential enrichment, while Kafka queues missed telemetry for asynchronous post-auth AML review.

How are new fraud models validated before blocking live customer payments?

Candidate Scikit-learn pipelines deploy first in shadow mode consuming live Kafka transaction streams without affecting authorization outcomes. Risk engineers compare false-positive rates and score stability against the production champion in ClickHouse before promoting traffic.

How do fraud analysts know why a specific transfer was declined or routed to manual review?

Every scored event persists the active rule hits alongside top contributing Scikit-learn feature deviations—such as unusual beneficiary IBAN novelty or cross-border velocity spikes—directly in PostgreSQL so compliance teams never face unexplained numeric scores.

03 — Similar project?

describe what is different about yours

Build yours.

Tell me what exists, what you need and the deadline. Fixed price for a defined scope, or $55/day (8–9 hours work) with a written plan first.

Solitaire Corporate Park, Makarba, Ahmedabad, Gujarat 380015, India · IST (UTC+5:30) · --:-- IST · Mon–Fri 09:00–18:00 IST · US & EU overlap daily

No newsletter, no CRM. Just a reply.