Sr. Manager, Technical Product Marketing, Neo4j
17 min read
Follow along on github
Somewhere in a bank right now, a few customer accounts are being hijacked. An attacker reset a password, logged in from a device the customer has never used, added a new payee, and is about to move money.
The tricky part is that no single step gives an attack away. Customers get new phones, make large transfers, and add payees all the time. What stands out is the sequence and how recent it is, and that’s where most approaches struggle. Supervised models need plenty of labeled takeovers to learn from, and you only have 30. Most graph embeddings tell you who’s connected to whom, but not what happened in which order.
FastPath, a node embedding algorithm now available in Aura Graph Analytics, works with the sequence itself. It gives recent events more weight and measures time relative to each account, so an attack from three weeks ago can be compared directly with one happening right now.
In this post, you’ll try FastPath on a synthetic graph of 2,000 bank accounts and about 48,000 events, including 30 accounts already confirmed as takeovers. You’ll embed each account’s recent activity, compare the active accounts to the confirmed takeovers, see how many live takeovers it surfaces, and then use the graph to figure out why an account was flagged.
Most graph embeddings capture structure, meaning who’s connected to whom. FastPath captures sequences. For each node you want to embed (the base node), it looks at that node’s events, like logins, purchases, or sensor readings, and adds up their contributions into one fixed-length vector. Each node is embedded as of a snapshot time (called its observation time in the code), and four ideas shape that vector:
- Recent events count more: Each event is weighted by how old it is (using an exponential decay), so what happened in the last few hours matters more than what happened last week.
- Each node gets its own snapshot time: You choose the moment each node is looked at as of. That lets you freeze the picture at a meaningful point, like just after something you already know happened, or at the present moment for everything else. In our example, the 30 confirmed takeovers are looked at as of just after the attack, and every other account, including the 12 live takeovers, is looked at as of now.
- Time is measured from that snapshot: FastPath doesn’t care what day an event happened, only how long before the snapshot it happened. So two nodes whose events played out the same way look alike, even if one story happened weeks ago and the other is happening now. In our example, that’s what lets an attack from three weeks ago be compared directly with one happening today.
- Events carry context: Each event can point to context nodes (like a device, a location, or a product), and it can carry a categorical type and a numeric feature vector.
The notebook loads a synthetic retail-banking graph with 2,000 accounts and about 48,000 events over a 30-day window. Every account has a sequence of events, and each event can point to the device, IP address, and payee involved:
Three kinds of accounts matter here:
- 30 confirmed takeovers: attacks that wrapped up earlier in the month. Each one’s observationTime sits just after its last fraudulent event, so its embedding captures the lead-up to the attack. These are our reference set.
- 12 live takeovers: attacks happening right now, still labeled active. About half haven’t cashed out yet. These are the accounts we’re trying to find.
- 300 decoys: legitimate customers who look a bit like an attack, like someone who got a new phone after a password reset, made a big transfer to a known payee, or added a new payee and then paid them. They’re what makes this hard.
Every account also has two held-out columns, isTakeover and scenario. We never give them to the algorithm. They’re only there at the end so we can check our answers.
In this example, we will be using the python client, but everything you see here can be done in cypher. Import graphdatascience (v2.0 or higher):
import graphdatascience
print(graphdatascience.__version__)
2.2
Then load your credentials. Copy .env.example to .env and fill in these values.
import os
from dotenv import load_dotenv
load_dotenv()
TENANT_ID = os.environ["TENANT_ID"]
NEO4J_URI = os.environ["NEO4J_URI"]
NEO4J_USERNAME = os.environ.get("NEO4J_USERNAME", "neo4j")
NEO4J_PASSWORD = os.environ["NEO4J_PASSWORD"]
CLIENT_SECRET = os.environ["CLIENT_SECRET"]
CLIENT_ID = os.environ["CLIENT_ID"]
First estimate the amount of memory needed by Aura Graph Analytics:
from graphdatascience.session import GdsSessions, AuraAPICredentials, DbmsConnectionInfo, AlgorithmCategory
import numpy as np
import pandas as pd
from datetime import timedelta
sessions = GdsSessions(api_credentials=AuraAPICredentials(CLIENT_ID, CLIENT_SECRET, TENANT_ID))
memory = sessions.estimate(
node_count=55_000, relationship_count=160_000,
algorithms=["fast_path"]
)
db_connection_info = DbmsConnectionInfo(NEO4J_URI, NEO4J_USERNAME, NEO4J_PASSWORD)
And then start the session:
session_name = "fastpath-takeover-demo"
gds = sessions.get_or_create(
session_name,
memory=memory,
db_connection=db_connection_info,
ttl=timedelta(hours=2),
)
print("GDS session initialized.")
Use load.cypher to load in the CSVs from the repo.
from pathlib import Path
script = Path("load.cypher").read_text()
statements = [s.strip() for s in script.split(";") if s.strip()]
for statement in statements:
gds.run_cypher(statement)
print(f"Ran {len(statements)} statements.")
A quick count by label tells us everything landed.
gds.run_cypher("""
MATCH (n)
RETURN labels(n) AS labels, count(*) AS nodes
ORDER BY nodes DESC
""")
labels nodes
0 [Event] 48665
1 [Device, Context] 2593
2 [Account] 2000
3 [IPAddress, Context] 1131
4 [Payee, Context] 604
Those 48,665 events are the sequences FastPath will embed. The devices, IP addresses, and payees all share a Context label, and we’ll use it when we project the graph.
Break the accounts down #
This cell groups the accounts by status, scenario, and the held-out isTakeover flag.
gds.run_cypher("""
MATCH (a:Account)
RETURN a.status AS status, a.scenario AS scenario, a.isTakeover AS isTakeover, count(*) AS accounts
ORDER BY isTakeover DESC, status, accounts DESC
""")
The first rows of the result show the three attack scenarios in the data, takeover_classic, takeover_nocreds and takeover_slowburn. The 30 confirmed takeovers (15, 8 and 7 across those scenarios) have the status confirmed_takeover.
We also planted 12 live takeovers in the synthetic data (6, 3 and 3 across the same scenarios), which we hope to uncover with FastPath. They have the status active, the same as the 1,658 normal accounts, so a filter on status can’t find them.
The last 12 hours of one takeover
Before we run any algorithm, it helps to see what an attack looks like. This query grabs one confirmed takeover_classic account, A0096, and lists its events in the 12 hours before its observation time, along with the device and payee on each one.
gds.run_cypher("""
MATCH (a:Account {scenario: 'takeover_classic', status: 'confirmed_takeover'})
WITH a ORDER BY a.accountId LIMIT 1
MATCH (a)-[:HAS_EVENT]->(e:Event)
WHERE e.timestamp >= a.observationTime - 12
OPTIONAL MATCH (e)-[:USED_DEVICE]->(d:Device)
OPTIONAL MATCH (e)-[:TO_PAYEE]->(p:Payee)
RETURN a.accountId AS account, round(e.timestamp, 1) AS hour, e.eventType AS event,
e.amount AS amount, d.deviceId AS device, p.payeeId AS payee
ORDER BY e.timestamp
""")
account hour event amount device payee
0 A0096 478.7 PASSWORD_RESET 0.00 D00815 NaN
1 A0096 478.8 LOGIN 0.00 D00815 NaN
2 A0096 479.2 PAYEE_ADDED 0.00 D00815 PAY0609
3 A0096 479.4 TRANSFER 2614.52 D00815 PAY0609
It’s a pretty classic pattern in fraud: a password reset from a device the customer never used, a new payee added within hours, then a large transfer to that payee. The whole thing takes under an hour. (Timestamps here are hours since the start of the 30-day window.)
FastPath runs inside the GDS session, so we first copy over the parts of the graph it needs:
- Accounts, with the
observationTimewe picked for each one. - Events, with a timestamp, a number for the event type (like login or transfer), and the amount and time of day as numbers.
- Context nodes, the devices, IP addresses, and payees that events touch.
Events point to their context nodes, which is the direction FastPath expects. The cell below sends two sets of rows to the session, account-to-event and event-to-context, and the session assembles them into the projection.
gds.graph.drop("takeover-graph", fail_if_missing=False)
G, result = gds.graph.project.cypher(
graph_name="takeover-graph",
query="""
CALL () {
MATCH (a:Account)-[r:HAS_EVENT]->(e:Event)
RETURN a AS source, r AS rel, e AS target,
['Account'] AS sourceLabels, ['Event'] AS targetLabels,
a { .observationTime } AS sourceNodeProperties,
e { .timestamp, .eventTypeCode, .features } AS targetNodeProperties
UNION
MATCH (e:Event)-[r:USED_DEVICE|FROM_IP|TO_PAYEE]->(c:Context)
RETURN e AS source, r AS rel, c AS target,
['Event'] AS sourceLabels, ['Context'] AS targetLabels,
e { .timestamp, .eventTypeCode, .features } AS sourceNodeProperties,
{} AS targetNodeProperties
}
RETURN gds.graph.project.remote(source, target, {
sourceNodeLabels: sourceLabels,
targetNodeLabels: targetLabels,
sourceNodeProperties: sourceNodeProperties,
targetNodeProperties: targetNodeProperties,
relationshipType: type(rel),
relationshipProperties: properties(rel)
})
""",
)
print(result)
graph_name='takeover-graph' node_count=54993 relationship_count=159002 project_millis=1361 ...
That gives us a projection with 54,993 nodes and 159,002 relationships
How do I tune FastPath? #
FastPath cares about the order of events and when they happened, so tuning oftentime means adjusting how it handles time. There’s no formula for the right values, since they depend on how fast things happen in your data, but three settings did most of the work for us.
lookback_horizonis how far back from the observation time an event can be and still count. Older events are ignored. We matched it to the attacks we’re after: 48 hours for fast ones and 7 days for slow ones.decay_rateis how quickly older events fade within that window. Higher values make recent events count for more. We used 0.1 for the 48-hour run and 0.5 for the 7-day run, both from a sweep on this dataset.num_time_anchorsis how many buckets the lookback window is split into. Events count as related when they land in the same bucket. Let’s walk through a simplified example. With a 12-hour window and 4 buckets, each bucket is 3 hours wide. A password reset 1 hour before one account’s observation time and one 2 hours before another’s would land in the same bucket and look alike. With too many buckets, the same attack looks different from one account to the next. With too few, different attacks blur together. We tried a range of values, found that 3 to 5 worked well, and went with 4.- Additionally, you have the option to smooth the buckets with
smoothing_rateandsmoothing_window, which spreads each event across neighboring time points so it belongs partly to several instead of just one.
- Additionally, you have the option to smooth the buckets with
- Additionally, you have the option to smooth the buckets with
We run FastPath twice so we can catch both fast and slow attacks. fastPathShort looks back 48 hours, which suits attacks that play out over hours to a day. fastPathLong looks back 7 days, which suits slow burns, where the attacker resets the password and then waits days before cashing out.
COMMON = dict(
base_node_label="Account",
event_node_label="Event",
context_node_label="Context",
event_node_time_property="timestamp",
event_node_categorical_properties=["eventTypeCode"],
event_node_feature_vector_property="features",
base_node_observation_time_property="observationTime",
embedding_dimension=128,
random_seed=42,
)
short = gds.fast_path.mutate(
G, mutate_property="fastPathShort",
lookback_horizon=48, num_time_anchors=4, decay_rate=0.1,
**COMMON,
)
long = gds.fast_path.mutate(
G, mutate_property="fastPathLong",
lookback_horizon=168, num_time_anchors=4, decay_rate=0.5,
**COMMON,
)
print(f"short: {short.node_count} accounts embedded in {short.compute_millis} ms")
print(f"long: {long.node_count} accounts embedded in {long.compute_millis} ms")
short: 2000 accounts embedded in 21399 ms
long: 2000 accounts embedded in 21692 ms
Next, we pull the embeddings back into the notebook. Each account now has a list of 128 numbers that summarizes its recent activity, tagged with its account ID so we know whose is whose. We also scale every list to the same length, which makes comparing two accounts a quick calculation.
DB_PROPS = ["accountId", "status", "isTakeover", "scenario"]
def account_embeddings(prop):
df = gds.graph.node_properties.stream(
G, [prop], node_labels=["Account"], db_node_properties=DB_PROPS
)
value_col = prop if prop in df.columns else "propertyValue"
df = df.sort_values("accountId").reset_index(drop=True)
emb = np.vstack(df[value_col].to_numpy()).astype(float)
emb /= np.clip(np.linalg.norm(emb, axis=1, keepdims=True), 1e-9, None) # unit length, so a dot product is cosine similarity
return df[DB_PROPS], emb
accounts, E_short = account_embeddings("fastPathShort")
_, E_long = account_embeddings("fastPathLong")
print(E_short.shape, E_long.shape)
accounts.head()
(2000, 128) (2000, 128)
accountId status isTakeover scenario
0 A0000 active 0 new_payee
1 A0001 active 0 new_phone
2 A0002 active 0 new_payee
3 A0003 active 0 normal
4 A0004 active 0 normal
Every account that’s still active gets a score for how closely it resembles our 30 confirmed takeovers. To get it, we find the account’s three closest matches among those takeovers and average how similar they are. We stop at the closest few because there are several kinds of attack, and an account only needs to look like one of them. We score the short and long embeddings separately, then average the two into a combined score.
K = 3
confirmed = (accounts["status"] == "confirmed_takeover").to_numpy()
def lookalike_score(E):
sims = E[~confirmed] @ E[confirmed].T
return np.sort(sims, axis=1)[:, -K:].mean(axis=1)
candidates = accounts[~confirmed].copy()
candidates["short"] = lookalike_score(E_short)
candidates["long"] = lookalike_score(E_long)
candidates["combined"] = (candidates["short"] + candidates["long"]) / 2
candidates.sort_values("combined", ascending=False).head(15)
accountId status isTakeover scenario short long
572 A0572 active 1 takeover_classic 0.736379 0.723118
929 A0929 active 1 takeover_classic 0.716196 0.703022
867 A0867 active 1 takeover_nocreds 0.707109 0.665324
1424 A1424 active 1 takeover_classic 0.637824 0.657934
1223 A1223 active 1 takeover_slowburn 0.657079 0.637297
1740 A1740 active 1 takeover_slowburn 0.617797 0.604350
689 A0689 active 1 takeover_slowburn 0.570520 0.554344
214 A0214 active 1 takeover_nocreds 0.532960 0.544948
427 A0427 active 0 normal 0.556364 0.511296
946 A0946 active 1 takeover_classic 0.534624 0.518814
1949 A1949 active 0 normal 0.524020 0.525003
665 A0665 active 1 takeover_nocreds 0.534463 0.513843
The top eight accounts are all live takeovers, covering all three attack scenarios. The first ordinary account shows up at rank 9.
Now we bring in the held-out isTakeover column. There are 12 live takeovers hidden among 1,970 active accounts, plus 300 decoys built to throw off the search. For each embedding, this cell counts how many real takeovers land in the top 12 and the top 25, and how many decoys land in the top 25.
def evaluate(col):
ranked = candidates.sort_values(col, ascending=False)
return {
"takeovers in top 12": int(ranked.head(12)["isTakeover"].sum()),
"takeovers in top 25": int(ranked.head(25)["isTakeover"].sum()),
"decoys in top 25": int((ranked.head(25)["scenario"].isin(["new_phone", "big_transfer", "new_payee"])).sum()),
}
pd.DataFrame({name: evaluate(name) for name in ["short", "long", "combined"]}).T
takeovers in top 12 takeovers in top 25 decoys in top 25
short 10 10 0
long 9 10 0
combined 10 10 0
We ranked every active account by its score, so the ones that look most like the confirmed takeovers sit at the top. Of the 12 highest-scoring accounts, 10 are live takeovers when we use the short lookback or the combined score, and 9 are with the long lookback alone.
Picking 12 accounts at random would find well under one. For a fraud team, that means reviewing a dozen accounts out of nearly 2,000 and catching most of the attacks in progress. None of the 25 highest-scoring accounts were decoys, so everyday behavior like a new phone or a big transfer doesn’t flood the queue with false alarms. It isn’t perfect.
What shows up in the top 25 #
This cell counts which scenarios show up in the top 25 of the combined ranking.
top25 = candidates.sort_values("combined", ascending=False).head(25)
top25["scenario"].value_counts().to_frame("accounts")
accounts
scenario
normal 15
takeover_classic 4
takeover_nocreds 3
takeover_slowburn 3
The top 25 holds 10 live takeovers across all three attack types, along with 15 ordinary accounts and no decoys. The ranking still works best as a prioritized list for an analyst to work through.
A score tells an analyst which account to look at, but “similarity 0.73” isn’t something they can act on. They still need a reason they can check, and fortunately, our graph can supply that reason.
For the highest-scoring account, the query below finds the devices, IP addresses, and payees it shares with confirmed takeovers and counts how many confirmed takeovers touched each one. That gives the analyst something concrete, like a payee that several confirmed takeovers also used. It’s a lead they can investigate, not just a number.
flagged = candidates.sort_values("combined", ascending=False).iloc[0]["accountId"]
print("Highest-scoring account:", flagged)
gds.run_cypher("""
MATCH (a:Account {accountId: $flagged})-[:HAS_EVENT]->(:Event)-[:USED_DEVICE|FROM_IP|TO_PAYEE]->(c:Context)
MATCH (c)<-[:USED_DEVICE|FROM_IP|TO_PAYEE]-(:Event)<-[:HAS_EVENT]-(other:Account {status: 'confirmed_takeover'})
WHERE other <> a
RETURN [l IN labels(c) WHERE l <> 'Context'][0] AS sharedType,
coalesce(c.deviceId, c.ipAddress, c.payeeId) AS sharedWith,
count(DISTINCT other) AS confirmedTakeoversSharingIt
ORDER BY confirmedTakeoversSharingIt DESC
""", params={"flagged": flagged})
Highest-scoring account: A0572
sharedType sharedWith confirmedTakeoversSharingIt
0 IPAddress 163.192.185.247 7
1 IPAddress 153.119.227.164 6
2 Device D00645 6
3 IPAddress 46.201.62.239 4
4 Payee PAY0313 4
5 IPAddress 49.224.56.184 2
6 IPAddress 44.184.78.40 2
7 IPAddress 119.203.241.212 1
A0572 shares one IP address with seven confirmed takeovers, another with six, and a device with six. Attackers reuse infrastructure across victims, and that overlap is part of what the embeddings picked up. It also gives an analyst something concrete to act on: block the shared IP address, or review every account that touched that device.
We embedded 2,000 accounts from their event sequences, with no labeled training data and no model to train, and used 30 confirmed takeovers as a reference to find look-alikes still in flight. Three things made that possible:
- Time-relative embeddings. We embedded past attacks as of the moment they were caught and live accounts as of now, so we could compare them directly.
- Recency weighting. What an account did in the last few hours dominates its vector, which is what you want when an attack is happening now.
- Context nodes. Devices, IP addresses, and payees feed into the embedding, so shared attacker infrastructure counts as evidence alongside the event sequence.
Because each account is embedded independently, you can run FastPath on a schedule over only the accounts with new events, and the new vectors stay comparable with the old ones.
Ready to try it? Aura Graph Analytics is available for AuraDB Free. To get started, create an Aura Graph Analytics session from the Aura Console, put your credentials in .env, and run the notebook. Or get started with AGA via Graph Academy. The FastPath documentation covers every parameter we used, and the GDS Python Client tutorials go deeper on session setup.