SlideShare a Scribd company logo
© 2022 Neo4j, Inc. All rights reserved.
Neo4j Drivers Best Practices
M. David Allen
Senior Director, Developer Relations
mdavidallen
These slides: https://dev.neo4j.com/neo4j-driver-best-practices
© 2022 Neo4j, Inc. All rights reserved.
2
Outline
● What's a driver and how does it work?
● What are the best practices?
● Common Pitfalls
● Understanding consistency in Neo4j
© 2022 Neo4j, Inc. All rights reserved.
3
What Drivers Do
© 2022 Neo4j, Inc. All rights reserved.
4
What Drivers Work Against
© 2022 Neo4j, Inc. All rights reserved.
5
Routing Tables
© 2022 Neo4j, Inc. All rights reserved.
6
What Routing Tables Look Like
CALL
dbms.cluster.routing.getRoutingTable({})
YIELD ttl, servers
UNWIND servers as server
RETURN ttl, server.role, server.addresses;
© 2022 Neo4j, Inc. All rights reserved.
7
Best Practices
© 2022 Neo4j, Inc. All rights reserved.
8
Connect with neo4j+s:// Whenever Possible
You want routing context, and you want to be secured via full certificate validation, to prevent man
in the middle attacks
neo4j+s:// is the default in AuraDB, and going forward bolt is likely to be phased out.
© 2022 Neo4j, Inc. All rights reserved.
9
Use Very Recent Versions of Neo4j Drivers
● Introduction of AuraDB has introduced changes to
connection details and routing details for clusters
● Newer drivers benefit from performance
enhancements, and reduced connection errors in
cloud environments
© 2022 Neo4j, Inc. All rights reserved.
10
Verify Connectivity Before Issuing Queries
● Push connection errors to code initialization time, not query time
● Pay one-time cost in a predictable place
● Drivers initialize a connection pool
© 2022 Neo4j, Inc. All rights reserved.
11
Create One Driver Instance and Hold Onto It
Expensive:
● Drivers
● Connection Pools
Cheap:
● Sessions
● Queries
11
© 2022 Neo4j, Inc. All rights reserved.
12
Where This Goes Wrong: What Not To Do
● AWS Lambda functions, serverless functions in general
● Users create a driver for every request, and don't verify connectivity
● Observed problems:
○ Serverless functions take too long to execute (paying connection pool cost
over and over again)
○ Connection errors to the database fail at function invocation time, not startup
© 2022 Neo4j, Inc. All rights reserved.
13
Use Explicit Transaction Functions
with driver.session as session:
session.run("CREATE (p:Person { name: $name})", name="David")
def add_person(self, name):
with driver.session() as session:
session.write_transaction(self.create_person_node, name)
def create_person_node(tx, name):
return tx.run("CREATE (a:Person {name: $name})", name=name)
© 2022 Neo4j, Inc. All rights reserved.
14
Use Query Parameters Whenever Possible
def create_person_node(tx, name):
tx.run("CREATE (a:Person {name: $name})", name=name )
def create_person_node(tx, name):
tx.run("CREATE (a:Person {name: '%s'})" % name )
● Avoids Cypher injection attack potential
● Reuses compiled queries in the database
© 2022 Neo4j, Inc. All rights reserved.
15
Where This Goes Wrong: Pitfalls
● "Autocommit transactions" (session.run()) always send traffic to the leader
● Heavy workloads overload the leader, leaving followers idle
● Without parameterized queries, database has to work harder to execute
the same query over and over
© 2022 Neo4j, Inc. All rights reserved.
16
Process Database Results Within your Tx Function
© 2022 Neo4j, Inc. All rights reserved.
17
Returning Vanilla Python Objects
© 2022 Neo4j, Inc. All rights reserved.
18
Causal Consistency in Neo4j (part 1)
CREATE (p:Person { name: "David" })
MATCH (p:Person) WHERE p.name = "David" RETURN count(p)
1st query succeeds when a majority of cluster members have acknowledged the write.
Generally that will be 2 out of 3.
What the second query returns depends on timing, and which cluster member you ask!
© 2022 Neo4j, Inc. All rights reserved.
19
Causal Consistency in Neo4j: Bookmarks (part 2)
User: CREATE (p:Person { name: "David" })
Server: OK, got it. Bookmark XYZ.
User: As of point in time XYZ,
MATCH (p:Person) WHERE p.name = "David" RETURN count(p)
Server: OK, cool. Result=1
With bookmarks, you always get what you expect, because you query "as of point in time"
from your previous queries
That is, you read your own writes
In other words: you read the changes you cause (causal consistency)
© 2022 Neo4j, Inc. All rights reserved.
20
Causal Consistency (part 3): Bookmark chaining
● Session objects in Neo4j drivers chain bookmarks automatically
● As long as you reuse a session, you get the expected behavior for free
● If you create new sessions, you can still pass bookmarks manually
© 2022 Neo4j, Inc. All rights reserved.
21
Advanced Issues
● Distributed microservices that need to read each other's writes
○ Generally requires bookmark passing, for example via Redis
© 2022 Neo4j, Inc. All rights reserved.
22
Summary: Best Practices Make your Code:
● More performant (minimizing setup/connection time)
● More secure (no Cypher injection potential, encrypted communications)
● More robust & portable to different Neo4j environments (single instance
vs. cluster)

More Related Content

PDF
Neo4j GraphDay Seattle- Sept19- neo4j basic training
PDF
Présentation des bases de données orientées graphes
PDF
Introducing Neo4j
PDF
Neo4j 4.1 overview
PDF
Intermediate Cypher.pdf
PPTX
Top 10 Cypher Tuning Tips & Tricks
PDF
Building Lakehouses on Delta Lake with SQL Analytics Primer
PDF
Neo4j Demo: Using Knowledge Graphs to Classify Diabetes Patients (GlaxoSmithK...
Neo4j GraphDay Seattle- Sept19- neo4j basic training
Présentation des bases de données orientées graphes
Introducing Neo4j
Neo4j 4.1 overview
Intermediate Cypher.pdf
Top 10 Cypher Tuning Tips & Tricks
Building Lakehouses on Delta Lake with SQL Analytics Primer
Neo4j Demo: Using Knowledge Graphs to Classify Diabetes Patients (GlaxoSmithK...

What's hot (20)

PDF
The Graph Database Universe: Neo4j Overview
PDF
Intro to Neo4j and Graph Databases
PDF
Workshop - Neo4j Graph Data Science
PPTX
Intro to Neo4j
PDF
Neo4j: The path to success with Graph Database and Graph Data Science
PDF
Graph database Use Cases
PPTX
Neo4j graph database
PDF
ntroducing to the Power of Graph Technology
PPTX
Knowledge Graphs and Generative AI_GraphSummit Minneapolis Sept 20.pptx
KEY
Intro to Neo4j presentation
PPT
Neo4J : Introduction to Graph Database
PDF
Full Stack Graph in the Cloud
PDF
Knowledge Graphs & Graph Data Science, More Context, Better Predictions - Neo...
PDF
Data Modeling with Neo4j
PPTX
Siligong.Data - May 2021 - Transforming your analytics workflow with dbt
PDF
Neanex - Semantic Construction with Graphs
PDF
Intro to Graphs and Neo4j
PDF
Neo4j graphs in government
PPTX
Knowledge Graph Introduction
PDF
Neo4j Fundamentals
The Graph Database Universe: Neo4j Overview
Intro to Neo4j and Graph Databases
Workshop - Neo4j Graph Data Science
Intro to Neo4j
Neo4j: The path to success with Graph Database and Graph Data Science
Graph database Use Cases
Neo4j graph database
ntroducing to the Power of Graph Technology
Knowledge Graphs and Generative AI_GraphSummit Minneapolis Sept 20.pptx
Intro to Neo4j presentation
Neo4J : Introduction to Graph Database
Full Stack Graph in the Cloud
Knowledge Graphs & Graph Data Science, More Context, Better Predictions - Neo...
Data Modeling with Neo4j
Siligong.Data - May 2021 - Transforming your analytics workflow with dbt
Neanex - Semantic Construction with Graphs
Intro to Graphs and Neo4j
Neo4j graphs in government
Knowledge Graph Introduction
Neo4j Fundamentals
Ad

Similar to Neo4j Drivers Best Practices (20)

PPTX
Fun with Fabric in 15
PPTX
Master Real-Time Streams With Neo4j and Apache Kafka
PDF
Get your instance by name integration of nova, neutron and designate
PDF
DCEU 18: App-in-a-Box with Docker Application Packages
PDF
002 Introducing Neo4j 5 for Administrators - NODES2022 AMERICAS Beginner 2 - ...
PPTX
Leveraging Neo4j With Apache Spark
PDF
Day In A Life Of A Node.js Developer
PDF
Day in a life of a node.js developer
PPTX
Introduction to Neo4j AuraDB: Your Fastest Path to Graph
PDF
Drupal Camp Göteborg 2013: Skalbarhet och tillgänglighet med MySQL-replikering
PDF
DevOpsDays Taipei 2017 從打鐵到雲端
DOCX
Creating Virtual Infrastructure
PDF
99.9999% (Seriously, that Many 9's) Uptime at Adobe: How We Got There with Neo4j
PDF
Docker and Your Path to a Better Staging Environment - webinar by Gil Tayar
PDF
Tech Talk: DevOps at LeanIX @ Startup Camp Berlin
PDF
Running MongoDB Enterprise on Kubernetes
PDF
Intro to development sites and site migration
PDF
Docker from basics to orchestration (PHPConfBr2015)
PPTX
Introduction to Node.js
PPTX
GraphConnect 2022 - Top 10 Cypher Tuning Tips & Tricks.pptx
Fun with Fabric in 15
Master Real-Time Streams With Neo4j and Apache Kafka
Get your instance by name integration of nova, neutron and designate
DCEU 18: App-in-a-Box with Docker Application Packages
002 Introducing Neo4j 5 for Administrators - NODES2022 AMERICAS Beginner 2 - ...
Leveraging Neo4j With Apache Spark
Day In A Life Of A Node.js Developer
Day in a life of a node.js developer
Introduction to Neo4j AuraDB: Your Fastest Path to Graph
Drupal Camp Göteborg 2013: Skalbarhet och tillgänglighet med MySQL-replikering
DevOpsDays Taipei 2017 從打鐵到雲端
Creating Virtual Infrastructure
99.9999% (Seriously, that Many 9's) Uptime at Adobe: How We Got There with Neo4j
Docker and Your Path to a Better Staging Environment - webinar by Gil Tayar
Tech Talk: DevOps at LeanIX @ Startup Camp Berlin
Running MongoDB Enterprise on Kubernetes
Intro to development sites and site migration
Docker from basics to orchestration (PHPConfBr2015)
Introduction to Node.js
GraphConnect 2022 - Top 10 Cypher Tuning Tips & Tricks.pptx
Ad

More from Neo4j (20)

PDF
MASTERDECK GRAPHSUMMIT SYDNEY (Public).pdf
PDF
Jin Foo - Prospa GraphSummit Sydney Presentation.pdf
PDF
GraphSummit Singapore Master Deck - May 20, 2025
PPTX
Graphs & GraphRAG - Essential Ingredients for GenAI
PPTX
Neo4j Knowledge for Customer Experience.pptx
PPTX
GraphTalk New Zealand - The Art of The Possible.pptx
PDF
Neo4j: The Art of the Possible with Graph
PDF
Smarter Knowledge Graphs For Public Sector
PDF
GraphRAG and Knowledge Graphs Exploring AI's Future
PDF
Matinée GenAI & GraphRAG Paris - Décembre 24
PDF
ANZ Presentation: GraphSummit Melbourne 2024
PDF
Google Cloud Presentation GraphSummit Melbourne 2024: Building Generative AI ...
PDF
Telstra Presentation GraphSummit Melbourne: Optimising Business Outcomes with...
PDF
Hands-On GraphRAG Workshop: GraphSummit Melbourne 2024
PDF
Démonstration Digital Twin Building Wire Management
PDF
Swiss Life - Les graphes au service de la détection de fraude dans le domaine...
PDF
Démonstration Supply Chain - GraphTalk Paris
PDF
The Art of Possible - GraphTalk Paris Opening Session
PPTX
How Siemens bolstered supply chain resilience with graph-powered AI insights ...
PDF
Knowledge Graphs for AI-Ready Data and Enterprise Deployment - Gartner IT Sym...
MASTERDECK GRAPHSUMMIT SYDNEY (Public).pdf
Jin Foo - Prospa GraphSummit Sydney Presentation.pdf
GraphSummit Singapore Master Deck - May 20, 2025
Graphs & GraphRAG - Essential Ingredients for GenAI
Neo4j Knowledge for Customer Experience.pptx
GraphTalk New Zealand - The Art of The Possible.pptx
Neo4j: The Art of the Possible with Graph
Smarter Knowledge Graphs For Public Sector
GraphRAG and Knowledge Graphs Exploring AI's Future
Matinée GenAI & GraphRAG Paris - Décembre 24
ANZ Presentation: GraphSummit Melbourne 2024
Google Cloud Presentation GraphSummit Melbourne 2024: Building Generative AI ...
Telstra Presentation GraphSummit Melbourne: Optimising Business Outcomes with...
Hands-On GraphRAG Workshop: GraphSummit Melbourne 2024
Démonstration Digital Twin Building Wire Management
Swiss Life - Les graphes au service de la détection de fraude dans le domaine...
Démonstration Supply Chain - GraphTalk Paris
The Art of Possible - GraphTalk Paris Opening Session
How Siemens bolstered supply chain resilience with graph-powered AI insights ...
Knowledge Graphs for AI-Ready Data and Enterprise Deployment - Gartner IT Sym...

Recently uploaded (20)

PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
A novel scalable deep ensemble learning framework for big data classification...
PDF
Transform Your ITIL® 4 & ITSM Strategy with AI in 2025.pdf
PDF
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Web App vs Mobile App What Should You Build First.pdf
PDF
DASA ADMISSION 2024_FirstRound_FirstRank_LastRank.pdf
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
Heart disease approach using modified random forest and particle swarm optimi...
PDF
Approach and Philosophy of On baking technology
PDF
NewMind AI Weekly Chronicles - August'25-Week II
PDF
ENT215_Completing-a-large-scale-migration-and-modernization-with-AWS.pdf
PDF
DP Operators-handbook-extract for the Mautical Institute
PDF
Mushroom cultivation and it's methods.pdf
PPTX
Chapter 5: Probability Theory and Statistics
PPTX
A Presentation on Touch Screen Technology
PDF
Zenith AI: Advanced Artificial Intelligence
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PPTX
Tartificialntelligence_presentation.pptx
MIND Revenue Release Quarter 2 2025 Press Release
A novel scalable deep ensemble learning framework for big data classification...
Transform Your ITIL® 4 & ITSM Strategy with AI in 2025.pdf
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Web App vs Mobile App What Should You Build First.pdf
DASA ADMISSION 2024_FirstRound_FirstRank_LastRank.pdf
Programs and apps: productivity, graphics, security and other tools
Heart disease approach using modified random forest and particle swarm optimi...
Approach and Philosophy of On baking technology
NewMind AI Weekly Chronicles - August'25-Week II
ENT215_Completing-a-large-scale-migration-and-modernization-with-AWS.pdf
DP Operators-handbook-extract for the Mautical Institute
Mushroom cultivation and it's methods.pdf
Chapter 5: Probability Theory and Statistics
A Presentation on Touch Screen Technology
Zenith AI: Advanced Artificial Intelligence
Building Integrated photovoltaic BIPV_UPV.pdf
Tartificialntelligence_presentation.pptx

Neo4j Drivers Best Practices

  • 1. © 2022 Neo4j, Inc. All rights reserved. Neo4j Drivers Best Practices M. David Allen Senior Director, Developer Relations mdavidallen These slides: https://dev.neo4j.com/neo4j-driver-best-practices
  • 2. © 2022 Neo4j, Inc. All rights reserved. 2 Outline ● What's a driver and how does it work? ● What are the best practices? ● Common Pitfalls ● Understanding consistency in Neo4j
  • 3. © 2022 Neo4j, Inc. All rights reserved. 3 What Drivers Do
  • 4. © 2022 Neo4j, Inc. All rights reserved. 4 What Drivers Work Against
  • 5. © 2022 Neo4j, Inc. All rights reserved. 5 Routing Tables
  • 6. © 2022 Neo4j, Inc. All rights reserved. 6 What Routing Tables Look Like CALL dbms.cluster.routing.getRoutingTable({}) YIELD ttl, servers UNWIND servers as server RETURN ttl, server.role, server.addresses;
  • 7. © 2022 Neo4j, Inc. All rights reserved. 7 Best Practices
  • 8. © 2022 Neo4j, Inc. All rights reserved. 8 Connect with neo4j+s:// Whenever Possible You want routing context, and you want to be secured via full certificate validation, to prevent man in the middle attacks neo4j+s:// is the default in AuraDB, and going forward bolt is likely to be phased out.
  • 9. © 2022 Neo4j, Inc. All rights reserved. 9 Use Very Recent Versions of Neo4j Drivers ● Introduction of AuraDB has introduced changes to connection details and routing details for clusters ● Newer drivers benefit from performance enhancements, and reduced connection errors in cloud environments
  • 10. © 2022 Neo4j, Inc. All rights reserved. 10 Verify Connectivity Before Issuing Queries ● Push connection errors to code initialization time, not query time ● Pay one-time cost in a predictable place ● Drivers initialize a connection pool
  • 11. © 2022 Neo4j, Inc. All rights reserved. 11 Create One Driver Instance and Hold Onto It Expensive: ● Drivers ● Connection Pools Cheap: ● Sessions ● Queries 11
  • 12. © 2022 Neo4j, Inc. All rights reserved. 12 Where This Goes Wrong: What Not To Do ● AWS Lambda functions, serverless functions in general ● Users create a driver for every request, and don't verify connectivity ● Observed problems: ○ Serverless functions take too long to execute (paying connection pool cost over and over again) ○ Connection errors to the database fail at function invocation time, not startup
  • 13. © 2022 Neo4j, Inc. All rights reserved. 13 Use Explicit Transaction Functions with driver.session as session: session.run("CREATE (p:Person { name: $name})", name="David") def add_person(self, name): with driver.session() as session: session.write_transaction(self.create_person_node, name) def create_person_node(tx, name): return tx.run("CREATE (a:Person {name: $name})", name=name)
  • 14. © 2022 Neo4j, Inc. All rights reserved. 14 Use Query Parameters Whenever Possible def create_person_node(tx, name): tx.run("CREATE (a:Person {name: $name})", name=name ) def create_person_node(tx, name): tx.run("CREATE (a:Person {name: '%s'})" % name ) ● Avoids Cypher injection attack potential ● Reuses compiled queries in the database
  • 15. © 2022 Neo4j, Inc. All rights reserved. 15 Where This Goes Wrong: Pitfalls ● "Autocommit transactions" (session.run()) always send traffic to the leader ● Heavy workloads overload the leader, leaving followers idle ● Without parameterized queries, database has to work harder to execute the same query over and over
  • 16. © 2022 Neo4j, Inc. All rights reserved. 16 Process Database Results Within your Tx Function
  • 17. © 2022 Neo4j, Inc. All rights reserved. 17 Returning Vanilla Python Objects
  • 18. © 2022 Neo4j, Inc. All rights reserved. 18 Causal Consistency in Neo4j (part 1) CREATE (p:Person { name: "David" }) MATCH (p:Person) WHERE p.name = "David" RETURN count(p) 1st query succeeds when a majority of cluster members have acknowledged the write. Generally that will be 2 out of 3. What the second query returns depends on timing, and which cluster member you ask!
  • 19. © 2022 Neo4j, Inc. All rights reserved. 19 Causal Consistency in Neo4j: Bookmarks (part 2) User: CREATE (p:Person { name: "David" }) Server: OK, got it. Bookmark XYZ. User: As of point in time XYZ, MATCH (p:Person) WHERE p.name = "David" RETURN count(p) Server: OK, cool. Result=1 With bookmarks, you always get what you expect, because you query "as of point in time" from your previous queries That is, you read your own writes In other words: you read the changes you cause (causal consistency)
  • 20. © 2022 Neo4j, Inc. All rights reserved. 20 Causal Consistency (part 3): Bookmark chaining ● Session objects in Neo4j drivers chain bookmarks automatically ● As long as you reuse a session, you get the expected behavior for free ● If you create new sessions, you can still pass bookmarks manually
  • 21. © 2022 Neo4j, Inc. All rights reserved. 21 Advanced Issues ● Distributed microservices that need to read each other's writes ○ Generally requires bookmark passing, for example via Redis
  • 22. © 2022 Neo4j, Inc. All rights reserved. 22 Summary: Best Practices Make your Code: ● More performant (minimizing setup/connection time) ● More secure (no Cypher injection potential, encrypted communications) ● More robust & portable to different Neo4j environments (single instance vs. cluster)