{"slug": "catching-account-takeovers-mid-attack-with-fastpath", "title": "Catching Account Takeovers Mid-Attack with FastPath", "summary": "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.", "body_md": "# Catching Account Takeovers Mid-Attack with FastPath\n\nSr. Manager, Technical Product Marketing, Neo4j\n\n17 min read\n\n*Follow along on [github](https://github.com/neo4j-product-examples/aura-graph-analytics/tree/main/account_takeover)*\n\nSomewhere 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.\n\nThe 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.\n\nFastPath, 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.\n\nIn 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.\n\n# What FastPath is\n\nMost 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:\n\n- **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.\n- **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.\n- **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.\n- **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.\n\n# The data\n\nThe 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:\n\nThree kinds of accounts matter here:\n\n- 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.\n- 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.\n- 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.\n\nEvery 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.\n\n# Setting up Aura Graph Analytics\n\nIn 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):\n\n``` python\nimport graphdatascience\nprint(graphdatascience.__version__)\n2.2\n```\n\nThen load your credentials. Copy .env.example to .env and fill in these values.\n\n``` python\nimport os\n\nfrom dotenv import load_dotenv\n\nload_dotenv()\n\n# This credential is the Organization ID\n\nTENANT_ID = os.environ[\"TENANT_ID\"]\n\n# These credentials were generated after the creation of the Aura Instance\n\nNEO4J_URI = os.environ[\"NEO4J_URI\"]\n\nNEO4J_USERNAME = os.environ.get(\"NEO4J_USERNAME\", \"neo4j\")\n\nNEO4J_PASSWORD = os.environ[\"NEO4J_PASSWORD\"]\n\n# These credentials were generated after the creation of the API Endpoint\n\nCLIENT_SECRET = os.environ[\"CLIENT_SECRET\"]\n\nCLIENT_ID = os.environ[\"CLIENT_ID\"]\n```\n\nFirst estimate the amount of memory needed by Aura Graph Analytics:\n\n``` python\nfrom graphdatascience.session import GdsSessions, AuraAPICredentials, DbmsConnectionInfo, AlgorithmCategory\nimport numpy as np\nimport pandas as pd\nfrom datetime import timedelta\n\nsessions = GdsSessions(api_credentials=AuraAPICredentials(CLIENT_ID, CLIENT_SECRET, TENANT_ID))\n\nmemory = sessions.estimate(\n    node_count=55_000, relationship_count=160_000,\n    algorithms=[\"fast_path\"]\n)\n\ndb_connection_info = DbmsConnectionInfo(NEO4J_URI, NEO4J_USERNAME, NEO4J_PASSWORD)\n```\n\nAnd then start the session:\n\n```\nsession_name = \"fastpath-takeover-demo\"\n\n# Initialize a GDS session scoped for 2 hours, sized to estimated graph\ngds = sessions.get_or_create(\n    session_name,\n    memory=memory,\n    db_connection=db_connection_info,\n    ttl=timedelta(hours=2),\n)\n\nprint(\"GDS session initialized.\")\n```\n\n# Loading the data\n\nUse load.cypher to load in the CSVs from the repo.\n\n``` python\nfrom pathlib import Path\n\nscript = Path(\"load.cypher\").read_text()\nstatements = [s.strip() for s in script.split(\";\") if s.strip()]\n\nfor statement in statements:\n    gds.run_cypher(statement)\n\nprint(f\"Ran {len(statements)} statements.\")\n```\n\nA quick count by label tells us everything landed.\n\n```\ngds.run_cypher(\"\"\"\nMATCH (n)\nRETURN labels(n) AS labels, count(*) AS nodes\nORDER BY nodes DESC\n\"\"\")\nlabels  nodes\n0               [Event]  48665\n1     [Device, Context]   2593\n2             [Account]   2000\n3  [IPAddress, Context]   1131\n4      [Payee, Context]    604\n```\n\nThose 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.\n\n## Break the accounts down\n\nThis cell groups the accounts by status, scenario, and the held-out isTakeover flag.\n\n```\ngds.run_cypher(\"\"\"\nMATCH (a:Account)\nRETURN a.status AS status, a.scenario AS scenario, a.isTakeover AS isTakeover, count(*) AS accounts\nORDER BY isTakeover DESC, status, accounts DESC\n\"\"\")\n```\n\nThe 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`. \n\nWe 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.\n\n# Looking at an attack before modeling it\n\n#### The last 12 hours of one takeover\n\nBefore 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.\n\n```\ngds.run_cypher(\"\"\"\nMATCH (a:Account {scenario: 'takeover_classic', status: 'confirmed_takeover'})\nWITH a ORDER BY a.accountId LIMIT 1\nMATCH (a)-[:HAS_EVENT]->(e:Event)\nWHERE e.timestamp >= a.observationTime - 12\nOPTIONAL MATCH (e)-[:USED_DEVICE]->(d:Device)\nOPTIONAL MATCH (e)-[:TO_PAYEE]->(p:Payee)\nRETURN a.accountId AS account, round(e.timestamp, 1) AS hour, e.eventType AS event,\n       e.amount AS amount, d.deviceId AS device, p.payeeId AS payee\nORDER BY e.timestamp\n\"\"\")\naccount   hour           event   amount  device    payee\n0   A0096  478.7  PASSWORD_RESET     0.00  D00815      NaN\n1   A0096  478.8           LOGIN     0.00  D00815      NaN\n2   A0096  479.2     PAYEE_ADDED     0.00  D00815  PAY0609\n3   A0096  479.4        TRANSFER  2614.52  D00815  PAY0609\n```\n\nIt’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.)\n\n# Projecting the graph into the session\n\nFastPath runs inside the GDS session, so we first copy over the parts of the graph it needs:\n\n- Accounts, with the `observationTime` we picked for each one.\n- Events, with a timestamp, a number for the event type (like login or transfer), and the amount and time of day as numbers.\n- Context nodes, the devices, IP addresses, and payees that events touch.\n\nEvents 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.\n\n```\ngds.graph.drop(\"takeover-graph\", fail_if_missing=False)\n\nG, result = gds.graph.project.cypher(\n    graph_name=\"takeover-graph\",\n    query=\"\"\"\n    CALL () {\n        MATCH (a:Account)-[r:HAS_EVENT]->(e:Event)\n        RETURN a AS source, r AS rel, e AS target,\n               ['Account'] AS sourceLabels, ['Event'] AS targetLabels,\n               a { .observationTime } AS sourceNodeProperties,\n               e { .timestamp, .eventTypeCode, .features } AS targetNodeProperties\n        UNION\n        MATCH (e:Event)-[r:USED_DEVICE|FROM_IP|TO_PAYEE]->(c:Context)\n        RETURN e AS source, r AS rel, c AS target,\n               ['Event'] AS sourceLabels, ['Context'] AS targetLabels,\n               e { .timestamp, .eventTypeCode, .features } AS sourceNodeProperties,\n               {} AS targetNodeProperties\n    }\n    RETURN gds.graph.project.remote(source, target, {\n      sourceNodeLabels: sourceLabels,\n      targetNodeLabels: targetLabels,\n      sourceNodeProperties: sourceNodeProperties,\n      targetNodeProperties: targetNodeProperties,\n      relationshipType: type(rel),\n      relationshipProperties: properties(rel)\n    })\n    \"\"\",\n)\n\nprint(result)\ngraph_name='takeover-graph' node_count=54993 relationship_count=159002 project_millis=1361 ...\n```\n\nThat gives us a projection with 54,993 nodes and 159,002 relationships\n\n## How do I tune FastPath?\n\nFastPath 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.\n\n- `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.\n- `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.\n- `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.\n  - 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.\n- Additionally, you have the option to smooth the buckets with \n\nWe 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.\n\n```\nCOMMON = dict(\n    base_node_label=\"Account\",\n    event_node_label=\"Event\",\n    context_node_label=\"Context\",\n    event_node_time_property=\"timestamp\",\n    event_node_categorical_properties=[\"eventTypeCode\"],\n    event_node_feature_vector_property=\"features\",\n    base_node_observation_time_property=\"observationTime\",\n    embedding_dimension=128,\n    random_seed=42,\n)\n\nshort = gds.fast_path.mutate(\n    G, mutate_property=\"fastPathShort\",\n    lookback_horizon=48, num_time_anchors=4, decay_rate=0.1,\n    **COMMON,\n)\n\nlong = gds.fast_path.mutate(\n    G, mutate_property=\"fastPathLong\",\n    lookback_horizon=168, num_time_anchors=4, decay_rate=0.5,\n    **COMMON,\n)\n\nprint(f\"short: {short.node_count} accounts embedded in {short.compute_millis} ms\")\nprint(f\"long:  {long.node_count} accounts embedded in {long.compute_millis} ms\")\nshort: 2000 accounts embedded in 21399 ms\nlong:  2000 accounts embedded in 21692 ms\n```\n\n# Pulling the embeddings back\n\nNext, 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.\n\n```\nDB_PROPS = [\"accountId\", \"status\", \"isTakeover\", \"scenario\"]\n\ndef account_embeddings(prop):\n    df = gds.graph.node_properties.stream(\n        G, [prop], node_labels=[\"Account\"], db_node_properties=DB_PROPS\n    )\n    value_col = prop if prop in df.columns else \"propertyValue\"\n    df = df.sort_values(\"accountId\").reset_index(drop=True)\n    emb = np.vstack(df[value_col].to_numpy()).astype(float)\n    emb /= np.clip(np.linalg.norm(emb, axis=1, keepdims=True), 1e-9, None)  # unit length, so a dot product is cosine similarity\n    return df[DB_PROPS], emb\n\naccounts, E_short = account_embeddings(\"fastPathShort\")\n_, E_long = account_embeddings(\"fastPathLong\")\n\nprint(E_short.shape, E_long.shape)\naccounts.head()\n(2000, 128) (2000, 128)\n\n  accountId  status  isTakeover   scenario\n0     A0000  active           0  new_payee\n1     A0001  active           0  new_phone\n2     A0002  active           0  new_payee\n3     A0003  active           0     normal\n4     A0004  active           0     normal\n```\n\n# Finding accounts that look like past takeovers\n\nEvery 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.\n\n```\nK = 3\nconfirmed = (accounts[\"status\"] == \"confirmed_takeover\").to_numpy()\n\ndef lookalike_score(E):\n    sims = E[~confirmed] @ E[confirmed].T\n    return np.sort(sims, axis=1)[:, -K:].mean(axis=1)\n\ncandidates = accounts[~confirmed].copy()\ncandidates[\"short\"] = lookalike_score(E_short)\ncandidates[\"long\"] = lookalike_score(E_long)\ncandidates[\"combined\"] = (candidates[\"short\"] + candidates[\"long\"]) / 2\n\ncandidates.sort_values(\"combined\", ascending=False).head(15)\naccountId  status  isTakeover           scenario     short      long\n572      A0572  active           1   takeover_classic  0.736379  0.723118\n929      A0929  active           1   takeover_classic  0.716196  0.703022\n867      A0867  active           1   takeover_nocreds  0.707109  0.665324\n1424     A1424  active           1   takeover_classic  0.637824  0.657934\n1223     A1223  active           1  takeover_slowburn  0.657079  0.637297\n1740     A1740  active           1  takeover_slowburn  0.617797  0.604350\n689      A0689  active           1  takeover_slowburn  0.570520  0.554344\n214      A0214  active           1   takeover_nocreds  0.532960  0.544948\n427      A0427  active           0             normal  0.556364  0.511296\n946      A0946  active           1   takeover_classic  0.534624  0.518814\n1949     A1949  active           0             normal  0.524020  0.525003\n665      A0665  active           1   takeover_nocreds  0.534463  0.513843\n```\n\nThe top eight accounts are all live takeovers, covering all three attack scenarios. The first ordinary account shows up at rank 9.\n\n# Checking the answer\n\nNow 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.\n\n``` python\ndef evaluate(col):\n    ranked = candidates.sort_values(col, ascending=False)\n    return {\n        \"takeovers in top 12\": int(ranked.head(12)[\"isTakeover\"].sum()),\n        \"takeovers in top 25\": int(ranked.head(25)[\"isTakeover\"].sum()),\n        \"decoys in top 25\": int((ranked.head(25)[\"scenario\"].isin([\"new_phone\", \"big_transfer\", \"new_payee\"])).sum()),\n    }\n\npd.DataFrame({name: evaluate(name) for name in [\"short\", \"long\", \"combined\"]}).T\ntakeovers in top 12  takeovers in top 25  decoys in top 25\nshort                      10                   10                 0\nlong                        9                   10                 0\ncombined                   10                   10                 0\n```\n\nWe 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.\n\nPicking 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.\n\n## What shows up in the top 25\n\nThis cell counts which scenarios show up in the top 25 of the combined ranking.\n\n```\ntop25 = candidates.sort_values(\"combined\", ascending=False).head(25)\ntop25[\"scenario\"].value_counts().to_frame(\"accounts\")\naccounts\nscenario                   \nnormal                   15\ntakeover_classic          4\ntakeover_nocreds          3\ntakeover_slowburn         3\n```\n\nThe 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.\n\n# Why was this account flagged?\n\nA 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.\n\nFor 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.\n\n```\nflagged = candidates.sort_values(\"combined\", ascending=False).iloc[0][\"accountId\"]\nprint(\"Highest-scoring account:\", flagged)\n\ngds.run_cypher(\"\"\"\nMATCH (a:Account {accountId: $flagged})-[:HAS_EVENT]->(:Event)-[:USED_DEVICE|FROM_IP|TO_PAYEE]->(c:Context)\nMATCH (c)<-[:USED_DEVICE|FROM_IP|TO_PAYEE]-(:Event)<-[:HAS_EVENT]-(other:Account {status: 'confirmed_takeover'})\nWHERE other <> a\nRETURN [l IN labels(c) WHERE l <> 'Context'][0] AS sharedType,\n       coalesce(c.deviceId, c.ipAddress, c.payeeId) AS sharedWith,\n       count(DISTINCT other) AS confirmedTakeoversSharingIt\nORDER BY confirmedTakeoversSharingIt DESC\n\"\"\", params={\"flagged\": flagged})\nHighest-scoring account: A0572\n\n  sharedType       sharedWith  confirmedTakeoversSharingIt\n0  IPAddress  163.192.185.247                            7\n1  IPAddress  153.119.227.164                            6\n2     Device           D00645                            6\n3  IPAddress    46.201.62.239                            4\n4      Payee          PAY0313                            4\n5  IPAddress    49.224.56.184                            2\n6  IPAddress     44.184.78.40                            2\n7  IPAddress  119.203.241.212                            1\n```\n\nA0572 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.\n\n# Wrap-up\n\nWe 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:\n\n- **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.\n- **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.\n- **Context nodes.** Devices, IP addresses, and payees feed into the embedding, so shared attacker infrastructure counts as evidence alongside the event sequence.\n\nBecause 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.\n\nReady 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.", "url": "https://wpnews.pro/news/catching-account-takeovers-mid-attack-with-fastpath", "canonical_source": "https://neo4j.com/blog/graph-data-science/catching-account-takeovers-mid-attack-with-fastpath/", "published_at": "2026-12-04 14:32:00+00:00", "updated_at": "2026-12-04 21:13:43.452809+00:00", "lang": "en", "topics": ["artificial-intelligence", "machine-learning", "ai-tools", "developer-tools"], "entities": ["Neo4j", "FastPath", "Aura Graph Analytics"], "also_reported_by": [], "takeaway": "FastPath embeds each node from its event sequence with exponential decay on event age and time measured from a per-node observation time, letting 30 confirmed takeovers serve as a reference set to flag 12 live takeovers among 2,000 accounts.", "recommendation": null, "alternates": {"html": "https://wpnews.pro/news/catching-account-takeovers-mid-attack-with-fastpath", "markdown": "https://wpnews.pro/news/catching-account-takeovers-mid-attack-with-fastpath.md", "text": "https://wpnews.pro/news/catching-account-takeovers-mid-attack-with-fastpath.txt", "jsonld": "https://wpnews.pro/news/catching-account-takeovers-mid-attack-with-fastpath.jsonld"}}