Explain, Profile, Selectivity and Connection Management

Article · 6:00

Reading explain and profile for all three languages, Neptune's indexing, traversal selectivity, connection pooling and the limits, and throughput testing.

Neptune's indexing is not something you configure, and that is the first thing to understand. There are no user-defined indexes. Neptune maintains its own internal index structures - for the property graph, indexes on subject-predicate-object orderings internally; for RDF, the standard triple-pattern indexes. You cannot add an index, and you cannot choose one. So the performance levers are: the shape of the query, the selectivity of your starting pattern, and the instance size.

That makes selectivity the whole of query tuning here. The question for every query is "how many elements does my first pattern match, and how does that number grow at each step?" A traversal starting from a specific vertex by id is one element; one starting from hasLabel('Person') is every person. There is no index to add that changes this - you change the query.

Explain and profile exist for all three languages and report different things:

  • Gremlin explain() shows the compiled traversal strategy and which steps were folded into native operations - the thing to look for is a step that was not optimised, which appears as a NeptuneTraverserConverterStep or similar and often means a step Neptune cannot push down.
  • Gremlin profile() runs it and reports per-step counts and times.
  • openCypher explain returns a plan, as a query hint in the request.
  • SPARQL explain returns the query plan, with the join order.

The number to look for in all three is the same: where the cardinality grows. A step that takes 50 elements to 5,000,000 is the step to fix, and the fix is a more selective predicate earlier, a bounded repeat, or a different traversal direction.

Connection management is more consequential in Neptune than in most databases, for three reasons. First, the connection limit is tied to instance size and is low on small instances. Second, the reader endpoint is DNS round-robin, so a pool created at startup pins itself to whichever replicas DNS returned then - and a pool that never reconnects will never discover a new replica. Third, Gremlin over WebSocket holds a long-lived connection, so pooling behaviour differs from HTTP.

The practical rules: size the pool deliberately against the instance's limit; set a connection lifetime so the pool rediscovers the reader endpoint's DNS; handle ConcurrentModificationException and the retryable AWS errors; and monitor NumConnections and the pending request queue, because a full request queue is the symptom of too few connections or too many.

Throughput testing has one Neptune-specific caveat worth stating: Serverless scales on load, over minutes, so a benchmark that ramps instantly measures the scaling rather than the steady state. Warm up, hold, then measure. And measure from inside the VPC, because otherwise you are measuring your bastion.

Laboratory exercise 4 - a measured improvement.

Load at least five million vertices and twenty million edges. Declare a baseline: five queries with p50, p95 and p99 measured from inside the VPC, plus the explain or profile output for each.

Demonstrate selectivity: take one query and write it three ways - starting from a specific vertex by id, from a property predicate, and from a label - and record the profile and the latency for each. The progression is the module's main artefact, and it demonstrates that the query is the only lever.

Trace cardinality growth: profile a three-hop traversal and record the element count at each step. Then reverse the direction and compare.

Compare the same five queries in Gremlin and openCypher, recording latency and explain output, and note any case where one is substantially faster.

Measure the connection limit: open connections until refused, and record the number. Then run a benchmark at 50%, 100% and 150% of that number and record the latency and error rate at each.

Demonstrate the reader endpoint DNS problem: create a pool, add a replica, and show that existing connections never use it. Then set a connection lifetime and show it discovered.

Finally, if on Serverless, demonstrate the scaling delay: apply a sudden 10x load and record the latency until capacity catches up.

Deliverable: the benchmark report with percentiles and plans at each step, the three-way selectivity comparison, the cardinality trace in both directions, the Gremlin-against-openCypher comparison, the connection limit with the three load levels, the DNS rediscovery demonstration, and the Serverless scaling curve.

# ==================================================================
# *** THERE ARE NO USER-DEFINED INDEXES. Understand this first. ***
# ==================================================================
# Neptune maintains its own internal index structures and you CANNOT
# ADD ONE, CANNOT CHOOSE ONE, and CANNOT HINT ONE.
#
# So the performance levers are exactly three:
#   1. THE SHAPE OF THE QUERY
#   2. THE SELECTIVITY OF THE STARTING PATTERN
#   3. THE INSTANCE SIZE
#
# *** WHICH MAKES SELECTIVITY THE WHOLE OF QUERY TUNING HERE. ***
# In Neo4j the answer to a slow query is often "add an index". Here
# there is no such answer. You change the query.

# ==================================================================
# *** DEMONSTRATE SELECTIVITY. The module's main artefact. ***
# ==================================================================
# The SAME logical question, three starting points:

# A. From a SPECIFIC VERTEX BY ID - one element:
%%gremlin
g.V('p-0001').out('HAS_EMAIL').in('HAS_EMAIL').hasLabel('Person')
  .dedup().limit(50).profile()
#   starting elements: 1            -> ~8 ms

# B. From a PROPERTY PREDICATE - however many match:
%%gremlin
g.V().has('Person','email','ada@example.test')
  .out('HAS_EMAIL').in('HAS_EMAIL').hasLabel('Person')
  .dedup().limit(50).profile()
#   starting elements: 1 (but found by a predicate)  -> ~14 ms

# C. From a LABEL - every Person:
%%gremlin
g.V().hasLabel('Person')
  .out('HAS_EMAIL').in('HAS_EMAIL').hasLabel('Person')
  .dedup().limit(50).profile()
#   starting elements: 5,000,000    -> times out at 120 s
#
# C IS NOT FIXABLE WITH AN INDEX. There is no index to add. The
# three latencies are the lesson.

# ==================================================================
# EXPLAIN AND PROFILE, in all three languages.
# ==================================================================
%%gremlin
g.V().has('Person','email','ada@example.test').out('HAS_EMAIL').explain()
#   Shows the COMPILED strategy and which steps were folded into
#   NATIVE operations. *** THE THING TO LOOK FOR IS A STEP THAT WAS
#   NOT OPTIMISED *** - it appears as a converter/traverser step and
#   usually means a step Neptune cannot push down, so it is being
#   evaluated in the Gremlin layer over materialised results.

%%gremlin
g.V('p-0001').out().out().out().dedup().profile()
#   Per-step counts and times:
#     NeptuneGraphQueryStep   count 1
#     NeptuneTraverserConverterStep count 412
#     ... count 184,203            <- THE STEP TO FIX
#     ... count 11,420,117         <- or this one

%%oc
EXPLAIN MATCH (p:Person)-[:HAS_EMAIL]->(e:Email) RETURN count(*)

%%sparql
EXPLAIN SELECT ?s WHERE { ?s foaf:name ?n . ?s foaf:mbox ?m }
#   SPARQL's plan shows the JOIN ORDER, which is the equivalent
#   lever: the engine chooses it, and a selective pattern first is
#   what lets it choose well.

# *** THE NUMBER TO LOOK FOR IS THE SAME IN ALL THREE: WHERE THE
# *** CARDINALITY GROWS. *** A step taking 50 elements to 5,000,000
# is the step to fix, and the fixes are: a more selective predicate
# EARLIER, a BOUNDED repeat, or a DIFFERENT DIRECTION.

# Trace it, then reverse it:
%%gremlin
g.V('p-0001').out('HAS_DEVICE').in('HAS_DEVICE').out('HAS_EMAIL').profile()
%%gremlin
g.V('p-0001').out('HAS_EMAIL').in('HAS_EMAIL').out('HAS_DEVICE').profile()
#   The same logical set, very different costs, depending on which
#   side has the lower degree. Measure both, every time.

# ==================================================================
# *** CONNECTION MANAGEMENT: more consequential here than usual. ***
# ==================================================================
# THREE reasons:
#
# 1. *** THE CONNECTION LIMIT IS TIED TO INSTANCE SIZE and is LOW on
#    small instances. *** Measure yours - open connections until
#    refused, and record the number:
#      CloudWatch: NumConnections
#                  MainRequestQueuePendingRequestsCount
#    A FULL REQUEST QUEUE is the symptom of TOO FEW connections OR
#    TOO MANY, so the metric alone does not tell you which - run the
#    benchmark at 50%, 100% and 150% of the limit to find out.
#
# 2. *** THE READER ENDPOINT IS DNS ROUND-ROBIN. *** A pool created
#    at startup PINS ITSELF to whichever replicas DNS returned then,
#    and A POOL THAT NEVER RECONNECTS WILL NEVER DISCOVER A NEW
#    REPLICA. Demonstrate it: create a pool, add a replica, and show
#    the existing connections never use it.
#    *** THE FIX IS A CONNECTION LIFETIME *** so the pool
#    re-resolves DNS periodically:
#      # gremlin-python
#      DriverRemoteConnection(
#          'wss://identity-graph.cluster-ro-abc...:8182/gremlin', 'g',
#          pool_size=8,
#          max_workers=8,
#          message_serializer=GraphSONSerializersV2d0())
#      # and recreate the connection on a schedule, or use a pool
#      # implementation with a max connection age
#
# 3. *** GREMLIN OVER WEBSOCKET HOLDS A LONG-LIVED CONNECTION ***, so
#    pooling behaviour differs from openCypher and SPARQL over HTTP.
#    An HTTP client with keep-alive has the same DNS problem for the
#    same reason.
#
# THE PRACTICAL RULES:
#   * size the pool DELIBERATELY against the instance's limit
#   * SET A CONNECTION LIFETIME so DNS is rediscovered
#   * handle ConcurrentModificationException AND the retryable AWS
#     errors (throttling, a brief unavailability during failover)
#   * monitor NumConnections and the pending request queue

# ==================================================================
# THROUGHPUT TESTING: two Neptune-specific caveats.
# ==================================================================
# 1. *** SERVERLESS SCALES ON LOAD, OVER MINUTES. *** A benchmark
#    that ramps instantly MEASURES THE SCALING, not the steady
#    state. Warm up, hold, THEN measure. Record the scaling curve
#    separately - it is the number that matters for a spiky workload.
#      CloudWatch: ServerlessDatabaseCapacity
#
# 2. *** MEASURE FROM INSIDE THE VPC. *** From a bastion or a VPN you
#    are measuring your tunnel. Run the load generator on an EC2
#    instance in the same subnets.
#
# The metrics that matter:
#   GremlinRequestsPerSec / OpenCypherRequestsPerSec / SparqlRequestsPerSec
#   GremlinHttp5xx, GremlinErrors
#   MainRequestQueuePendingRequestsCount   <- backpressure
#   CPUUtilization, FreeableMemory
#   BufferCacheHitRatio                    <- the graph in memory
#   NeptuneReplicaLag
#   ServerlessDatabaseCapacity
#
#   *** BufferCacheHitRatio is the closest analogue to Neo4j's page
#   *** cache hit ratio, and it matters for the same reason: if the
#   *** working set does not fit, every hop is a storage read. ***
#   A low ratio is an instance-size problem, and it is one of the
#   few Neptune performance problems that money does fix.

Discussion

No questions on this topic yet. Sign in to ask the first one.