We are going to design a system for temporal graph analytics for fraud detection. The system should handle incremental updates to the graph, provide a query language for analysis, implement caching strategies for performance, and include explanation tooling to help understand the results.
Components:
Graph Storage: We need to store a temporal graph (nodes and edges with timestamps). We should support incremental updates (adding nodes/edges with timestamps). We'll use a combination of storage backends. Since it's temporal, we might need to store multiple versions of the graph. However, full versioning might be expensive. Alternatively, we can store the graph as a set of events (edge creations/deletions, node properties changes) and compute the state at a given time on the fly or via incremental materialization.
Given the requirement for incremental updates and queries over time, we might consider a temporal graph database or a versioned graph approach. But to keep it general, we can design our own storage layer.
We'll assume we have a write-optimized storage for incoming events (like a log) and a read-optimized storage for querying (materialized views or snapshots). We'll use a combination:
Event Log: Append-only log of all graph changes (node/edge additions, property updates, deletions) with timestamps. This is the source of truth.
Materialized Snapshots: Periodically, we take snapshots of the graph at certain times to speed up queries. Alternatively, we can maintain an in-memory or on-disk graph that is updated incrementally.
For real-time fraud detection, we might need to query the graph as of the latest time (or near latest) frequently. So we can maintain a current graph state in memory (or a fast store) that is updated with each incoming event.
We'll design:
A Graph Store that maintains the current state (for latest time) and can also reconstruct historical states (for temporal queries) by using the event log and possibly periodic snapshots.
Query Language: We need a language to express temporal graph queries. Examples:
"Find all transactions (edges) between user nodes where the total amount in the last 7 days exceeds $10,000."
"Find cycles of length 3 in the transaction graph in the last 30 days that involve a particular flagged user."
We can design a DSL (domain-specific language) or use an existing one (like Cypher with temporal extensions, or Gremlin with time predicates). But since we are building from scratch, we'll define a simple query language.
Let's call it Temporal Graph Query Language (TGQL).
Basic ideas:
Queries are about finding patterns in the graph over a time window.
We can specify time constraints on edges and nodes (e.g., edge timestamp within a window).
We might want to aggregate over time (sum, count, etc.) within windows.
Example query in pseudo-code:
code
MATCH (u1:User)-[t:TRANSACTION {timestamp: window}]->(u2:User)
WHERE t.amount > 1000
AND window := last_7_days
RETURN u1, u2, sum(t.amount) as total
But we need more expressive power for fraud patterns (like cycles, chain of transactions, etc.).
We can base it on graph pattern matching with temporal constraints. However, implementing a full pattern matching engine is complex. Alternatively, we can compile certain patterns to operations on the graph.
Given the scope, we might support:
Simple traversals with time filters.
Aggregations over time windows (sliding or tumbling).
Maybe predefined fraud patterns (like triangular fraud) as built-in functions.
But to keep it extensible, we can define a core query language that is Turing complete? Maybe not necessary.
Let's plan for:
Time Travel Queries: Query the graph as of a specific timestamp or time range.
Temporal Aggregations: Compute metrics over time windows (e.g., sum of transaction amounts per user in last 24h).
Pattern Matching: Detect specific subgraph patterns that occur within a time window (e.g., a cycle where all edges are within a short time window).
We'll design the query engine to parse TGQL and translate it into operations on our graph store.
Caching Strategies: Since fraud detection needs low latency, we'll cache:
Query Results: Cache the results of recent queries (with their time parameters) for a short time. Use a LRU cache keyed by query string and time parameters (or time window). But note: as new events come in, the results for past windows may not change (if the window is fixed and in the past) but for rolling windows (like last 7 days) they will change as new data arrives. So we need to invalidate caches for rolling windows when new data arrives.
Graph Snapshots: Cache snapshots of the graph at certain times. For example, we can cache the graph state for the last few minutes/hours to avoid recomputing from the event log every time.
Intermediate Results: For complex queries, we might cache intermediate aggregations (like per-user transaction sum for a given day) to speed up repeated queries.
We'll design a Cache Manager that can be configured with multiple cache layers.
Explanation Tooling: When a fraud is detected, we want to explain why. So we need to generate human-readable (or analyst-readable) explanations that include:
The pattern that matched.
The specific subgraph (nodes and edges) that triggered the alert.
Temporal aspects: when the events occurred, time differences, etc.
Possibly visualizations.
We can design:
An Explanation Generator that takes a query and its result (a set of graph elements) and produces a report.
We can also store the executed query and the data that caused the match so that we can reproduce.
We might integrate with a visualization tool (like a graph viewer) to display the subgraph with timestamps on edges.
getGraphAsOf(timestamp): returns a graph (snapshot) as of that time.
getEdges(nodeId, startTime, endTime, edgeType): get edges incident to a node within a time window.
getNodes(...) similar.
traverse(startNode, pattern, timeWindow): for pattern matching.
We can implement getGraphAsOf by:
Maintaining a current in-memory graph (for latest) and an event log.
For historical queries, we can reconstruct by applying events up to the given timestamp. This can be expensive if we do it from scratch every time. So we use snapshots: periodically (e.g., every hour) we save the entire graph state. Then for a query at time T, we find the latest snapshot before T and then apply events from that snapshot time to T.
Alternatively, we can use a versioned graph database like Datomic or a temporal database like TimescaleDB with graph extensions? But we are designing our own.
We'll choose a hybrid:
Current State Graph: stored in a graph database (like Neo4j) or in-memory (like NetworkX) for fast latest queries. But we need incremental updates, so an in-memory graph that we update with each event might be feasible if the graph isn't huge. For large graphs, we need a distributed store.
Given the complexity, let's assume we are building for a moderate scale (millions of nodes, tens of millions of edges). We can use:
Event Log: Kafka or a simple disk-based log.
Current State: We maintain a graph in memory (or in a fast key-value store) that is updated with each event. For historical states, we rely on snapshots plus log.
But memory might not be enough. So we can use a disk-based graph store that supports versioning? Maybe we use a Temporal Graph Index:
We index edges by time. For each edge type, we have a time-partitioned storage: e.g., edges are stored in buckets by day. Then to get the graph as of a time, we need to consider all buckets up to that day and then filter edges that were active at that time (if edges can be deleted). But if edges are never deleted, then the graph as of time T is the union of all edges with timestamp <= T. That is simpler. But in fraud, we might have edge deletions (e.g., transaction reversed). So we need to handle edge lifespans.
We can store edges with validFrom and validTo timestamps. Initially, validTo is infinity. When an edge is deleted, we set validTo to the deletion time. So the graph as of time T is all edges where validFrom <= T < validTo. Similarly for node properties.
So our storage:
Nodes: nodeId, properties, validFrom, validTo? But nodes might be created and deleted. We can model similarly.
Then to get the graph as of T, we query for all nodes and edges that were active at T.
We need efficient range queries on validFrom and validTo. We can index by validFrom and also by validTo or use a composite.
But this approach means we store the entire history. That can be large. We might need to prune or archive old data.
For performance, we can maintain materialized views for recent times. For example, we keep a current graph (with all edges that have validTo > now) in a fast store. And we have an archive of historical edges that are no longer current.
So:
Current Graph Store: holds edges with validTo > current time (or infinity). Actually, we need to include edges that are still active. This is the latest state.
Historical Archive: holds edges that have expired (validTo set). We can store this in a slower store.
Then for a query at time T:
If T is in the recent past (e.g., within last 24h), we might have a snapshot of the graph at that time? Or we can compute by taking the current graph and then removing edges that were added after T and adding edges that were deleted after T? That's tricky.
Alternatively, we maintain periodic snapshots (e.g., every hour) of the entire graph. Then for a query at T, we:
Find the latest snapshot S before T.
Get all events (edge/node changes) that occurred after S and before or at T.
Apply those events to the snapshot to get the state at T.
This is a common approach in event sourcing.
We'll design:
Snapshot Store: stores full graph snapshots at times S1, S2, ... (serialized graph).
Event Log: stores all events (node/edge create/update/delete) with timestamps and a monotonically increasing sequence number.
To get graph as of T:
Find the latest snapshot with time <= T. (We can keep snapshots at fixed intervals, e.g., every hour.)
Determine the last event sequence number in that snapshot (the snapshot includes the log offset up to which events are applied).
Read events from that offset+1 up to events with timestamp <= T.
Apply those events to the snapshot to get the graph at T.
This is efficient if the number of events between snapshots is not huge. We can also keep snapshots more frequently (e.g., every 5 minutes) for low latency.
But snapshots of a large graph can be expensive. We might use incremental snapshots? Or we can use a hybrid where we keep the current state in a mutable store and use the event log for recovery and historical queries only for times before the current state started? Hmm.
Another approach: use a temporal graph database that natively supports versioning, like Titan with time? Not sure.
Given the time, we'll design a simpler system:
We assume that fraud detection queries are mainly about recent times (last few days) and we don't need arbitrary historical queries far back. So we can:
Keep the last 30 days of data in an online store that supports time travel within that window.
For older data, we archive to a data lake and run batch queries if needed.
So for our engine, we focus on the online temporal graph for the last N days.
We can use a time-partitioned graph:
For each day, we store a graph snapshot at the end of the day. But then intra-day queries require events from the current day.
Alternatively, we store the graph as a stream of events and maintain a 实时视图 that can be queried at any time within the retention window. This is like a materialized view that is continuously updated.
We can use a stream processor (like Flink) to maintain the current state and also allow time-travel queries by keeping the state for the retention window. Flink has state that can be queried (but it's not designed for arbitrary historical queries).
Perhaps we use a database with temporal features. Since we are designing, we can choose:
Use a graph database that supports temporal queries? Neo4j has a temporal plugin? Not natively.
I think for the purpose of this design, we'll abstract the storage and assume we have a component that can provide:
getSubgraph(startTime, endTime, nodeFilter, edgeFilter): returns the subgraph of nodes and edges that were active during the given time interval (with conditions). This is a heavy operation but we can optimize with indices.
We'll design the storage layer to efficiently answer such queries by having:
Edge Index: a composite index on (edgeType, validFrom, validTo) and also on (srcId, edgeType, validFrom, validTo) and (dstId, ...). We might use a B-tree or LSM-tree.
Node Index: similar.
But we also need to support pattern matching that traverses the graph. So we need to be able to get outgoing/incoming edges for a node within a time window quickly.
We can store edges in a key-value store where key is (srcId, edgeType, validFrom) or something. But then for a given node and time window, we need to find edges where validFrom <= windowEnd and validTo > windowStart (or at least one point in common). That's a range query on validFrom and validTo.
This is complex. Maybe we simplify: assume edges are never deleted, only added. Then the graph is monotonically increasing. Then the graph as of time T is all edges with timestamp <= T. And we can index edges by timestamp. That is much simpler.
In fraud detection, transactions might be reversed, but we can model reversals as new edges (with a different type) that link back? Or we can allow edge deletion but that complicates. Let's assume for now edges are never deleted, but we have a flag or type for reversal. Then we can ignore reversed edges in queries by filtering edge type. So we keep all edges forever.
Then our storage:
We store edges with a timestamp (transaction time). The graph as of time T is the set of edges with timestamp <= T.
We index edges by timestamp and also by source and destination.
Then to get outgoing edges for a node within a time window [t1, t2], we look up edges where srcId = nodeId and timestamp between t1 and t2. That's a simple range query on timestamp with a condition on srcId.
We can have a primary index on (srcId, timestamp) and also on (dstId, timestamp). That allows bidirectional traversal.
So we'll go with:
Edges are immutable and never deleted. They have a timestamp.
Nodes are also immutable? Node properties might change, but we can treat property changes as new nodes with a new timestamp? Or we can store node versions. To keep it simple, we assume nodes are created once and properties don't change. Or if they do, we store a new node version with a new id? That complicates. Alternatively, we store node properties with a timestamp and for a given time we take the latest property version before that time. That's similar to edges.
But for simplicity, let's assume nodes are static. Fraud detection often uses static user attributes (like registration time) and dynamic transaction edges.
So we design:
Node table: node_id, label, properties (properties might include static info and maybe a created_at timestamp). We assume nodes are created at a time and never deleted/updated.
Edge table: edge_id, src_id, dst_id, type, properties, timestamp (timestamp is transaction time). Indexes on (src_id, timestamp), (dst_id, timestamp), (type, timestamp).
Then to get the graph as of time T, we take all edges with timestamp <= T and all nodes that are incident to at least one such edge (or we might want all nodes? but nodes without edges might be irrelevant). But we might want to include isolated nodes that existed at that time? We can have a node creation timestamp. Then nodes with created_at <= T are considered to exist at time T.
So we add created_at to nodes. Then graph as of T: nodes with created_at <= T, edges with timestamp <= T.
That's a clean model.
Now we need to support incremental updates: new edges and nodes are added with timestamps (which can be in the past? Possibly, but usually transactions have the time they occurred. In real-time, we receive events with timestamps close to current time. But there might be late arrivals. We need to handle out-of-order events? For fraud detection, we might tolerate some lateness. We can set a watermark: we only consider events with timestamp within, say, last 24h. But for correctness, we might need to handle out-of-order data. That complicates the storage because we need to update previously materialized views if an old edge arrives. But if we keep edges immutable and just insert with their timestamp, then we can insert any time and queries that include that timestamp will see it. However, if we have a cached graph snapshot for a time that now includes this new edge, we need to invalidate that cache.
So we need to handle:
Late events: If an event with timestamp T arrives after we've already taken a snapshot that includes times after T, then that snapshot is no longer valid for queries covering T. We need to either rebuild snapshots or not rely on snapshots for times that might have late data. Alternatively, we set a data freshness policy: we consider data as provisional until a certain time (e.g., 1 hour) after which it is immutable. Then we only take snapshots for times that are older than the provisional window. This is like in stream processing: we have event time and we wait for a certain lateness.
So we'll define:
Provisional Period: For a time T, data is considered provisional until current_time - provisional_lateness (e.g., 1 hour). After that, no more edges with timestamp T are expected (or we ignore very late ones). Then we can safely take snapshots for times that are older than the provisional period.
So our snapshot strategy:
We take snapshots for times that are at least provisional_lateness in the past.
For queries with a time window that ends in the provisional period, we cannot use snapshots; we must read from the event log (or from a real-time materialized view that is updated with every event and may still change).
We can maintain:
Real-time Graph: an in-memory (or fast) graph that contains all edges with timestamp >= (now - provisional_lateness). This is constantly updated with incoming events. This graph is used for queries with windows overlapping the provisional period.
Historical Graph: for times older than provisional_lateness, we have snapshots at regular intervals (e.g., every hour). For a query entirely in the historical period, we use the nearest snapshot and then apply events between snapshot time and query time (but those events are already in the snapshot? Actually, snapshot at time S includes all events with timestamp <= S. So if query time T is between snapshots, we take snapshot at S (where S <= T and next snapshot > T) and then apply events with timestamp in (S, T] from the event log. But note: events with timestamp in (S, T] might have been included in the snapshot if their timestamp <= S? No, because snapshot is at time S, it includes events with timestamp <= S. So we need events with timestamp in (S, T] to bring the graph to state at T. However, these events might be in the real-time graph if they are recent? But if T is historical (older than provisional_lateness), then all events with timestamp <= T are considered final and should be in the event log. We can replay them.
So we need:
Event Log: persistent storage of all events (edges) with their timestamps. We can use a distributed log like Kafka or a simple append-only file with an index.
Snapshot Store: stores serialized graph snapshots at times S (with the graph state including nodes and edges with timestamp <= S). We also store the last event offset included in the snapshot.
Real-time Materialized View: a graph that is updated with every incoming event (for events with timestamp >= now - provisional_lateness). This view is used for queries that need the latest data. We can also use it for historical queries if we keep it for the whole provisional period? But that would be large. Instead, for historical queries we rely on snapshots and event log.
Let's define:
provisional_lateness = 1 hour.
We take snapshots every hour for times that are at least 1 hour old. So snapshot at time T includes all events with timestamp <= T. The next snapshot at T+1h includes events up to T+1h.
For a query with time window [start, end]:
If end <= now - provisional_lateness (i.e., entirely in the historical past), then:
Find the latest snapshot S <= start? Actually we need the graph as of end? But we want the subgraph of edges that have timestamp in [start, end]. That is not the same as the graph as of end. Because we want only edges that occurred in that window, not all edges up to end. So we need to compute the set of edges with timestamp in [start, end]. This can be done by:
Option 1: Use the snapshot at time start-1 (just before start) and then apply events with timestamp in [start, end] from the event log. But we need the graph at start to compute changes? Actually, we want only edges in the window. We don't need the whole graph state; we need a subgraph. So we can directly query the edge index for edges with timestamp in [start, end]. That's simpler.
However, if we also need nodes that exist at that time, we need to get nodes that were created before or during the window and maybe deleted? But we assume nodes never deleted. So nodes with created_at <= end and maybe we also want nodes that are incident to edges in the window. So we can query edges in the window, then get the distinct node IDs from those edges, then fetch those nodes (with their properties). That is straightforward.
So maybe we don't need full graph snapshots for edge queries; we can just query the edge table with a time range. That's what the edge index on timestamp is for.
But pattern matching (like finding cycles) requires traversing the graph of edges in the window. We need to load the subgraph (nodes and edges in the window) into memory and run the pattern matching. That subgraph could be large if the window is long. We might need to sample or use distributed processing.
For fraud detection, we are often looking for specific patterns in recent data (last few hours or days). So we can limit the window size.
So we can design:
The query engine receives a query with a time window [start, end].
It retrieves edges with timestamp in [start, end] from the edge index (using start and end bounds). Also retrieves nodes that are incident to these edges (or all nodes with created_at <= end, but that might be huge). So we should retrieve only nodes that are involved in the edges of interest.
Then it runs the pattern matching on this in-memory subgraph.
This is feasible if the window is not too large. For larger windows, we might need to do distributed graph processing (like Spark GraphX) but that's beyond scope.
So for our engine, we assume the time window is such that the subgraph fits in memory of a single server (or we use a singlemachine graph library).
Therefore, we might not need complex snapshotting; we can just query the edge index for the time window.
But what about efficiency? If we query the same window repeatedly, we can cache the subgraph. That's our caching strategy.
So:
Storage: We store nodes and edges in a database that supports range queries on timestamp. We'll use a relational database with indexes or a time-series database with graph capabilities? Or a graph database that also indexes by time? We can use PostgreSQL with TimescaleDB for time-series and then join? But graph traversal is hard.
We might use a dedicated graph database that allows property on edges including timestamp, and we can index that property. For example, Neo4j has indexes on properties. But range queries on timestamps might be slow if not properly indexed.
We can also use an Elasticsearch cluster for edges: we index edges by timestamp, src_id, dst_id, type. Then we can search for edges within a time range and then fetch nodes by IDs from a separate node store.
That might work.
But we are designing the engine, not the underlying store. We'll assume we have a GraphStorage interface that can efficiently retrieve:
getEdgesByTimeRange(start, end, edgeType, srcId=None, dstId=None): returns edges with timestamp in [start, end] and optional filters.
getNodesByIds(nodeIds): returns node properties.
getNodeCreationTime(nodeId): maybe.
And we also need to support incremental updates: addEdge(edge) and addNode(node).
So the storage layer can be implemented using a combination of:
A time-series database for edges (like InfluxDB, TimescaleDB) with a schema that includes src_id, dst_id, type, and timestamp as the time index. But then src_id and dst_id are just tags, and we can query by time range and also filter by src_id or dst_id? Yes, in TimescaleDB we can have indexes on tags.
A key-value store for nodes: node_id -> properties.
But then retrieving a subgraph: we first query edges in time range, then get distinct node IDs, then batch get nodes. That's fine.
However, pattern matching might require traversing from a node to its neighbors within the time window. If we have an index on (src_id, timestamp), we can get outgoing edges for a node in a time range quickly. But if we want to traverse multiple hops, we need to repeatedly query the storage for each node's edges. That could be many round trips. So we want to load the entire edge set for the window into memory and then do in-memory traversal. That's what we proposed: fetch all edges in the window first. But if the window is large and the graph is dense, that could be too many edges. We might need to limit the window or use a distributed approach.
Given that fraud detection often focuses on recent activity, we can assume the window is limited (e.g., last 24 hours or last 7 days) and the number of edges in that window is manageable (maybe millions). That's acceptable.
So plan:
For a query, we retrieve all edges in the time window from storage (using the time index) and all nodes that are incident to these edges. We build an in-memory graph (adjacency lists) and run the pattern matching algorithm.
We cache the subgraph (edges set) for a given time window and query parameters (like edge types) to avoid re-fetching if the same window is queried again and no new edges have arrived for that window.
But note: if new edges arrive with timestamps in that window, the cached subgraph becomes stale. So we need to invalidate cache entries when new edges arrive for that window. Since we have a provisional period, we might only cache windows that are fully in the historical past (i.e., end <= now - provisional_lateness). For windows that overlap the provisional period, we might not cache or use a shorter TTL.
Alternatively, we can use a versioned cache: each time we fetch edges for a window, we also note the maximum event sequence number (or timestamp of latest edge) we have seen. When new edges arrive, if they belong to a cached window and have a higher sequence number, we invalidate that cache. But we can also update the cache by adding the new edges? That's more complex.
Simpler: For historical windows (end < now - provisional_lateness), we assume the data is immutable and we can cache indefinitely. For windows that include recent data, we use a short TTL (e.g., 1 minute) or no cache.
But queries might be for sliding windows like "last 24 hours" which always include recent data. So those won't be cached. That's okay because the subgraph is changing every minute.
So caching strategy:
Query Result Cache: For a query that specifies a fixed time window (e.g., [start, end]) and other parameters, we cache the result set (the matching subgraph patterns) if the window is entirely in the past beyond the provisional period. We use a key: hash(query_string + window_start + window_end). TTL = infinite (until snapshot invalidation? but if we use event log, the data for that window won't change). So we can cache forever.
Subgraph Cache: We might also cache the fetched edges and nodes for a given window to avoid re-fetching from storage if multiple queries use the same window. This is lower level. But we can combine with query result cache: if we cache query results, we don't need subgraph cache separately because the result is computed from subgraph. But if different queries use the same window but different patterns, we might fetch subgraph multiple times. So we can cache the subgraph for a window (with maybe a shorter TTL for recent windows). We'll have a SubgraphCache keyed by (window_start, window_end, edge_types?) and store the set of edges (and maybe nodes) as a graph object.
We need to be careful about memory: subgraphs can be large. So we might limit the cache size with LRU.
Snapshot Cache: If we use snapshots for historical queries, we cache the snapshots themselves.
But we decided we don't need snapshots if we directly query edges by time range. However, for very large historical windows, querying the edge index might be slow because it scans all edges in that window? But if we have an index on timestamp, it should be a range scan which is efficient. But still, if the window is months, the number of edges could be huge and we wouldn't load them all into memory anyway. So for large windows, we might need to do distributed processing or sampling. So we'll assume queries have reasonable window sizes.
So we might skip snapshots and rely on direct edge queries. But then for a query that asks for "graph as of time T" (like all edges up to T), we would query edges with timestamp <= T, which is a large set if T is far back. That's not feasible for large T. But our fraud queries are likely to be on recent data or on specific patterns that are naturally limited (like "find cycles in last 7 days"). So the window is recent.
So we'll assume all queries have a time window that is at most a few days.
Therefore, we can implement:
Storage: Use a database with a table edges with columns: id, src_id, dst_id, type, timestamp, properties. Index on timestamp (maybe partition by time) and also on (src_id, timestamp) and (dst_id, timestamp) to support per-node time range queries. But our method of fetching all edges in a window doesn't need per-node index; we just do a range scan on timestamp. That could be heavy if the window is large and the table is huge. But if we partition by time (e.g., by day) then a range scan over a few days is okay.
We'll assume the storage can handle range scans efficiently.
Now, the Query Engine:
Parse TGQL.
Translate to an execution plan:
Extract time window from query (if not specified, default to last 24h?).
Determine which edge types are needed.
Fetch edges from storage: SELECT * FROM edges WHERE timestamp BETWEEN start AND end AND type IN (...). Possibly also filter by other edge properties? We can push down simple filters to storage.
Fetch distinct node IDs from the edges (both src and dst).
Fetch nodes from node store: SELECT * FROM nodes WHERE id IN (...).
Build an in-memory graph: nodes with properties, adjacency lists for edges (with properties).
Run pattern matching: e.g., find all triangles, or find all paths of length 2 with sum condition, etc.
We need to define the pattern matching algorithms for common fraud patterns. We can have a library of pattern detectors:
detect_triangles(graph): returns set of triangles (three nodes with edges between them all within the time window? Actually, each edge has its own timestamp; we need to ensure that all three edges are within the window? That's given because we only loaded edges in the window. But what if a triangle spans edges with timestamps outside the window? Our subgraph only contains edges in the window, so any triangle we find is entirely within the window. That's fine.
But sometimes fraud patterns require temporal ordering: e.g., A pays B, then B pays C, then C pays A within a short time. That's a cycle with temporal order. Our in-memory graph doesn't store order explicitly; we have edges with timestamps. We can check timestamps when detecting cycles.
So pattern matching functions will take the in-memory graph and produce matches, possibly with additional conditions on timestamps.
We need to design the query language to express these patterns.
Let's define TGQL:
A query is:
code
[MATCH pattern] [WHERE conditions] [RETURN or AGGREGATE]
The pattern describes a graph structure with optional temporal constraints.
Example for triangular fraud:
code
MATCH (a)-[e1:TRANSACTION]->(b)-[e2:TRANSACTION]->(c)-[e3:TRANSACTION]->(a)
WHERE e1.amount > 1000 AND e2.amount > 1000 AND e3.amount > 1000
AND e1.timestamp < e2.timestamp AND e2.timestamp < e3.timestamp
AND e3.timestamp - e1.timestamp < 24h
RETURN a,b,c, e1,e2,e3
This finds directed cycles of length 3 with amounts >1000 and happening within 24h.
We might also want to aggregate:
code
MATCH (u)-[t:TRANSACTION]->(v)
WHERE t.timestamp >= last_7_days
RETURN u, sum(t.amount) as total, count(*) as count
HAVING total > 10000
So we need to support aggregations and having.
This is essentially a graph query language with time windows and aggregations.
We can base it on Cypher but with temporal extensions.
Implementation:
Parse the query using a parser (ANTLR or hand-written).
Build an abstract syntax tree (AST).
The executor:
Determines the time window: from the WHERE clause or a default. If the query uses last_n_days, we compute from current time.
Fetches edges and nodes as described.
Builds in-memory graph.
Evaluates the pattern matching: we need to find all embeddings of the pattern in the graph that satisfy the conditions.
For simple patterns like a path or cycle, we can do nested loops or use algorithms.
For complex patterns, we might need a generic subgraph isomorphism algorithm, which is NP-hard. But given the pattern is small (usually up to 5 nodes) and the graph is not huge, we can do backtracking.
However, we can optimize by using indexes on node labels/attributes from the pattern. But our in-memory graph is already filtered by time and edge types. We can also filter nodes by labels (e.g., :User) during node fetch.
We'll assume nodes have labels and we can push down label filters to the node fetch.
So the execution steps:
Parse query, extract:
Time window (start, end).
Node patterns: e.g., (a:User), (b:Merchant).
Edge patterns: e.g., -[e:TRANSACTION]->, with direction and type.
Conditions on node/edge properties and on timestamps (like e.timestamp < e2.timestamp).
Return clause: what to output (variables, aggregations).
Plan:
For each node variable, determine the label filter (if any). For each edge, type filter.
Build a set of required edge types.
Fetch edges from storage: SELECT * FROM edges WHERE timestamp BETWEEN start AND end AND type IN (required_types). Also, if there are conditions on edge properties that are simple (e.g., amount > 1000), we can push down to storage. But if conditions involve comparing two edges' timestamps, we cannot push down because it's a cross-edge condition. So we might not be able to push down all. But we can push down simple ones to reduce data.
Fetch nodes: we need all nodes that appear in any of the edges. But also, if there are isolated nodes in the pattern? Not really; pattern involves edges. So we get distinct node IDs from the edges. Then fetch nodes with those IDs and apply label filters (if any) and any node property conditions that are not pushed down.
Build in-memory graph:
Map node IDs to node objects with properties.
For each node, maintain adjacency lists: for outgoing edges, list of (neighbor, edge). For incoming edges, similar.
We might need to quickly get edges by type and direction.
Pattern matching:
We have a pattern with variables and chain. We need to find all assignments of variables to nodes and edges that satisfy:
The structure: e.g., a->b, b->c, c->a.
All edges exist and have the specified types? We already filtered edges by type, so edges in the graph have the required types? But careful: we fetched all edges of required types in the window. The pattern might require specific edge types for each step. So when we traverse, we only consider edges of that type.
Conditions on properties and timestamps: we'll evaluate them during matching.
We can implement a backtracking search:
Let pattern be a sequence of relationships. We can order the pattern to start with the node with the most restrictive filters (like label or property). But we can do a simple recursive join:
For each node variable in the pattern, we have a set of candidate nodes (initially all nodes that match the label and any simple property filters). But we can start with one variable.
This is a basic pattern matching engine.
Now, Explanation Tooling:
For each match, we want to generate an explanation. That could be as simple as listing the nodes and edges with their timestamps and amounts. For a triangle, we might say:
"User A sent XtoUserBatt1,UserBsentY to User C at t2, User C sent $Z to User A at t3. The total amount circulating is X+Y+Z. The time between first and last transaction is Δt."
We can have a template for each fraud pattern type. The query can specify a pattern name (like DETECT TRIANGLE FRAUD) and then the explanation generator knows the template. Alternatively, we can generate a generic explanation by printing the matched subgraph.
We'll design:
An ExplanationGenerator that takes a query and a match (binding of variables to nodes/edges) and produces a natural language description, possibly with a visualization (like a graph image). For visualization, we can output JSON in a format that a frontend can render (e.g., nodes and links with timestamps).
We'll also store the query and the match in a database for audit.
Caching:
We'll implement a multi-level cache:
EdgeCache: caches the result of edge queries for a given (start, end, edge_types, property_filters). Key: (start, end, edge_types_hash, property_filters_hash). Value: list of edges. TTL: if the window is entirely in the past beyond provisional_lateness, cache indefinitely; else, short TTL (e.g., 1 minute). Invalidation: when new edges arrive, we need to check if they belong to any cached window. We can maintain a reverse index: for each cached window, we have the max timestamp we have seen? Actually, we can set TTL based on window's end time: if window_end > now - provisional_lateness, then TTL = provisional_lateness - (now - window_end)? That's messy. Simpler: we don't cache recent windows; we only cache windows that are older than provisional_lateness. So we set a rule: when caching an edge query result, if window_end > now - provisional_lateness, we don't cache. So only historical windows are cached. Then we don't need invalidation because historical data won't change.
NodeCache: similar for nodes, but we cache by list of node IDs. Since node data rarely changes, we can cache longer.
PatternMatchCache: caches the final result of a query (list of matches) for a given query string and time window. Again, only for historical windows. This avoids re-running pattern matching if the same query is repeated. Key: (query_hash, start, end). TTL: indefinite for historical windows.
We'll also have a SubgraphCache that caches the built in-memory graph (nodes and adjacency lists) for a window. This can be reused by multiple queries on the same window. We can store the subgraph in a serialized form.
We'll implement a CacheManager that uses LRU with size limits.
System Architecture:
Components:
Ingestion API: receives events (node/edge additions) and writes to the storage (edge table, node table). Also appends to an event log for recovery and for real-time materialization? But we already store in tables.
Query API: receives a TGQL query, parses it, and executes.
Storage Layer: wraps the underlying database(s). Provides methods to fetch edges and nodes with filters.
Pattern Matching Library: implements various fraud pattern detectors.
Cache Manager: manages caches.
Explanation Generator: formats results.
Scheduler: maybe for running periodic queries (like every hour scan for new fraud). Not required but could be.
Scalability:
For large graphs, we might need to distribute the edge storage and processing. We could shard by time (each day on a different partition) or by node ID. For a single query, we might need to gather edges from multiple shards. But if we keep the window small, it might hit only a few shards.
For pattern matching, we could distribute by node ID: partition the graph and run pattern matching on each partition, then combine results (taking care of patterns that span partitions). That's complex. So we assume single-machine for now.
Implementation Details:
We'll choose a stack:
Storage: PostgreSQL with TimescaleDB extension for time-series on edges, and a separate table for nodes. Indexes: on edges (timestamp, type, src_id, dst_id). Partition by time (daily). Nodes table with primary key on id, and maybe index on label.
In-memory graph: use networkx or similar.
Query parsing: use ANTLR or a simple recursive descent parser for a small grammar.
Caching: use Redis or in-process LRU caches.
But we are designing, not coding.
Example Walkthrough:
Query: "Find all triangle frauds in the last 7 days where each transaction amount > 1000 and the cycle completes within 24 hours."
Steps:
Parse query: time window = last 7 days (start = now - 7d, end = now). Pattern: (a)-[e1:TRANSACTION]->(b)-[e2:TRANSACTION]->(c)-[e3:TRANSACTION]->(a). Conditions: e1.amount > 1000, e2.amount > 1000, e3.amount > 1000, e1.timestamp < e2.timestamp < e3.timestamp, e3.timestamp - e1.timestamp < 24h.
Check if window is historical: if now is current time, then end = now, so it includes provisional data. So we might not use cache for edge fetch or pattern match.
Fetch edges: SELECT * FROM edges WHERE timestamp >= start AND timestamp <= end AND type = 'TRANSACTION'. Possibly also filter amount > 1000? That can be pushed down: AND amount > 1000. So we add that to reduce data.
Fetch distinct node IDs from these edges, then fetch nodes with those IDs (maybe with label filter? none here).
Build graph: nodes dict, adjacency lists: for each node, list of outgoing edges (with dst, edge properties) and incoming edges.
Pattern matching:
For each node a (from nodes), explore outgoing edges e1 to b.
From b, outgoing edges e2 to c.
From c, outgoing edges e3 to a.
Check that a, b, c are distinct.
Check that timestamps: e1.ts < e2.ts < e3.ts and e3.ts - e1.ts < 24h.
If match, record (a,b,c,e1,e2,e3).
Return matches.
Generate explanation for each match: e.g., "Triangle fraud detected: User A (id:...) sent 500toUserBat1500 to User C at 10:05, User C sent 3200. Time span: 10 minutes."
Additional Features:
Alerting: The engine could be used to run queries periodically and generate alerts. That's a separate component that schedules queries and sends notifications.
Visualization: Provide a UI where analysts can run queries and see results as a graph.
Optimizations:
For pattern matching, we can pre-index edges by type and maybe by node degree to start with low-degree nodes.
For triangle detection, we can use a classic algorithm: for each edge (a,b), intersect the outgoing neighbor sets of b and a? Actually for directed triangle a->b->c->a, we can: for each edge (a,b), for each outgoing edge from b (b->c), check if there is an edge from c to a. That's O(E * d) where d is out-degree. We can improve by indexing outgoing edges by destination? We have adjacency lists, so for each (a,b) we look at b's outgoing edges and for each c, check if a is in c's outgoing adjacency? That's a lookup. Efficient if we have a set of neighbors for each node. So we can build a dictionary: for each node, set of outgoing neighbors. Then for each (a,b), for each c in out[b], check if a in out[c]. That's O(E * avg_out_degree). Could be heavy but okay for moderate graphs.
We can also filter by amount and time constraints early: during traversal, we only consider edges that satisfy amount>1000 (already filtered) and we can check temporal conditions after we have three edges.
For larger patterns, we might need more sophisticated algorithms.
Explanation Tooling:
We can provide:
A textual explanation as above.
A graph visualization: nodes and edges with timestamps as labels, maybe color-coded by amount.
cache.py: LRU caches for edges, nodes, subgraphs, query results. Use functools.lru_cache or Redis.
parser.py: Use ANTLR to parse TGQL? Might be overkill. We can start with a simple regex-based parser for a limited subset. Or we can avoid parsing by having the query be a Python function call? But we want a language. For prototype, we can support a subset: MATCH (a)-[e1:TRANSACTION]->(b)-[e2:TRANSACTION]->(c)-[e3:TRANSACTION]->(a) WHERE e1.amount > 1000 AND e2.amount > 1000 AND e3.amount > 1000 AND e1.timestamp < e2.timestamp AND e2.timestamp < e3.timestamp AND e3.timestamp - e1.timestamp < interval '24 hours' RETURN a,b,c,e1,e2,e3. That's basically Cypher with interval syntax. We can use an existing Cypher parser? There is cypher.
But to keep it simple, we can define our own simple format: maybe JSON-based query? Or we can directly implement a function call in Python that builds a query object. However, the requirement is a query language, so we need a textual language.
Given complexity, we can design a minimalistic language:
code
FIND pattern IN time_window
WITH edge_filter: "type='TRANSACTION' AND amount>1000"
NODE_FILTERS: "label='User'"
ORDER_BY timestamp
LIMIT 100
Not great.
Maybe we use a subset of Cypher and use an existing library like py2neo to parse? py2neo has a parser? I think neocons or cypher? There is a package cypher but not standard.
Alternatively, we can avoid full parser and define the query as a Python dictionary passed via JSON. That's acceptable for an API. The requirement says "query language", which could be a textual language or an API. We can say we provide a REST API that accepts JSON queries.
and then parse that string with a simple parser. That's like Cypher pattern.
I think for simplicity, we'll assume the query is a Cypher-like string and we use a third-party parser if available. Since this is a design, we can state we use a parser generator to parse a custom grammar.
But for the purpose of this answer, we don't need to implement; we just need to design.
Summary:
We propose a system with:
Storage: Time-partitioned edge table with indexes, node table.
Query Execution: Parse query, determine time window, fetch edges and nodes, build in-memory graph, run pattern matching, return results.
Caching: Cache edge fetch results for historical windows; cache query results for historical windows; possibly cache subgraphs.
Explanation: Generate textual and visual explanations for each match.
We also need to handle incremental updates: new edges are inserted into the edge table. The query engine reads the latest data on each query (or from cache if available and valid).
For real-time detection, we could also push-based: evaluate queries as new edges arrive. That's an alternative: we could maintain a stream processor that continuously evaluates pattern matching on the incoming edge stream and emits alerts. That might be more efficient for real-time. But the requirement says "incremental updates, query language, caching strategies, and explanation tooling." It doesn't specify push or pull. We can support both: pull-based queries on demand, and also a push-based alerting system that uses the same query engine.
For push-based, we can have a component that subscribes to new edges, updates an in-memory graph, and evaluates registered queries against new edges. But that's more complex. We'll stick to pull-based for now.
However, for fraud detection, real-time is important. So we should support both:
On-demand queries: analysts run ad-hoc queries.
Continuous queries: registered queries that run continuously as new data arrives and produce alerts.
We'll extend the engine to support continuous queries:
A continuous query is a TGQL query with a time window that is relative to now (e.g., last 5 minutes). As new edges arrive with timestamps in that window, we evaluate the query incrementally.
Implementation: We can maintain for each continuous query an in-memory graph that contains edges from the window. As new edges arrive, we add them to the graph and run the pattern matching incrementally: only check patterns that involve the new edge. For example, for triangle detection, when a new edge (a,b) arrives, we check if there exists b->c and c->a already in the graph. This incremental evaluation is more efficient than re-running the whole query.
We'll need:
A Continuous Query Manager that registers continuous queries.
It subscribes to the event stream (new edges) and for each new edge, updates the relevant query's in-memory graph and triggers pattern matching for patterns that could be affected.
It then emits alerts.
This is more advanced. But we can mention it as an extension.
Given the scope, we'll focus on the pull-based query engine and mention that continuous queries can be built using the same pattern matching logic in an incremental fashion.
Final Design:
Data Storage:
Table nodes: id (PK), label, properties (JSON), created_at (timestamp).
Check cache for subgraph (edges) for the window and filters. If hit, use cached subgraph; else, fetch edges from storage (with pushed-down filters) and cache if historical.
Fetch nodes in bulk.
Build in-memory graph (adjacency lists).
Run pattern matching: use backtracking to find all matches.
Apply aggregations if any.
Return results.
Cache Manager:
EdgeCache: LRU cache with key (start, end, edge_types, edge_property_filters). Value: list of edges.
NodeCache: LRU cache with key (tuple of node IDs). Value: list of nodes.
SubgraphCache: LRU cache with key (window, edge_types, node_labels) storing the built graph (nodes and adjacency). Can be derived from edges+nodes but avoids reconstructing.
QueryResultCache: LRU cache with key (query_hash, window) storing the final result list.
Eviction policy: LRU with max size (e.g., 1000 entries, or memory bound).
For windows that are not completely historical (i.e., end > now - provisional_lateness), we set a short TTL (e.g., 60 seconds) or bypass cache.
Explanation Generator:
For each match, creates a natural language description using a template based on the pattern type.
Also generates JSON for visualization.
Continuous Query Extension:
Register continuous query with a sliding window (e.g., last 5 minutes).
Maintain a materialized graph for that window (a sliding window over edges).
On each new edge, add to graph, remove edges older than window.
Run incremental pattern matching: for patterns like triangles, we can use algorithms that update counts when edges are added/removed.
We'll describe the incremental pattern matching for triangles:
code
Maintain for each ordered pair (x,y) the set of common successors z such that x->z and z->y exist? Actually for triangle x->y->z->x, we can maintain counts per directed pair. When an edge a->b arrives, we want to check if there is b->c and c->a. We can look for c in out[b] such that a in out[c]. So we need to quickly check if an edge exists from c to a. We can maintain a adjacency matrix or set of edges. For each candidate c from out[b], check if (c,a) in edges. That's O(out_degree(b)). If we have many such edges, we can index by destination: for each node, maintain a set of incoming neighbors? Actually, to check if there is an edge from c to a, we need to query the graph for edge c->a. So we can maintain a dictionary: for each node, set of nodes it points to. Then checking existence is O(1) per candidate. So we can do:
for each new edge (a,b):
for each c in out[b]:
if a in out[c]:
triangle (a,b,c) found with edges (a,b), (b,c), (c,a).
Also, we need to check temporal conditions: all three edges must be within the window. Since the window is sliding, we need to ensure that when an edge expires (older than window), we remove it and also invalidate triangles that included it. For continuous detection, we might only want to alert when a triangle is first completed. So we need to track triangles that are currently present. We can maintain a set of triangles and update on addition/removal.
This is doable.
But we won't go deeper.
Conclusion:
We have designed a temporal graph analytics engine for fraud detection with the following key aspects:
Incremental updates: new edges/nodes are appended to storage; queries read from storage (or caches) reflecting latest state.
Query language: TGQL, a Cypher-like language with temporal conditions and aggregations.
Caching: multi-level caches for edges, nodes, subgraphs, and query results, with policies to handle provisional data.
Explanation tooling: generates natural language and visual explanations for each match.
The system is designed for moderate-scale graphs with time windows of a few days, and can be extended to continuous query evaluation for real-time alerts.
We can also discuss scalability: for larger graphs, we can shard the edge table by time and node ID, and distribute pattern matching using a framework like Spark GraphX. But that's beyond the initial scope.
This design should meet the requirements.
Temporal Graph Analytics Engine for Fraud Detection
1. System Overview
A Temporal Graph Analytics Engine (TGAE) processes time-evolving graph data (users, transactions, devices) to detect fraud patterns. It supports incremental updates, expressive temporal queries, caching for low-latency responses, and explanations for detected fraud.
Core Components:
Storage Layer: Manages temporal graph data with efficient range queries.
Query Engine: Parses and executes temporal graph patterns.
Cache Manager: Accelerates repeated queries.
Explanation Module: Generates audit trails and visualizations.
Graph at time T: all nodes with created_at ≤ T and edges with timestamp ≤ T.
Provisional Period: Data with timestamps in (now - L, now] is considered provisional (subject to late arrivals). L = lateness threshold (e.g., 1 hour). Only snapshots older than L are immutable.
3. Storage Layer
Schema (PostgreSQL + TimescaleDB)
sql
CREATE TABLE nodes (
id TEXT PRIMARY KEY,
label TEXT NOT NULL,
properties JSONB,
created_at TIMESTAMPTZ NOT NULL
);
CREATE TABLE edges (
id TEXT PRIMARY KEY,
src_id TEXT REFERENCES nodes(id),
dst_id TEXT REFERENCES nodes(id),
type TEXT NOT NULL,
properties JSONB,
timestamp TIMESTAMPTZ NOT NULL
);
SELECT create_hypertable('edges', 'timestamp', chunk_time_interval => INTERVAL '1 day');
-- Indexes
CREATE INDEX idx_edges_timestamp ON edges(timestamp);
CREATE INDEX idx_edges_src_ts ON edges(src_id, timestamp);
CREATE INDEX idx_edges_dst_ts ON edges(dst_id, timestamp);
CREATE INDEX idx_edges_type_ts ON edges(type, timestamp);
CREATE INDEX idx_nodes_label ON nodes(label);
Incremental Updates
API: POST /ingest with batch of node/edge creations.
Processing: Append to tables; event log (Kafka) for recovery/continuous queries.
4. Query Language: Temporal Graph Query Language (TGQL)
Triangle Fraud (directed cycle, amounts > 1000, within 24h):
cypher
MATCH (a:User)-[e1:TRANSACTION]->(b:User)-[e2:TRANSACTION]->(c:User)-[e3:TRANSACTION]->(a)
WHERE e1.amount > 1000 AND e2.amount > 1000 AND e3.amount > 1000
AND e1.timestamp < e2.timestamp AND e2.timestamp < e3.timestamp
AND e3.timestamp - e1.timestamp < INTERVAL '24 HOURS'
RETURN a,b,c, e1,e2,e3
Largest Transaction Recipient (last 7 days):
cypher
MATCH (u:User)-[t:TRANSACTION]->(v)
WHERE t.timestamp >= NOW() - INTERVAL '7 DAYS'
RETURN v, SUM(t.amount) AS total, COUNT(*) AS cnt
ORDER BY total DESC LIMIT 10
In-Memory Graph: networkx (Python) or custom adjacency maps.
API: FastAPI (Python) or Spring Boot (Java).
Continuous Queries: Flink/Spark Streaming for large scale; custom in-process for moderate scale.
13. Limitations & Future Work
Graph Size: Assumes windowed subgraph fits in memory. For larger graphs, use distributed GraphX.
Pattern Matching Complexity: NP-hard; limited to small patterns (<5 hops). For larger patterns, use approximate or sampling.
Late Data: Provisonal window handles some lateness. For very late data, manual re-run required.
Concurrent Queries: Cache contention; use read replicas for storage.
This design provides a scalable, low-latency analytics engine for fraud detection with strong temporal support, caching, and explainability, ready for both ad-hoc analysis and real-time monitoring.
However, we need to ensure that the edges connect the nodes and their timestamps are within the window (already ensured) and any additional temporal conditions (like e1.timestamp < e2.timestamp) are satisfied.
We can do:
For each candidate for the first node (say a), get its outgoing edges of type TRANSACTION within the window (we have adjacency lists precomputed). For each such edge e1, get the target node b. Then check if b matches node pattern for b. Then for b, get outgoing edges of type TRANSACTION to c, etc.
This is like a path traversal.
For cycles, we need to ensure that the last edge connects back to the start.
We must also ensure that all variables are distinct (unless pattern allows reuse? usually not). We keep assignments of nodes to variables and avoid assigning the same node to two different variables unless the pattern allows (like a=b? not typically). So we enforce distinctness.
During traversal, we evaluate conditions that involve multiple edges (like timestamp comparisons). That's fine.
Complexity: worst-case exponential in pattern size, but pattern size is small (<5). And the degree of nodes might be high, but we can prune by property conditions.
After finding all matches, we either return the raw matches (list of bindings) or aggregate (group by some variables and compute sums, counts, etc.). For aggregation, we can accumulate during the search or after.
Return results.
10
:
00,UserBsent
1200toUserAat10:10.Totalamount:
Cache the subgraph (edges) for this window? Since window includes current time, we might not cache. Or cache with TTL=1 minute.
Cache the query result? Not for this window because it changes.