AWS Builder Center
Detecting fraud in real time with Temporal Graph Networks on AWS - Part 1

Detecting fraud in real time with Temporal Graph Networks on AWS - Part 1

Build a TGN fraud detector on AWS — from temporal graph data generation and model training to sub-100ms production inference on SageMaker and Neptune.

Data and Ai lead at AWS
This is Part 1 of a two-part series.  Part 2    will explore advanced techniques including MiNT (Multi-Network Training), transfer learning across payment networks, and ensemble scoring.
Learning level: 300 — Advanced technical Post type: Technical walkthrough AWS services: Amazon Kinesis Data Streams, Amazon Neptune, Amazon ElastiCache for Valkey, Amazon SageMaker, AWS Lambda, Amazon API Gateway, Amazon S3, AWS Glue, Amazon CloudWatch AWS services: Amazon Kinesis Data Streams, Amazon Neptune, Amazon ElastiCache for Valkey, Amazon SageMaker, AWS Lambda, Amazon API Gateway, Amazon S3, AWS Glue, Amazon CloudWatch



Introduction

Every day, financial institutions process billions of transactions — and fraudsters adapt faster than rule-based systems can keep up. Traditional approaches model each transaction in isolation: a single row of features fed to a gradient-boosted classifier. They miss the patterns that matter most — the sequence of interactions between entities over time.
Consider card testing fraud: a fraudster runs dozens of tiny authorization requests in rapid succession before a major charge. Each transaction looks benign in isolation. Zoom out to the account's temporal transaction graph, and the pattern is unmistakable.
Temporal Graph Networks (TGN) solve this by treating fraud detection as a dynamic graph problem. Each account, merchant, and device is a node; each transaction is an edge with a timestamp. The model maintains a memory for every entity — a state vector that evolves with each interaction — capturing behavioral history without requiring hand-crafted features.
In this post, you'll learn how to build a production-grade TGN fraud detection system on AWS. You'll walk through:
  • Why temporal graphs outperform tabular models for detecting sequential fraud patterns
  • The TGN architecture: memory, graph attention, and dual scoring heads
  • A complete training example with real Python code
  • How to deploy at scale using Amazon SageMaker, Amazon Neptune, Amazon ElastiCache, and Amazon Kinesis
  • A two-pass scoring architecture that delivers sub-100ms inference on 10,000 transactions per second
The code in this walkthrough comes from an open-source implementation built for financial services teams. You can find the full library on GitHub (link at the end of this post).
Prerequisites: Python ≥ 3.10, PyTorch ≥ 2.1, PyTorch Geometric ≥ 2.4, and an AWS account. Familiarity with graph neural networks and PyTorch is helpful but not required.



Prerequisites

  • An AWS account
  • Basic familiarity with machine learning concepts (loss functions, train/test splits)



Why standard fraud detection falls short

Most deployed fraud models score transactions as independent events. A gradient-boosted tree receives a vector of features — amount, merchant category, time of day, velocity counts — and outputs a risk score. These models are fast, interpretable, and work well in aggregate.
They miss three things that fraud exploits:
Sequential patterns. Card testing, account takeover, and money laundering all have characteristic sequences of transactions. A single transaction is ambiguous; the sequence tells the story.
Network context. Fraudsters don't act in isolation. A compromised account funnels money through a chain of mule accounts. A synthetic identity ring shares device fingerprints. Graph structure encodes these relationships directly.
Behavioral drift. A legitimate cardholder has a stable spending pattern. Account takeover produces a sudden, sharp deviation. Detecting this requires memory — a representation of historical behavior.
TGN addresses all three. The key insight from Rossi et al. (2020) is the memory module: each node maintains a state vector updated with a gated recurrent unit (GRU) after every interaction. The model learns what to remember and what to forget, building a compressed behavioral profile for each entity automatically.



The TGN architecture

The TGN Fraud Detector is built from four components that work in sequence. Understanding each one will help you tune and extend the model for your use case.

1. Memory module

The memory module maintains a  memory_dim -dimensional state vector per node. After each transaction, both the source and destination nodes receive a memory update:
msg = IdentityMessage(memory[src], memory[dst], edge_features, Δt)
memory[src] = GRU(memory[src], msg)
memory[dst] = GRU(memory[dst], msg)

 IdentityMessage  passes the raw edge features directly, keeping the message function lightweight.  LastAggregator  keeps only the most recent message per node — simple but effective in practice because recent interactions are most predictive of fraud.
The GRU update is the core of what makes TGN powerful: the model learns, end-to-end, how to encode interaction history into a fixed-size vector. There are no hand-crafted velocity features, no lookback windows to tune. The memory learns what matters.

2. Time encoder

Each timestamp is encoded into a high-dimensional vector using a learnable Fourier encoding:
# Time deltas become continuous representations spanning seconds to years
time_enc = TimeEncoder(time_dim=32)
encoding = time_enc(torch.tensor([0.0, 60.0, 3600.0, 86400.0]))
# Shape: [4, 32] — different time scales produce different encodings

The time encoder learns a set of cosine frequencies during training. This lets the model reason about recency without discretizing time into arbitrary buckets — it can simultaneously learn that "transactions within 60 seconds of each other are suspicious" and "spending patterns change over weeks."

3. Graph attention embedding

Memory vectors capture what happened to a node historically. The graph attention embedding module adds structural context — information from the node's recent transaction neighbors:
z = TransformerConv(memory[node], neighbors, edge_features + time_encodings)

Multi-head attention learns which neighbors are most relevant. For a potentially compromised account, its interactions with recently flagged merchants will receive higher attention weights than routine grocery purchases. The output embedding  z  fuses memory-based history with graph-based context.

4. Dual scoring heads

The model produces two scores simultaneously:
LinkPredictor scores the transaction itself — is this specific edge (src → dst at time t) anomalous?
link_score = LinkPredictor(z_src, z_dst) # anomaly logit for this edge

NodeClassifier scores the account — is the source node a risky entity overall?
node_score = NodeClassifier(z_src) # account-level risk logit

Dual scoring enables downstream flexibility. The link score catches one-off anomalous transactions. The node score catches accounts engaged in sustained fraudulent behavior — useful for AML and account takeover detection.
Here is the full forward pass:
class TGNFraudDetector(nn.Module):
def forward(self, src, dst, t, msg, neg_dst=None):
# 1. Retrieve memory for all involved nodes
n_id = torch.cat([src, dst]).unique()
z, last_update = self.memory(n_id)

# 2. Build index mapping: node_id -> position in z
assoc = torch.full((n_id.max() + 1,), -1, dtype=torch.long)
assoc[n_id] = torch.arange(n_id.size(0))

z_src = z[assoc[src]]
z_dst = z[assoc[dst]]

# 3. Score the transaction and the account
pos_score = self.link_pred(z_src, z_dst) # link anomaly score
node_scores = self.node_pred(z_src) # account risk score

# 4. Update memory — the model always learns from new interactions
self.memory.update_state(src, dst, t.long(), msg)

return pos_score, None, node_scores

Step 4 is notable: memory updates happen during inference, not just training. Every scored transaction immediately enriches the behavioral profile of the entities involved.



Generating training data

Before training, you need transaction data represented as a temporal graph. The  tgn_learn  library includes synthetic generators for two common fraud scenarios:
from tgn_learn.generators import BankSimGenerator
from tgn_learn.generators.base import GeneratorConfig

config = GeneratorConfig(
num_accounts=200,
num_merchants=30,
num_transactions=5000,
fraud_rate=0.03, # 3% fraud — realistic for card-present fraud
seed=42,
duration_days=30,
)

graph = BankSimGenerator(config).generate()
print(graph.summary())
# Nodes: 230, Edges: 5000, Fraud edges: 150 (3.0%)
# Time span: 30.0 days, Avg transactions/day: 167

The generator injects five distinct fraud patterns with realistic temporal signatures:
Pattern
Temporal signature
Card testing
Rapid bursts of tiny amounts (< $5)
Account takeover
Sudden spike in transaction amount/velocity
Money laundering
Layered chains: A → B → C → D with time delays
Synthetic identity
New account with unusually high early activity
Bust-out fraud
Gradual limit utilization then sudden maximum-charge
Each edge in the graph carries a  label  (0 = legitimate, 1 = fraud) and the  pattern  metadata. This structure is what you will use for training.



Training the model

The combined loss function

Training uses two loss components simultaneously, which is central to why TGN learns robust fraud representations.
Contrastive link loss (unsupervised): For each real transaction (src → dst), the model samples a random "negative" destination  neg_dst . The loss trains the model to score real edges higher than synthetic ones. This forces the model to learn who normally transacts with whom — structural norms of the transaction network.
Supervised node loss (supervised): For nodes involved in labeled fraud transactions, the model predicts the fraud label using class-weighted binary cross-entropy. The  pos_weight  parameter compensates for the extreme class imbalance typical of fraud data (95–99% legitimate).
# Combined loss — learns structure and behavior simultaneously
loss = 0.5 * link_loss + 0.5 * node_loss

The contrastive component provides a rich training signal even for unlabeled transactions. The supervised component anchors the model to actual fraud labels. Together they outperform either loss alone.

Temporal splitting

A critical implementation detail: never split the dataset randomly. Fraud models trained with random splits consistently overestimate performance in production because temporal patterns leak from future data into training.
All transactions sorted by timestamp:
├── Train: first 70% (transactions 1 → 3,500)
├── Validation: next 15% (transactions 3,501 → 4,250)
└── Test: final 15% (transactions 4,251 → 5,000)

This mirrors production conditions — the model scores transactions it has never seen, using only behavioral history from before the transaction occurred.

Running training

from tgn_learn.generators import BankSimGenerator
from tgn_learn.generators.base import GeneratorConfig
from tgn_learn.model import TGNConfig
from tgn_learn.training import TGNTrainer, TrainingConfig

# Generate data
gen_config = GeneratorConfig(
num_accounts=200, num_merchants=30,
num_transactions=3000, fraud_rate=0.05, seed=42,
)
graph = BankSimGenerator(gen_config).generate()

# Configure training
train_config = TrainingConfig(
epochs=15,
batch_size=200,
learning_rate=1e-3,
patience=8, # early stopping on val AUC-PR
link_loss_weight=0.5,
node_loss_weight=0.5,
)
model_config = TGNConfig(
memory_dim=64,
embedding_dim=64,
time_dim=32,
)

# Train
trainer = TGNTrainer(train_config, model_config)
results = trainer.train(graph, verbose=True)

print(f"Test AUC-PR: {results['test_metrics'].auc_pr:.4f}")
# Test AUC-PR: 0.7843 (vs ~0.25 for a random baseline on 5% fraud data)


Why AUC-PR, not accuracy?

With 95% legitimate transactions, a classifier predicting "always legitimate" achieves 95% accuracy but catches zero fraud. AUC-PR (area under the precision-recall curve) measures what matters: the model's ability to rank actual fraud cases at the top of its scores. It is the correct metric for any severely imbalanced detection problem.



Scoring transactions at inference time

The  Scorer  class wraps the trained model with a user-facing API and adds two important capabilities: isotonic calibration and risk tier classification.
from tgn_learn.scoring import Scorer

scorer = Scorer(results["model"], device="cpu")

# Score a single transaction
result = scorer.score_transaction(
src=0, dst=50,
timestamp=1700050000.0,
amount=100.0
)
print(result)
# ScoreResult(risk_score=0.12, risk_tier=LOW, confidence=0.91)

# Score a suspicious transaction (large amount immediately after normal one)
result = scorer.score_transaction(
src=0, dst=50,
timestamp=1700050001.0, # 1 second later
amount=9500.0
)
print(result)
# ScoreResult(risk_score=0.78, risk_tier=HIGH, confidence=0.85)


Score calibration

Raw neural network outputs are not well-calibrated probabilities — a logit of 0.7 does not mean a 70% chance of fraud. Isotonic regression maps the model's raw scores to true probabilities using a held-out validation set:
scorer.calibrate(val_scores, val_labels)

# Before calibration: raw=0.7 may correspond to 40% true fraud rate
# After calibration: raw=0.7 → calibrated=0.68 (tracks actual rate)


Risk tiers

Calibrated scores map to four actionable tiers:
Score range
Tier
Action
0.00 – 0.30
LOW
Approve automatically
0.30 – 0.60
MEDIUM
Flag for analyst review
0.60 – 0.85
HIGH
Hold pending investigation
0.85 – 1.00
CRITICAL
Block immediately
The tier boundaries are tunable. Tightening the LOW threshold reduces false negatives but increases operational costs. Use your organization's fraud-loss-to-false-positive-cost ratio to set thresholds that optimize business outcomes.



Building on AWS: the production architecture

The training code above runs locally. Production deployment at financial-services scale — 50 million active entities, 1,000–10,000 transactions per second, sub-100ms latency — requires a thoughtful AWS architecture.
The core design follows the Lambda architecture pattern (BRIGHT, eBay, CIKM 2022): expensive multi-hop TGN computations run in batch offline; real-time inference retrieves pre-computed embeddings from cache and runs only a lightweight scoring head.

Architecture overview

Core Banking System
│ transaction event
▼
Amazon API Gateway → AWS Lambda (scoring orchestrator)
│
┌───────────────┼──────────────────────────┐
▼ ▼ ▼
Amazon ElastiCache SageMaker Amazon Kinesis
(Redis embeddings) Feature Store Data Streams
│ │
│ AWS Lambda (graph processor)
│ │
▼ Amazon Neptune
SageMaker TGN Fast Path (property graph)
ml.g5.2xlarge × 3 │
Pass 1 (~20ms) Neptune Analytics
│
score ≥ 0.3? (~3% of transactions)
│ yes
▼
SageMaker SEAL endpoint
ml.g5.xlarge × 2
Pass 2 (+50ms)
│
Risk score + tier + explanation
│
Amazon DocumentDB (fraud case record)
Amazon QuickSight (analyst dashboard)


Layer 1: Real-time ingestion with Amazon Kinesis Data Streams

Every transaction from your core banking system arrives as a timestamped event on a Kinesis Data Stream. Kinesis provides:
  • Ordered delivery within a shard — critical for maintaining temporal integrity when updating Neptune
  • Replay capability — reprocess historical events when retraining or backfilling
  • On-Demand mode (Standard or Advantage) — scales automatically to handle up to 200 MB/s write throughput; Advantage tier adds proactive capacity warming at lower per-unit pricing
An AWS Lambda function consumes from Kinesis, encodes the transaction as a graph event (node lookups, edge feature encoding, multi-scale time encoding), and writes the edge to Amazon Neptune.

Layer 2: Graph store with Amazon Neptune

Neptune stores the full transaction graph as a property graph: cardholders, merchants, and devices as vertices; transactions as edges with timestamp and amount properties.
Neptune serves two roles:
  1. Subgraph extraction at inference time — for the ~3% of transactions that score ≥ 0.3 in Pass 1, the SEAL endpoint performs a 2-hop neighborhood traversal to build a structural subgraph for deep inspection
  1. Fraud analyst workbench — Gremlin queries for fund-flow tracing, money chain identification, and ad-hoc investigation
Neptune Analytics adds in-memory capabilities on top: community detection for automatic fraud ring identification, and vector similarity search on TGN embeddings ("find 10 transactions most similar to this flagged one").

Layer 3: Node memory store with Amazon ElastiCache for Valkey

The Lambda architecture separates expensive offline computation from fast online retrieval. Amazon SageMaker Batch Transform runs hourly, computing updated entity embeddings across the full transaction graph and writing them to ElastiCache:
Data
Description
TTL
TGN memory vectors
128-dim float vectors per entity, updated post-transaction
90 days inactivity
Batch embeddings
Richer multi-hop embeddings computed hourly
2 hours
Redis gives sub-2ms P99 retrieval for 50M+ active entities. The scoring Lambda retrieves the embedding in ~2ms, making the per-entity memory lookup essentially free in the overall latency budget.

Layer 4: Two-pass scoring with Amazon SageMaker

Two separate SageMaker real-time inference endpoints implement the two-pass scoring logic:
Pass 1 (100% of transactions):
TGN memory retrieval + Fast Path endpoint → score
score < 0.3 → APPROVE (end)
score ≥ 0.3 → Pass 2

Pass 2 (~3% of transactions):
Neptune subgraph extraction → SEAL DGCNN → structural score
combined_score = α·tgn_score + (1-α)·seal_score
0.3 – 0.7 → soft decline / 3DS challenge
> 0.7 → hard decline / case management alert

Endpoint
Instance
Latency target
Scale
TGN Fast Path
ml.g5.2xlarge × 3
~20ms
Handles full TPS
SEAL Structural
ml.g5.xlarge × 2
~50ms additional
Sees only ~3% of volume
Keeping endpoints separate prevents the 97% of transactions that never need structural enrichment from consuming SEAL compute capacity, and allows independent auto-scaling.

Layer 5: Training pipeline with SageMaker Pipelines

The full MLOps workflow runs on SageMaker Pipelines, triggered weekly by Amazon EventBridge:
S3 (raw data) → AWS Glue ETL → SageMaker Training Job
→ SageMaker Model Registry → Validation gate (AUPRC ≥ previous)
→ SageMaker endpoint update

AWS Glue handles the critical step of building training datasets with strict chronological splits — not random shuffles. This is where most productionized fraud models introduce subtle temporal leakage that inflates offline metrics.
SageMaker Model Registry gates every promotion to production: a human reviewer must approve the model, and AUPRC must meet or exceed the current production model.

Layer 6: Drift detection and adaptive retraining

Fraud patterns evolve constantly — attackers respond to model deployments within days. Amazon CloudWatch and  Amazon SageMaker Model Monitor  watch three signals. Note: SageMaker Model Monitor is closing to new customers on 30 July 2026 — existing customers continue to have access. New deployments should use CloudWatch custom metrics with a custom monitoring container to achieve equivalent drift detection:
  • AUPRC on chargeback feedback (chargebacks arrive 30–90 days post-transaction)
  • Embedding distribution drift — the autoencoder reconstruction error detects concept drift before AUPRC degrades
  • Endpoint latency P99 and error rate
An Amazon EventBridge rule connects CloudWatch alarms to automatic SageMaker Pipeline retrain triggers — closing the feedback loop without manual intervention.

Estimated monthly cost (eu-west-1, on-demand)

Component
Service
Estimated monthly cost
Transaction ingestion
Kinesis On-Demand (1K TPS)
~$300
Node memory store
ElastiCache for Valkey 200 GB
~$900
TGN inference fast path
SageMaker ml.g5.2xlarge × 3
~$2,600
Structural inference
SageMaker ml.g5.xlarge × 2
~$1,100
Training jobs
SageMaker ml.g5.12xlarge
~$750
Graph store
Neptune db.r6g.2xlarge × 3, 2 TB
~$1,700
Feature store
SageMaker Feature Store 5 TB
~$1,500
Observability
CloudWatch + Model Monitor
~$200
Total (on-demand)

~$9,000/month
With 1-year Reserved Instances on compute: approximately $5,500/month. You can model your specific configuration with the  AWS Pricing Calculator .



Cleaning up

The resources deployed in this walkthrough will incur ongoing AWS charges. After you've finished experimenting, delete the following resources to avoid unexpected costs:
  1. SageMaker endpoints — In the  Amazon SageMaker console , choose Inference > Endpoints and delete the TGN Fast Path and SEAL Structural endpoints.
  1. Neptune cluster — In the  Amazon Neptune console , select your cluster and choose Delete.
  1. ElastiCache cluster — In the  Amazon ElastiCache console , select your Redis cluster and choose Delete.
  1. Kinesis Data Stream — In the  Amazon Kinesis console , select your data stream and choose Delete.
  1. SageMaker Feature Store — Delete the feature groups from the  Amazon SageMaker console  under Feature Store.
  1. S3 buckets — Empty and delete any S3 buckets created for training data and model artifacts.



Key design decisions

Neptune + ElastiCache instead of Neptune alone. Neptune P99 Gremlin query latency at inference scale is 50–200ms — too slow for the fast path. ElastiCache delivers sub-2ms for the 97% of transactions that do not require live graph traversal. Neptune remains the authoritative source; ElastiCache is the serving layer.
Two SageMaker endpoints instead of one. A single endpoint colocating TGN and SEAL wastes GPU capacity on transactions that never reach Pass 2. Separate endpoints allow independent auto-scaling aligned with actual traffic distribution.
SageMaker Feature Store for profile features. ElastiCache holds dynamic embeddings updated per-transaction. Feature Store holds slower-changing account characteristics (account age, balance quantile) and rolling velocity statistics. Separating them maintains training/serving feature parity — a common source of unexplained production AUC degradation.
Temporal splits everywhere. Random splits in fraud detection produce unrealistically high offline metrics and fail to predict production behavior. Every dataset split in this system — training, validation, test, and AWS Glue ETL output — uses strict chronological ordering.



Getting started

The  tgn_learn  library provides everything covered in this post: synthetic data generators, the full TGN model, training infrastructure, and a Streamlit app for interactive exploration.
Before you begin:
  • Python ≥ 3.10, PyTorch ≥ 2.1, PyTorch Geometric ≥ 2.4
# Clone the repository
git clone https://github.com/your-org/tgn-fraud-detection
cd tgn-fraud-detection

# Create a virtual environment and install dependencies
python -m venv .venv && source .venv/bin/activate
pip install -e ".[dev]"

# Launch the interactive Streamlit app
streamlit run app/main.py

# Or run the progressive learning scripts
python learn/01_data_generation.py
python learn/02_graph_construction.py
python learn/03_tgn_architecture.py
python learn/04_training_loop.py
python learn/05_inference_scoring.py
python learn/06_mint_transfer.py # multi-network transfer learning

The Streamlit app lets you generate synthetic networks, explore the transaction graph interactively, train a model with live loss charts, and score transactions — all in a browser. It is designed as a hands-on learning environment before moving to the production AWS deployment.



Conclusion

Temporal Graph Networks bring a fundamentally different lens to fraud detection. Instead of scoring transactions as independent events, TGN treats your transaction data as what it actually is: a dynamic network of evolving relationships. The memory module accumulates behavioral history; graph attention adds structural context; and the dual scoring heads expose both transaction-level and account-level risk.
Deployed on AWS with Amazon Neptune, Amazon ElastiCache, Amazon SageMaker, and Amazon Kinesis Data Streams, this architecture handles 10,000 transactions per second with sub-100ms P99 latency — ready for production financial services workloads.
The key principles to take away:
  1. Temporal graphs capture what tabular models miss — sequences, network structure, and behavioral drift
  1. TGN memory is the core innovation — each node builds its own behavioral profile automatically
  1. Combined loss learns structure and behavior simultaneously — contrastive + supervised
  1. Temporal splits are non-negotiable — random splits inflate offline metrics and fail in production
  1. The Lambda architecture is the right pattern — batch pre-computation of embeddings, lightweight real-time retrieval
This foundation — a trained TGN, a risk-tiered scorer, and an AWS deployment pipeline — is where most fraud detection systems stop. But it leaves a significant capability gap: the model is trained on a single network, so it generalizes poorly when deployed to a new payment domain or a new geographic market without a large labeled dataset.
 In Part 2 , we'll tackle that problem directly. We'll explore MiNT (Multi-Network Training), a transfer learning technique that pre-trains a single TGN backbone across multiple transaction networks simultaneously. Because fraud patterns are universal — card testing looks the same whether it occurs on a bank's card-present network or a mobile money platform — a MiNT-pretrained model learns generalizable fraud representations that transfer to new networks with minimal labeled data. We'll also look at ensemble scoring, combining TGN with gradient-boosted trees on TGN embeddings, and conformal prediction for uncertainty-aware risk scores.
If you have questions about what this post covered, leave a comment. If you build on this implementation, share what fraud patterns you find in your data — the community learns faster together.



Additional resources

In this post, I showed how to build a TGN-based fraud detection system from scratch — from data generation and model training to a two-pass production deployment on AWS.


  • BRIGHT — Lu et al. (2022) — Lambda architecture for graph-based fraud detection (eBay, CIKM 2022)


About the author: Faris Haddad is a technical lead at AWS based in UK, specializing in AI/ML and data solutions for enterprise customers. He works with financial services organizations to build scalable machine learning systems on AWS.

Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article