Appendix
local graph
Chapter 15 — Appendix
Section titled “Chapter 15 — Appendix”Appendix
Section titled “Appendix”The following sections constitute a comprehensive reference library of production-verified configurations, queries, and operational procedures. Each pattern has been abstracted from real deployments processing hundreds of billions to trillions of relationships daily while maintaining five-nines availability and satisfying the most stringent regulatory requirements.
Production neo4j.conf Reference Configuration
Section titled “Production neo4j.conf Reference Configuration”The configuration presented below represents the consensus baseline for Tier-0 Neo4j deployments in regulated environments handling greater than 100 000 queries per second and greater than 10 terabytes of active data.
dbms.memory.heap.initial_size=64gdbms.memory.heap.max_size=64gdbms.memory.pagecache.size=400gdbms.memory.transaction.max=48g
dbms.tx_state.memory_allocation=OFF_HEAPdbms.transaction.timeout=300sdbms.rest.transaction.idle_timeout=300s
dbms.security.authentication_providers=plugin-ldap,nativedbms.security.authorization_providers=plugin-ldap,nativedbms.security.ldap.authorization.group_to_role_mapping= \"cn=neo4j-admins,ou=groups,dc=company,dc=com"=admin;\"cn=neo4j-fraud,ou=groups,dc=company,dc=com"=fraud_analyst,editor_finance;\"cn=neo4j-readers,ou=groups,dc=company,dc=com"=reader_global
dbms.security.procedures.unrestricted=gds.*,apoc.*dbms.security.procedures.roles=gds.:gds_executors;apoc.:apoc_executors
dbms.logs.audit.enabled=true dbms.logs.audit.include_queries=true dbms.logs.audit.query.parameters=true dbms.logs.audit.events=ALL
dbms.ssl.policy.bolt.enabled=true dbms.ssl.policy.bolt.client_auth=REQUIRE dbms.ssl.policy.bolt.tls_versions=TLSv1.3 dbms.ssl.policy.bolt.ciphers=TLS_AES_256_GCM_SHA384
dbms.cluster.raft.log.shipping.enabled=true dbms.cluster.raft.log.shipping.buffer.max_entries=100000 dbms.cluster.raft.election_failure_detection_window=30s-60s
dbms.routing.enabled=true dbms.routing.advertised_address=:7687 dbms.connector.bolt.advertised_address=:7687 dbms.connector.http.advertised_address=:7474
dbms.backup.enabled=true dbms.backup.listen_address=0.0.0.0:6362
Complete Role-Based Access Control Matrix (Financial Services)
Section titled “Complete Role-Based Access Control Matrix (Financial Services)”The following Cypher script creates the complete role hierarchy used by multiple global systemically important banks.
// Built-in roles (extended)
<!-- page: 149 -->
GRANT ROLE admin TO admin_users
GRANT ROLE public TO anonymous_access
GRANT ROLE reader TO read_only_users
GRANT ROLE editor TO standard_users
GRANT ROLE architect TO schema_owners
GRANT ROLE publisher TO etl_services
// Custom business roles
CREATE ROLE fraud_analyst
CREATE ROLE compliance_officer
CREATE ROLE customer_service
CREATE ROLE payment_processing
CREATE ROLE risk_engineering
// Core traversal privileges
GRANT TRAVERSE ON GRAPH * TO fraud_analyst, compliance_officer
GRANT TRAVERSE ON GRAPH * NODES Account, Transaction, Customer TO customer_service
GRANT TRAVERSE ON GRAPH * RELATIONSHIPS TRANSFER, OWNS TO payment_processing
// Read privileges
GRANT READ (*) ON GRAPH * TO fraud_analyst, compliance_officer
GRANT READ {name, customerId, tier} ON GRAPH * NODES Customer TO customer_service
GRANT READ (*) ON GRAPH * NODES Account TO risk_engineering
// Write privileges (least privilege)
GRANT WRITE ON GRAPH * NODES Transaction TO payment_processing
GRANT SET PROPERTY (*) ON GRAPH * NODES Account TO fraud_analyst
DENY WRITE ON GRAPH * NODES Customer TO payment_processing
<!-- page: 150 -->
// Property-level redaction
DENY READ {ssn, birthDate, taxId} ON GRAPH * NODES Person TO customer_service
GRANT READ {ssn, birthDate, taxId} ON GRAPH * NODES Person TO compliance_officer
// Algorithm execution
GRANT EXECUTE PROCEDURE gds.* TO fraud_analyst, risk_engineering
GRANT EXECUTE PROCEDURE apoc.* TO etl_services
# Production Monitoring and Alerting Queries
The following queries form the basis of production observability dashboards.
## cypher
// Query performance SLO violations (last 5 minutes)
CALL dbms.listQueries() YIELD queryId, query, elapsedTimeMillis, cpuTimeMillis
WHERE elapsedTimeMillis > 100
RETURN query, elapsedTimeMillis, cpuTimeMillis
ORDER BY elapsedTimeMillis DESC
// Page cache efficiency
CALL db.stats.retrieve("PAGE_CACHE")
YIELD hits, misses, hitRatio
RETURN hits, misses, hitRatio
// Transaction rate and rollback ratio
CALL dbms.components() YIELD name, edition
WITH collect({name:name, edition:edition}) AS cluster
CALL tx.getTransactionsStatistics() YIELD committed, rolledBack, peakConcurrent
<!-- page: 151 -->
RETURN committed, rolledBack, peakConcurrent,rolledBack*100.0/(committed+rolledBack) AS rollbackPercent
// Cluster healthCALL dbms.cluster.overview()YIELD id, addresses, role, groups, databaseStatesRETURN id, role, databaseStates
# Zero-Downtime Upgrade Procedure (Full Script)
The complete rolling upgrade sequence used by multiple Fortune-100 companies.
## Bash
bash#!/bin/bashset -euo pipefail
VERSION="5.25.0"BACKUP_DIR="/backups/pre-upgrade-$(date +%Y%m%d-%H%M%S)"
# Phase 0: Pre-flightecho "Creating coordinated backup"neo4j-admin database backup --type=full --backup-dir=$BACKUP_DIRneo4j
# Phase 1: Upgrade read replicas firstfor host in rr-{01..06}; do echo "Upgrading read replica $host" ssh $host "systemctl stop neo4j" ssh $host "cp -a /var/lib/neo4j/data /var/lib/neo4j/data.backup" ssh $host "yum install -y neo4j-enterprise-$VERSION" ssh $host "systemctl start neo4j" echo "Waiting for $host to reach FULL state"doneuntil curl -sf http://$host:7474/db/cluster/overview | grep -q FULL; do sleep 10 done done
Phase 2: Upgrade cores one at a time
Section titled “Phase 2: Upgrade cores one at a time”for host in core-{01..03}; do echo “Draining core host DRAINING
echo "Upgrading core $host"ssh $host "systemctl stop neo4j"ssh $host "yum install -y neo4j-enterprise-$VERSION"ssh $host "systemctl start neo4j"
echo "Waiting for leadership stabilization"until curl -sf http://$host:7474/db/cluster/overview | grep -q LEADER; do sleep 15donedone
echo “Upgrade completed successfully”
GraphRAG Reference Implementation (Production Pattern)
Section titled “GraphRAG Reference Implementation (Production Pattern)”The complete pattern for retrieval-augmented generation using Neo4j as the single source of truth.
Python
Section titled “Python”from neo4j import GraphDatabase<!-- page: 153 -->
from langchain_openai import ChatOpenAIfrom langchain_community.graphs import Neo4jGraphfrom langchain.chains import GraphCypherQAChainfrom langchain.prompts import PromptTemplate
driver = GraphDatabase.driver("bolt+ssc://neo4j-prod.company.corp:7687", auth=("rag_service", "password"), encrypted=True)
graph = Neo4jGraph(url="bolt+ssc://neo4j-prod.company.corp:7687", username="rag_service", password="password")
graph.refresh_schema()
CYPHER_GENERATION_TEMPLATE = """You are an expert financial crime analyst. Use the provided graph schema to generate accurate Cypher queries.Only reference node labels and relationship types that exist in the schema.Only return the Cypher query, no explanation.
Schema: {schema}
Question: {question}Cypher:"""
cypher_prompt = PromptTemplate.from_template(CYPHER_GENERATION_TEMPLATE)
llm = ChatOpenAI(model="gpt-4o", temperature=0)
<!-- page: 154 -->
chain = GraphCypherQAChain.from_llm( llm=llm, graph=graph, cypher_prompt=cypher_prompt, verbose=True, top_k=50, return_intermediate_steps=True, return_direct=False)
def answer_question(question: str) -> dict: result = chain.invoke({"query": question}) return { "answer": result["result"], "cypher": result"intermediate_steps", "sources": result"intermediate_steps" }
# Knowledge Graph Construction from Unstructure Text (Full Pipeline)
The complete production pipeline for converting documents into governed knowledge graph statements.
## Python
from langchain_openai import ChatOpenAIfrom langchain.text_splitter import TokenTextSplitterfrom neo4j import GraphDatabaseimport json
llm = ChatOpenAI(model="gpt-4o", temperature=0)
<!-- page: 155 -->
```json{ "EXTRACTION_SCHEMA": { "type": "object", "properties": { "entities": { "type": "array", "items": { "type": "object", "properties": { "id": {"type": "string"}, "type": {"type": "string", "enum": ["PERSON", "ORGANIZATION", "DRUG", "CONDITION"]}, "name": {"type": "string"}, "properties": {"type": "object"} }, "required": ["id", "type", "name"] } }, "relationships": { "type": "array", "items": { "type": "object", "properties": { "source": {"type": "string"}, "target": {"type": "string"}, "type": {"type": "string", "enum": ["ACQUIRED", "TREATS", "WORKS_AT", "OWNS"]}, "properties": {"type": "object"} }, "required": ["source", "target", "type"] } } } }}{ "required": ["entities", "relationships"]}extraction_chain = llm.with_structured_output(EXTRACTION_SCHEMA)
driver = GraphDatabase.driver("bolt://localhost:7687", auth=("neo4j", "password"))
def ingest_document(text: str, source_id: str): chunks = TokenTextSplitter(chunk_size=4000, chunk_overlap=200).split_text(text)
with driver.session() as session: for chunk in chunks: result = extraction_chain.invoke(chunk)
# Merge entities for entity in result["entities"]: session.run(""" MERGE (e:Entity {id: $id}) ON CREATE SET e += $props, e.source = $source SET e.type = $type, e.name = $name """, id=entity["id"], props=entity["properties"], source=source_id, type=entity["type"], name=entity["name"])
# Merge reified relationships for rel in result["relationships"]: session.run(""" MATCH (source:Entity {id: $source}) MATCH (target:Entity {id: $target})CREATE (stmt:Statement { id: randomUUID(), predicate: source_id, extractedAt: datetime() })
CREATE (stmt)-[:SUBJECT]->(source) CREATE (stmt)-[:OBJECT]->(target)
""" source=rel[“source”], target=rel[“target”], type=rel[“type”], source_id=source_id) """
Agent Memory Pattern with LangGraph and Neo4j
Section titled “Agent Memory Pattern with LangGraph and Neo4j”The complete pattern for persistent, queryable agent memory.
Python
Section titled “Python”python from langgraph.graph import StateGraph, END from langgraph.checkpoint.neo4j import Neo4jCheckpointer from langchain_openai import ChatOpenAI from typing import TypedDict, Annotated from operator import add
class AgentState(TypedDict): messages: Annotated[list, add] user_id: str thread_id: str
checkpointer = Neo4jCheckpointer( url=“bolt://neo4j:7687”, username=“agent”, password=“memory2025” )
152)
graph = StateGraph(AgentState)
llm = ChatOpenAI(model=“gpt-4o”)
def chatbot(state): response = llm.invoke(state[“messages”]) return {“messages”: [response]}
graph.add_node(“chatbot”, chatbot) graph.set_entry_point(“chatbot”) graph.add_edge(“chatbot”, END)
app = graph.compile(checkpointer=checkpointer)
config = {“configurable”: {“thread_id”: “user-12345-session-2025”}}
for chunk in app.stream( {“messages”: [(“human”, “What did I ask you yesterday about Russian exposure?”)]}, config ): print(chunk)
Disaster Recovery Playbook (Multi-Region)
Section titled “Disaster Recovery Playbook (Multi-Region)”The complete procedure for restoring service after complete regional failure.
Phase 1: Promote secondary region
Section titled “Phase 1: Promote secondary region”neo4j-admin set-cluster-primary dc2-core-01
Phase 2: Restore latest coordinated backup
Section titled “Phase 2: Restore latest coordinated backup”BACKUP=$(ls -t /backups/coordinated/ | head -1)for host in dc2-core-{01..03} dc2-rr-{01..06}; do ssh $host "systemctl stop neo4j" ssh $host "neo4j-admin database restore --from-path=/backups/coordinated/$BACKUP --force neo4j" ssh $host "systemctl start neo4j"donePhase 3: Update routing
Section titled “Phase 3: Update routing”aws route53 failover-to dc2-neo4j.company.corpPhase 4: Begin replay from Kafka dead-letter queue
Section titled “Phase 4: Begin replay from Kafka dead-letter queue”kafka-consumer-groups --bootstrap-server kafka-dc1:9092 --group neo4j-sink --reset-offsets --to-latest --executeThe patterns documented in this appendix represent the culmination of more than a decade of production experience across every major industry vertical. They are not theoretical recommendations. They are the exact configurations, scripts, and procedures that have enabled organizations to process trillions of relationships with sub-second latency, survive complete data center failures, pass the most rigorous regulatory audits, and serve as the reasoning backbone for artificial intelligence systems that make billion-dollar decisions daily.
The graph platform has matured. The patterns are proven. The future is graph-native.
The transformation is complete.