Catching Account Takeovers Mid-Attack with FastPath Neo4j released FastPath, a node embedding algorithm now available in Aura Graph Analytics, which weights recent events more heavily and measures time relative to each account's snapshot so an attack from three weeks ago can be compared directly with one happening now. Neo4j demonstrated FastPath on a synthetic retail-banking graph of 2,000 accounts and about 48,000 events over a 30-day window, including 30 confirmed takeovers used as a reference set, 12 live takeovers the method tries to surface, and 300 decoys that resemble attacks. The approach targets account takeover detection where supervised models lack labeled examples and standard graph embeddings capture who is connected to whom but not the order in which events occurred. Catching Account Takeovers Mid-Attack with FastPath Sr. Manager, Technical Product Marketing, Neo4j 17 min read Follow along on github https://github.com/neo4j-product-examples/aura-graph-analytics/tree/main/account takeover 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 https://neo4j.com/docs/aura/graph-analytics/aga/ , 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. What FastPath is 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 data 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. Setting up Aura Graph Analytics 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 : python import graphdatascience print graphdatascience. version 2.2 Then load your credentials. Copy .env.example to .env and fill in these values. python import os from dotenv import load dotenv load dotenv This credential is the Organization ID TENANT ID = os.environ "TENANT ID" These credentials were generated after the creation of the Aura Instance NEO4J URI = os.environ "NEO4J URI" NEO4J USERNAME = os.environ.get "NEO4J USERNAME", "neo4j" NEO4J PASSWORD = os.environ "NEO4J PASSWORD" These credentials were generated after the creation of the API Endpoint CLIENT SECRET = os.environ "CLIENT SECRET" CLIENT ID = os.environ "CLIENT ID" First estimate the amount of memory needed by Aura Graph Analytics: python 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" Initialize a GDS session scoped for 2 hours, sized to estimated graph gds = sessions.get or create session name, memory=memory, db connection=db connection info, ttl=timedelta hours=2 , print "GDS session initialized." Loading the data Use load.cypher to load in the CSVs from the repo. python 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. Looking at an attack before modeling it 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. Projecting the graph into the session FastPath runs inside the GDS session, so we first copy over the parts of the graph it needs: - Accounts, with the observationTime we 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 horizon is 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 rate is 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 anchors is 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 rate and smoothing 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 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 Pulling the embeddings back 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 Finding accounts that look like past takeovers 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. Checking the answer 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. python 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. Why was this account flagged? 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. Wrap-up 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 https://console.neo4j.io/ , put your credentials in .env, and run the notebook. Or get started with AGA via Graph Academy https://graphacademy.neo4j.com/courses/aga-fundamentals . The FastPath documentation https://neo4j.com/docs/graph-data-science/current/machine-learning/node-embeddings/fastpath/ covers every parameter we used, and the GDS Python Client tutorials https://neo4j.com/docs/graph-data-science-client/current/tutorials/graph-analytics-serverless-standalone-fastpath/ go deeper on session setup.