Write performance bottleneck

Hi everyone,

I’m testing batch write performance in Python using the Neo4j driver with neo4j-rust-ext enabled, and I’m seeing a big slowdown when moving from a no-op UNWIND to MERGE + SET.

Data & Benchmark Setup

Each node has an id, and a properties map of 100 string keys ("0"–"99"), each with a 10-character random string (~10 million property writes across 100,000 nodes):

def random_str(length):
    import random
    import string
    return ''.join(random.choices(string.ascii_letters + string.digits, k=length))

print('generating nodes...')
props = {
    str(j): random_str(10)
    for j in range(100)
}
nodes = [
    {
        'id': i,
        'labels': [],
        'properties': {
            **props
        }
    }
    for i in range(100_000)
]

Batch loop (10,000 nodes per batch):

total = 0
gstart = time.perf_counter()
for batch in chunks(nodes, 10000):
    start = time.perf_counter()
    c = 0
    c += session.execute_write(
        lambda tx, b=batch: tx.run(create_nodes_query, nodes=b).single()['nodes_created']
    )
    total += c
    elapsed = time.perf_counter() - start
    print(f"Inserted {c} nodes in {elapsed:.6f}s")

print(f"Inserted {total} nodes in {time.perf_counter() - gstart:.6f}s")

Results:

  1. No-op query (UNWIND $nodes AS node RETURN count(node) AS nodes_created):

Total for 100,000 nodes: ~5.76s (~0.53s–0.66s per 10k batch)

  1. Write query (UNWIND $nodes AS node MERGE (n:Node {id: node.id}) SET n = node.properties RETURN count(n) AS nodes_created):

Total for 100,000 nodes: ~30.19s (~2.69s–3.38s per 10k batch)

Questions

  1. Based on Result 1, it seems to take quite a while to transfer and unpack the data even with a no-op query. Is there any way to improve this given that I’m already using neo4j-rust-ext, or is this close to the practical limit for Bolt?
  2. Based on Result 2, write performance drops significantly, and I’ve already ruled out missing indexes/constraints as the cause. Anything we can tune for the performance?

(P.S. I’ve tested dumping everything to CSV and using LOAD CSV, which takes about 7 seconds to set 10,100,000 properties. Is there any way to get closer to that speed from Python?)

Server settings:

heap.max_size=14GB
memory.pagecache.size=8GB
8-core CPU at ~300% total load when inserting nodes

Thank you!

Hi :waving_hand:

  1. or is this close to the practical limit for Bolt?

    I'm not sure there is such a thing as a practical limit. The faster the computer goes, the faster the encoding and decoding can happen. And it's not like Bolt is adding a superlinear overhead to the size of the encoded data.
    If this issue here is CPU bound (as suggested by your and my own tests), concurrency is your friend. See the example below and try to run it with a free-threaded python interpreter (i.e., a no-GIL build). You should see a decent improvement in performance (as well as a spike in CPU usage client and server side).

  2. If you are sure (or can make sure client side) that the id's are unique, try inserting with CREATE instead of MERGE. That saves a look up as well as locking the node and is significantly faster with the downside that you can end up with duplicate IDs if you don't de-duplicate the data first.

Generally, make sure you're running this on a local network with a good connection, preferably run the server on localhost even so you don't end up being bottlenecked by the network. Consider that the data you're transmitting is in the ball park of 20 MB. On a 1 Gbit connection that's 0,16 seconds for the network alone (1.6 s on 100 Mbit).

Example using concurrency:

import time
from concurrent.futures import ThreadPoolExecutor

import neo4j


URL = "neo4j://localhost:7687"
AUTH = ("neo4j", "pass")
DB = "neo4j"


def random_str(length):
    import random
    import string

    return "".join(
        random.choices(string.ascii_letters + string.digits, k=length)
    )


print("generating nodes...")
props = {str(j): random_str(10) for j in range(100)}
nodes = [
    {"id": i, "labels": [], "properties": {**props}} for i in range(100_000)
]


def chunks(all, size):
    for i in range(0, len(all), size):
        yield all[i : i + size]


create_nodes_query = """RETURN size($nodes) AS nodes_created"""


def work(driver, batch):
    start = time.perf_counter()
    with driver.session(database=DB) as session:
        c = session.execute_write(
            lambda tx, b=batch: tx.run(create_nodes_query, nodes=b).single()[
                "nodes_created"
            ]
        )
    elapsed = time.perf_counter() - start
    print(f"Inserted {c} nodes in {elapsed:.6f}s")
    return c


with (
    neo4j.GraphDatabase.driver(URL, auth=AUTH) as driver,
    ThreadPoolExecutor(max_workers=10) as executor,
):
    total = 0
    print("starting insertion...")
    gstart = time.perf_counter()
    futures = [
        executor.submit(work, driver, batch) for batch in chunks(nodes, 10000)
    ]
    for future in futures:
        c = future.result()
        total += c

    print(f"Inserted {total} nodes in {time.perf_counter() - gstart:.6f}s")