Inferensys

Glossary

Cost Model

A cost model is a component of a query optimizer that assigns a numerical cost, representing estimated resource usage (e.g., I/O, CPU, network), to each operation in a potential execution plan.
ML engineer managing model versions on laptop, version history visible, technical Git-like workflow.
GRAPH QUERY OPTIMIZATION

What is a Cost Model?

A cost model is the analytical engine within a query optimizer that quantifies the efficiency of potential execution strategies.

A cost model is a component of a query optimizer that assigns a numerical cost, representing estimated resource usage such as I/O, CPU cycles, and network transfer, to each operation in a potential execution plan. This quantitative framework enables cost-based optimization (CBO), allowing the system to compare thousands of alternative plans—varying in join ordering, index selection, and algorithm choice—to select the most efficient one before execution begins.

In graph databases, the cost model must account for unique operations like graph traversal and subgraph isomorphism matching. It relies heavily on cardinality estimation to predict the size of intermediate results, such as the number of nodes matching a label or the fan-out of relationships. Accurate models incorporate statistics on graph topology and property distributions, enabling optimizations like predicate pushdown to filter data early and minimize expensive computational work.

QUERY OPTIMIZATION

Key Components of a Cost Model

A cost model is the analytical engine within a query optimizer. It assigns a numerical cost, representing estimated resource consumption, to each operation in a potential execution plan. Its accuracy directly determines the optimizer's ability to select the fastest, most efficient plan.

01

Cardinality Estimation

The foundational input for any cost model. It predicts the number of intermediate results (e.g., rows, nodes, edges) that will be produced by each operation in a query plan. Inaccurate estimates are the primary cause of poor plan selection.

  • Mechanism: Uses statistics (histograms, distinct value counts) and assumptions about data distribution.
  • Challenge: Correlated predicates and complex graph patterns often violate independence assumptions, leading to significant estimation errors.
  • Example: Estimating the result size of a multi-hop path query in a social network graph.
02

Cost Units and Metrics

The abstract or concrete units used to quantify resource consumption. A cost model translates physical resource usage into a single, comparable numerical score.

  • Common Metrics:
    • I/O Cost: Number of disk page reads/writes.
    • CPU Cost: Number of CPU cycles for operations like predicate evaluation, hash table construction, or tuple comparison.
    • Network Cost: Amount of data transferred across a cluster (for distributed graphs).
    • Memory Cost: Working memory required for operations like sorts and joins.
  • Weighting: The cost model applies weights to different metrics (e.g., I/O is often 10x more expensive than CPU) based on the target hardware profile.
03

Operator Cost Formulas

Mathematical functions that calculate the cost of a specific database operation based on its input cardinality and system parameters.

  • Scan Operations: Cost = Pages_in_Relation * C_page_read.
  • Join Operations: Vary dramatically by algorithm:
    • Hash Join: Cost = (Build_Cardinality * C_hash) + (Probe_Cardinality * C_lookup).
    • Index Nested Loop Join: Cost = Outer_Cardinality * (C_index_lookup + C_fetch).
    • Graph Traversal: Cost = Start_Vertices * (Fanout ^ Depth) * C_edge_follow, where fanout is estimated average degree.
  • System Constants: Formulas rely on calibrated constants (e.g., C_page_read, C_tuple_process) that are specific to the hardware and storage engine.
04

Statistics and Metadata

The empirical data about the stored data that feeds the cardinality estimator and cost formulas. Without accurate statistics, the cost model operates on guesses.

  • Core Statistics: Table/Graph size, number of distinct values per attribute/label, value histograms, correlation statistics.
  • Graph-Specific Statistics: Degree distribution histograms, label frequencies, relationship selectivity.
  • Maintenance: Statistics must be updated periodically via ANALYZE commands or automatically as data changes. Stale statistics render the cost model ineffective.
05

Plan Space Enumeration

The process of generating alternative execution plans for a given query. The cost model is applied to each candidate plan to find the cheapest. The optimizer does not evaluate all possible plans (combinatorial explosion) but uses strategies to prune the search space.

  • Join Ordering: For a query joining N tables/patterns, there are N! possible orders. Dynamic programming (e.g., System R optimizer) is used to find the optimal order without exhaustive search.
  • Algorithm Selection: For each operation (e.g., a join), the optimizer must choose among algorithms like hash join, merge join, or index nested loop join, each with its own cost formula.
  • Access Path Selection: Deciding whether to use a full scan, an index scan, or an index-only scan for data retrieval.
06

Calibration and Tuning

The process of adjusting the cost model's internal parameters to reflect the actual performance characteristics of the underlying hardware and software stack. A default, uncalibrated model often performs poorly.

  • System Constants: Key parameters like sequential I/O cost, random I/O cost, and CPU tuple cost must be measured or tuned.
  • Methods:
    • Micro-benchmarking: Running controlled, low-level operations to measure their actual latency.
    • Feedback Loop: Using execution feedback from actual queries to adjust future estimates (a form of adaptive optimization).
  • Impact: Proper calibration can lead to order-of-magnitude performance improvements for complex analytical and graph queries.
GLOSSARY

How a Cost Model Works in Query Optimization

A cost model is the analytical engine within a query optimizer that quantifies the efficiency of potential execution plans.

A cost model is a component of a query optimizer that assigns a numerical cost, representing estimated resource usage (e.g., I/O, CPU, network), to each operation in a potential execution plan. It enables cost-based optimization (CBO) by allowing the optimizer to compare thousands of semantically equivalent plans and select the one with the lowest predicted cost. This cost is an abstract unit, not a direct measure of time or money, but a proxy for total system load.

The model's accuracy depends on cardinality estimation—predicting how many intermediate results each operation will produce. It uses statistics about data distribution, index selectivity, and hardware performance characteristics. In graph databases, costs are assigned to operations like label scans, property lookups, and graph traversals, with the goal of minimizing expensive random I/O and maximizing sequential access and memory efficiency.

GRAPH QUERY OPTIMIZATION

Common Cost Factors and Their Impact

A comparison of key factors that influence the estimated cost of different graph query execution plans, as evaluated by a cost-based optimizer.

Cost FactorLow Cost ImpactMedium Cost ImpactHigh Cost Impact

Intermediate Result Size

Small, filtered subgraph (< 1k nodes)

Moderate subgraph (1k - 100k nodes)

Large, unfiltered subgraph (> 100k nodes)

Join/Pattern Ordering

Selective patterns evaluated first

Moderately selective order

Unselective patterns evaluated first, creating large intermediates

Index Utilization

Unique property lookup or label scan

Non-unique index scan

Full label scan (no index)

Traversal Depth

Shallow traversal (depth 1-2)

Medium traversal (depth 3-5)

Deep or unbounded traversal (depth > 5)

Data Locality / Partitioning

Traversal stays within a single partition

Traversal crosses 2-3 partitions

Traversal requires cross-partition communication for most steps

Predicate Selectivity

Highly selective filter (> 90% rows filtered)

Moderately selective filter (50-90% filtered)

Non-selective filter (< 50% filtered)

Algorithm Choice

Index nested loop join for small sets

Hash join for medium sets

Cartesian product (worst-case)

Memory vs. I/O Trade-off

In-memory processing of intermediates

Spill to disk for large sorts/joins

Repeated I/O for un-cached data

COST MODEL

Frequently Asked Questions

A cost model is a core component of a query optimizer that assigns a numerical cost, representing estimated resource usage, to each operation in a potential execution plan. These FAQs address its function, components, and role in graph query optimization.

A cost model is a mathematical framework within a database or graph query optimizer that estimates the computational expense of different query execution strategies. It assigns a numerical cost to each low-level operation (e.g., index scan, join, filter) in a potential execution plan. This cost is a proxy for expected resource consumption, including I/O operations, CPU cycles, memory usage, and network transfer. The optimizer uses these estimates to compare thousands of alternative plans and select the one with the lowest predicted total cost, a process central to cost-based optimization (CBO). Without an accurate cost model, an optimizer would rely solely on heuristic rules, often resulting in suboptimal performance for complex queries.

Prasad Kumkar

About the author

Prasad Kumkar

CEO & MD, Inference Systems

Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.

His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.