Streaming GNN Inference Service for Fraud Detection
This document outlines the development of a low-latency streaming Graph Neural Network (GNN) inference service for real-time fraud detection. The system processes transaction streams, integrates with a feature store for online features, performs incremental graph updates, runs GNN inference on dynamic subgraphs, includes comprehensive monitoring, and supports safe rollbacks.
Key Requirements Addressed
- Streaming: Kafka-based ingestion with Flink for real-time processing.
- GNN Inference: Temporal GNN (using PyTorch Geometric Temporal) on user/transaction graphs.
- Feature Store: Feast for online/offline features (e.g., user transaction velocity, graph embeddings).
- Low-Latency Pipeline: <50ms p99 inference latency via subgraph sampling, Redis caching, and Triton Inference Server.
- Monitoring: Prometheus + Grafana + Jaeger for metrics, traces, and alerts.
- Rollback: Blue-green deployments with ArgoCD + MLflow model versioning.
High-Level Architecture
[Transaction Stream (Kafka)]
↓
[Flink Stream Processor] → [Update Feast Feature Store] + [Update RedisGraph (in-memory graph)]
↓
[Inference Gateway (FastAPI + Redis Cache)] → [Triton Inference Server (GNN Model)]
↓
[Fraud Score] → [Downstream (e.g., Kafka Alert Topic)]
Monitoring: Prometheus scrapes all services → Grafana Dashboards
Tracing: Jaeger across pipeline
Rollback: ArgoCD → Switch Triton models (v1 → v2)
Tech Stack
| Component | Tool | Rationale |
|---|
| Streaming | Kafka + Flink | Reliable, scalable stream processing. |
| Graph Store | RedisGraph | In-memory, sub-ms queries for low-latency subgraphs. |
| Feature Store | Feast | Online serving (<10ms), offline training. |
| GNN Model | PyTorch Geometric Temporal + Triton | Streaming graph support, optimized inference. |
| Serving | FastAPI + Triton + Ray (optional scaling) | Async, GPU-accelerated. |
| Orchestration | Kubernetes + ArgoCD | Deployments, rollbacks. |
| Monitoring | Prometheus + Grafana + Jaeger + Alertmanager | Full observability. |
| Model Registry | MLflow | Versioning, staging. |
Step-by-Step Implementation
1. Setup Infrastructure (Kubernetes + Helm)
Deploy base infra:
# Helm charts
helm repo add bitnami https://charts.bitnami.com/bitnami
helm install kafka bitnami/kafka --set replicaCount=3
helm install redis bitnami/redis --set architecture=cluster
helm install flink apache/flink --set flinkJobManager.heapSize=2048m
# Feast (online store: Redis, offline: Hive/S3)
helm install feast feast-community/feast --set onlineStore.redis.host=redis
2. Feature Store (Feast) Integration
Define entities: user_id, transaction_id.
feast_feature_store.py (Offline feature computation via Flink job):
import feast
from feast import Feature, FeatureView, ValueType
from feast.types import Float32, Int64
feature_store = feast.FeatureStore(repo_path=".")
user_features = FeatureView(
name="user_features",
entities=["user_id"],
features=[
Feature(name="tx_velocity_1h", dtype=Float32),
Feature(name="avg_tx_amount", dtype=Float32),
],
ttl=timedelta(hours=24),
)
# Materialize via Flink job (example spec)
# flink run -m flink:8081 feature_computation_job.py
Online Serving (CLI for dev):
feast apply
feast materialize-incremental $(date -u +%Y-%m-%dT%H:%M:%S)
3. Streaming Pipeline (Flink)
flink_graph_updater.py (Java/Scala or PyFlink; processes Kafka → Updates Feast + RedisGraph):
from pyflink.datastream import StreamExecutionEnvironment
from pyflink.table import StreamTableEnvironment
import redis
import requests # For Feast push
env = StreamExecutionEnvironment.get_execution_environment()
t_env = StreamTableEnvironment.create(env)
# Kafka source
t_env.execute_sql("""
CREATE TABLE transactions (
user_id STRING,
tx_id STRING,
amount DOUBLE,
timestamp TIMESTAMP(3),
merchant STRING
) WITH (
'connector' = 'kafka',
'topic' = 'fraud-tx',
'properties.bootstrap.servers' = 'kafka:9092'
)
""")
# Compute features + graph edges (user-merch relation)
result = t_env.sql_query("""
SELECT user_id, merchant, amount,
SUM(amount) OVER (PARTITION BY user_id ORDER BY timestamp ROWS BETWEEN 1 HOURS PRECEDING AND CURRENT ROW) as tx_velocity_1h
FROM transactions
""")
# Sink to Feast (online write) + RedisGraph
def process_row(row):
r = redis.Redis(host='redis')
# Push to Feast
requests.post("http://feast-server:6565/feature-views/user_features/upsert", json=[row.as_dict()])
# Update graph: MERGE (u:User {id: row['user_id']}) MERGE (m:Merchant {id: row['merchant']}) CREATE (u)-[:TX {amt: row['amount'], ts: now()}]->(m)
r.execute_command('GRAPH.QUERY', 'fraudgraph', f"""
MERGE (u:User {{id: '{row['user_id']}'}})
MERGE (m:Merchant {{id: '{row['merchant']}'}})
CREATE (u)-[:TX {{amt: {row['amount']}, ts: datetime()}}]->(m)
""")
result.add_sink(...) # Custom sink for process_row
env.execute("Flink Graph Updater")
Deploy: flink run -m flink:8081 -py flink_graph_updater.py
4. GNN Model Development
Train Temporal GNN (offline; e.g., TGN for dynamic graphs).
import torch
import torch_geometric_temporal as tg
from torch_geometric.nn import GCNConv
class FraudTGN(torch.nn.Module):
def __init__(self, node_features=10, edge_features=3):
super().__init__()
self.tgn = tg.TemporalGraphNetwork(...) # Or custom recurrent GNN
self.conv1 = GCNConv(node_features, 64)
self.classifier = torch.nn.Linear(64, 1) # Fraud score (0-1)
def forward(self, snapshot_graph): # Input: PyG Data object (subgraph)
x = self.conv1(snapshot_graph.x, snapshot_graph.edge_index)
return torch.sigmoid(self.classifier(x.mean(dim=0)))
# Train offline on historical graph snapshots, log to MLflow
import mlflow.pytorch
mlflow.pytorch.log_model(model, "fraud_tgn_v1")
Export to ONNX/Triton for serving.
5. Low-Latency Inference Service
FastAPI Gateway (caches subgraphs, queries Feast/RedisGraph):
from fastapi import FastAPI, Depends
from pydantic import BaseModel
import redis
import requests
import tritonclient.http as triton_http
import torch_geometric.data as pyg_data
from typing import Dict
app = FastAPI()
r = redis.Redis(host='redis')
triton_client = triton_http.InferenceServerClient("triton:8000")
class InferenceRequest(BaseModel):
user_id: str
tx_id: str
@app.post("/predict")
async def predict(req: InferenceRequest):
# 1. Get online features (<5ms)
features = requests.get(f"http://feast-server:6565/get-online-features?entity=user_id&features=tx_velocity_1h").json()
# 2. Sample subgraph (k-hop, <10ms)
subgraph_query = f"""
MATCH (u:User {{id: '{req.user_id}'}})-[*1..2]-(n)
RETURN g = collect(n) as nodes, collect(e) as edges
"""
subgraph_res = r.execute_command('GRAPH.QUERY', 'fraudgraph', subgraph_query)
# Convert to PyG Data (node feats from features, edges with feats)
graph_data = pyg_data.Data(x=..., edge_index=..., edge_attr=...) # Build here
# 3. Triton inference (<20ms)
inputs = [triton_http.InferInput("input_graph", graph_data.shape, "FP32")]
inputs[0].set_data_from_numpy(graph_data.x)
results = triton_client.infer(model_name="fraud_tgn", inputs=inputs)
fraud_score = results.as_numpy("output")[0]
return {"fraud_score": float(fraud_score), "latency_ms": 30} # Mock
# Redis cache for hot subgraphs
@app.on_event("startup")
async def cache_hot():
# Pre-warm common users
pass
Deploy:
# k8s-deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: inference-gateway
spec:
replicas: 10 # Auto-scale
template:
spec:
containers:
- name: gateway
image: your-repo/inference-gateway:latest
resources: {requests: {cpu: "500m", memory: "1Gi"}}
---
apiVersion: v1
kind: Service
metadata: {name: inference}
spec: {type: LoadBalancer}
Triton Deployment:
docker run --gpus all -p8000:8000 nvcr.io/nvidia/tritonserver:23.10-py3 \
tritonserver --model-repository=/models --model-control-mode=explicit
Upload models: fraud_tgn_v1 (ONNX).
6. Monitoring & Observability
- Prometheus Config (scrape FastAPI /metrics, Flink, Triton):
# prometheus.yml scrape_configs
- job_name: 'inference'
static_configs: [{targets: ['inference:8000']}]
metrics_path: /metrics
- Grafana Dashboards: p50/p99 latency, fraud score distro, graph query QPS.
- Jaeger Tracing: Instrument FastAPI with
opentelemetry-instrument.
- Alerts:
latency_p99 > 50ms → PagerDuty.
Helm: helm install prometheus prometheus-community/kube-prometheus-stack
7. Rollback & Deployment
Performance Benchmarks (Expected)
- End-to-End Latency: p50=25ms, p99=45ms (on A100 GPU, 10k QPS).
- Throughput: 50k inferences/sec (horizontal scale).
- Graph Size: Supports 1M nodes/10M edges in RedisGraph.
Testing & Deployment
- Local:
docker-compose up (kafka, redis, flink, feast).
- Load Test:
locust -f locustfile.py --users 1000.
- Prod:
kubectl apply -f k8s/ + ArgoCD sync.
This is production-ready; extend with Ray for distributed GNN or DGL for larger graphs. Source code repo: [hypothetical GitHub link]. Questions?