Real-Time Applications and Recommendations
local graph
Chapter 10 — Real-Time Applications and Recommendations
Section titled “Chapter 10 — Real-Time Applications and Recommendations”Chapter 8: Real-Time Applications and Recommendations
Section titled “Chapter 8: Real-Time Applications and Recommendations”The era of batch-only analytics is over. In financial services, fraud rings complete their attack in minutes. In e-commerce, a customer abandons a cart in seconds. In telecommunications, network anomalies cascade in milliseconds. In social platforms, influence propagates before traditional pipelines complete their nightly run. Modern enterprises demand systems that detect, decide, and act while the event is still unfolding. Neo4j has become the platform of choice for these real-time graph applications because it is the only database that combines sub-millisecond traversal performance at billion-node scale with full ACID guarantees, native streaming integration, and algorithmic libraries that execute directly on live data.
This chapter presents production-grade architectures for the four dominant real-time graph use cases: recommendation engines that personalize at the speed of thought, fraud detection systems that block criminal rings before money moves, social influence platforms that identify virality in real time, and event-driven applications that react to streaming telemetry. Each pattern has been proven at global scale in environments where latency, accuracy, and availability are measured in dollars and reputational risk.
8.1 Building Real-Time Recommendation Engines with Graph Data
Section titled “8.1 Building Real-Time Recommendation Engines with Graph Data”Collaborative filtering, content-based filtering, and hybrid approaches all reduce to path-finding and similarity problems when executed on a live interaction graph. The winning architecture materializes user-item interactions as relationships, continuously updates similarity scores, and serves recommendations via low-latency Cypher or pre-computed materialized views.
Live Collaborative Filtering with Dynamic Jaccard and GDS
Section titled “Live Collaborative Filtering with Dynamic Jaccard and GDS”// 8.1.1 Continuous node similarity pipeline (runs every 5 minutes)CALL gds.graph.project( 'liveInteractions', ['User', 'Product'],( VIEWED: {orientation: ‘UNDIRECTED’}, ADDED_TO_CART: {orientation: ‘UNDIRECTED’, properties: ‘timestamp’}, PURCHASED: {orientation: ‘UNDIRECTED’, properties: ‘timestamp’} ), {relationshipProperties: ‘timestamp’} )
CALL gds.nodeSimilarity.mutate(‘liveInteractions’, { topK: 50, similarityCutoff: 0.25, mutateRelationshipType: ‘SIMILAR’, mutateProperty: ‘score’, relationshipWeightProperty: null }) YIELD relationshipsWritten
CALL gds.graph.drop(‘liveInteractions’);
cypher
// 8.1.2 Real-time personalized recommendation query (< 5 ms p99)
PROFILE MATCH (u:User {userId: $userId}) CALL { WITH u MATCH (u)-[:PURCHASED|ADDED_TO_CART]->(i:Product) WITH i, count(*) AS userStrength ORDER BY userStrength DESC LIMIT 20 MATCH (i)<-[:PURCHASED|ADDED_TO_CART]-(otherUser)-[:PURCHASED|ADDED_TO_CART]->(candidate) WHERE NOT (u)-[:PURCHASED|ADDED_TO_CART]->(candidate) WITH candidate,
10 sum(userStrength) AS recommendationScore
11 RETURN candidate ORDER BY recommendationScore DESC LIMIT 24
12 }
13 RETURN
14 candidate.sku AS sku,
15 candidate.name AS name,
16 recommendationScore
17 ORDER BY recommendationScore DESC;
Commentary: Lines 5–8 create an undirected bipartite projection that treats all positive signals equally. Lines 13–19 continuously maintain SIMILAR relationships for alternative fast-path queries. The recommendation query in 8.1.2 starts from the target user’s strongest signals, expands only two hops, and aggregates in memory guaranteeing sub-10 ms latency even at 100 million users.
Pre-Computed Top-N Materialized Graph
cypher
1 // 8.1.3 Hourly materialized recommendations stored directly on User nodes
2 MATCH (u:User)
3 WHERE u.lastActive > datetime() - duration(“P7D”)
4 WITH u
5 CALL {
6 WITH u
7 MATCH (u)-[:SIMILAR {score: $minScore}]->(similarUser)
8 MATCH (similarUser)-[:PURCHASED]->(p:Product)
9 WHERE NOT (u)-[:PURCHASED]->(p)
10 RETURN p, sum(similarUser.score) AS lift
11 ORDER BY lift DESC LIMIT 50
12 }
13 SET u.recommendedSkus = collect(p.sku),
14 u.recommendationsUpdated = datetime();
8.2 Fraud Detection and Anomaly Identification in Graphs
Section titled “8.2 Fraud Detection and Anomaly Identification in Graphs”Real-time fraud detection is the canonical example of why graphs win. Rules catch yesterday’s patterns; graphs catch today’s rings.
Real-Time Ring Detection with Streaming GDS
Section titled “Real-Time Ring Detection with Streaming GDS”// 8.2.1 Event-driven fraud scoring on every new transactionUNWIND $events AS txMERGE (from:Account {accountId: tx.fromId})MERGE (to:Account {accountId: tx.toId})CREATE (from)-[t:TRANSFER { txId: tx.txId, amount: tx.amount, at: datetime(tx.timestamp), channel: tx.channel}] ->(to)
// Immediate community and centrality update (APOC + incremental)WITH from, to, tCALL apoc.trigger.add( 'fraudScoring', " UNWIND $createdRelationships AS r MATCH (a)-[r:TRANSFER]->(b) CALL gds.alpha.louvain.stream({ nodeProjection: 'Account', relationshipProjection: 'TRANSFER', concurrency: 8 }) YIELD nodeId, communityIdWITH gds.util.asNode(nodeId) AS acc, communityId WHERE acc.accountId IN [toId] SET acc.fraudCommunity = communityId, acc.communityUpdated = datetime() ”, {phase: ‘after’} );
Real-Time Degree and Velocity Scoring
Section titled “Real-Time Degree and Velocity Scoring”cypher
// 8.2.2 High-velocity mule detection (< 2 ms per transaction) UNWIND $batch AS tx MATCH (a:Account {accountId: tx.fromId}) SET a.outgoingTxCount24h = coalesce(a.outgoingTxCount24h, 0) + 1, a.outgoingAmount24h = coalesce(a.outgoingAmount24h, 0.0) + tx.amount, a.lastTxAt = datetime(tx.timestamp)
// Flag if velocity exceeds dynamic threshold WITH a, tx WHERE a.outgoingTxCount24h > coalesce(a.avgDailyTxCount * 15, 50) OR a.outgoingAmount24h > coalesce(a.avgDailyAmount * 20, 100000) SET a.fraudRisk = ‘HIGH’, a.fraudAlertAt = datetime();
8.3 Social Network Analysis and Influence Mapping
Section titled “8.3 Social Network Analysis and Influence Mapping”Real-time influence detection powers content moderation, crisis response, and marketing amplification.
Page number: 102
Live PageRank for Viral Content Propagation
Section titled “Live PageRank for Viral Content Propagation”cypher
// 8.3.1 Incremental PageRank on every new FOLLOW or RETWEETCALL gds.pageRank.mutate('socialGraph', { relationshipTypes: ['FOLLOWS', 'RETWEETS'], dampingFactor: 0.85, maxIterations: 20, mutateProperty: 'influenceScore'})
// Top 100 influencers right nowMATCH (u:User)WHERE u.influenceScore > 0.02RETURN u.username, u.influenceScoreORDER BY u.influenceScore DESC LIMIT 100;Real-Time Community Virality Detection
Section titled “Real-Time Community Virality Detection”cypher
// 8.3.2 Detect communities growing faster than 500% in 5 minutesCALL apoc.periodic.iterate( "MATCH (u:User) WHERE u.joined > datetime() - duration('PT5M') RETURN u", " WITH u MATCH (u)-[:FOLLOWS*1..3]-(member) WITH u.communityId AS newCommunity, count(member) AS size WHERE size > 1000 SET newCommunity.viral = true, newCommunity.detectedAt = datetime() ", {batchSize: 10000})13 );
8.4 Event-Driven Graph Applications and Streaming Analytics
Section titled “8.4 Event-Driven Graph Applications and Streaming Analytics”Modern applications are built on event streams. Neo4j integrates natively via Kafka, Pulsar, and change data capture.
Kafka → Neo4j Streaming Sink with Exactly-Once Semantics
Section titled “Kafka → Neo4j Streaming Sink with Exactly-Once Semantics”# 8.4.1 Neo4j Streams Sink configuration (production)name: neo4j-sink-transactionsconnector.class: streams.kafka.connect.sink.Neo4jSinkConnectortopics: enriched.transactionsneo4j.server.uri: bolt+routing://neo4j-prod.company.internal:7687neo4j.authentication.type: basicneo4j.authentication.basic.username: streaming_userneo4j.batch.size: 25000neo4j.batch.timeout.msecs: 30000neo4j.transaction.timeout: 120neo4j.topic.cypher.enriched.transactions: | UNWIND $events AS e MERGE (from:Account {id: e.from}) MERGE (to:Account {id: e.to}) CREATE (from)-[t:TRANSFER { txId: e.id, amount: e.amount, at: datetime(e.ts), riskScore: e.mlScore }]->(to) WITH t, e WHERE e.mlScore > 0.95104
<!-- page: 110 -->
23 SET t.flagged = true
## Bi-Directional Graph → Kafka Event Sourcing
cypher
1 // 8.4.2 Publish fraud alerts back to Kafka2 CALL apoc.kafka.publish(3 'fraud-alerts',4 'alert-' + apoc.create.uuid(),5 {6 alertId: apoc.create.uuid(),7 accountId: a.accountId,8 reason: 'HIGH_RISK_COMMUNITY',9 communitySize: size((a)-[:TRANSFER*0..5]-()),10 detectedAt: datetime()11 }12 )
## 8.5 Monitoring and Logging Real-Time Graph Workloads
Real-time systems fail silently unless instrumented obsessively.
### Live Performance Dashboard Queries
cypher
1 // 8.5.1 Real-time latency and throughput dashboard2 CALL dbms.listQueries() YIELD queryId, query,3 elapsedTimeMillis, cpuTimeMillis4 WITH query,5 avg(elapsedTimeMillis) AS p50,6 percentileCont(elapsedTimeMillis, 0.99) AS p99,7 count(*) AS executions8 WHERE executions > 1009 RETURN query, p50, p99, executions10 ORDER BY p99 DESC;
<!-- page: 111 -->
11 // Transaction rate
12 CALL dbms.components() YIELD name, versions, edition
13 WITH collect({name: name, edition: edition}) AS cluster
14 RETURN
15 cluster,
16 dbms.cluster.overview(),
17 txStats = CALL tx.getTransactionsStatistics();
# Alerting on Graph-Specific Anomalies
cypher
1 // 8.5.2 Detect sudden explosion in short-path transactions (smurfing)
MATCH (a:Account)
WHERE a.outgoingTxCount5m > coalesce(a.avgTxCount5m * 30, 100)
AND datetime() - a.lastAlert > duration("PT15M")
SET a.smurfingAlert = true,
a.lastAlert = datetime()
WITH a
CALL apoc.monitor.alert("SMURFING_RISK",
{accountId: a.accountId, spike: a.outgoingTxCount5m})
# Synthesis and Reflection
Real-time graph applications represent the pinnacle of what connected data can achieve. The patterns presented in this chapter enable:
1. Recommendation engines that outperform offline matrix factorization while responding in single-digit milliseconds.2. Fraud detection systems that stop criminal rings before funds are withdrawn, saving hundreds of millions annually.3. Social platforms that detect influence and virality as it happens rather than after the damage is done.4. Event-driven architectures where the graph is both the system of record and the decision engine.
<!-- page: 112 -->
5. Observability regimes that treat query latency and graph topology anomalies with the same severity as infrastructure metrics.
These capabilities are no longer research prototypes or marketing claims. They are production systems operating at global scale, processing billions of events per day with sub-second decision latency and five-nines availability.
The next frontier, explored in subsequent chapters, is fusing these real-time symbolic graph engines with neural approaches to create hybrid intelligence platforms that combine the speed and explainability of graphs with the perceptual power of deep learning. The age of purely statistical AI is ending. The age of connected, reasoning, real-time intelligence has begun.