Inferensys

Glossary

Cost-Based Optimization (CBO)

Cost-Based Optimization (CBO) is a query optimization strategy that evaluates multiple potential execution plans using a cost model to select the one with the lowest estimated resource consumption.
Knowledge engineer constructing knowledge base on laptop, document hierarchy visible, casual office setup.
GRAPH QUERY OPTIMIZATION

What is Cost-Based Optimization (CBO)?

Cost-Based Optimization (CBO) is the dominant query optimization paradigm in modern graph and relational database systems, used to select the most efficient execution plan from a vast search space of alternatives.

Cost-Based Optimization (CBO) is a query optimization strategy that evaluates multiple potential execution plans using a cost model to select the one with the lowest estimated resource consumption (e.g., I/O, CPU, memory). Unlike heuristic optimization, which applies fixed rules, CBO makes data-driven decisions by estimating the cardinality (number of intermediate results) for each operation, such as graph traversals, joins, and filters. This allows it to make critical decisions like optimal join ordering and index selection.

The optimizer's cost model assigns a numerical cost to operations based on statistical metadata about the data distribution, such as histograms and distinct value counts. Accurate cardinality estimation is paramount; poor estimates can lead the optimizer to choose a severely suboptimal plan. CBO is foundational for executing complex queries in labeled property graphs and RDF triplestores, enabling efficient subgraph isomorphism matching and multi-hop traversals. The final chosen plan is often inspected via an explain plan.

GRAPH QUERY OPTIMIZATION

Core Components of a CBO System

Cost-based optimization (CBO) is a query optimization strategy that evaluates multiple potential execution plans using a cost model to select the one with the lowest estimated resource consumption. A CBO system comprises several integrated components that work together to analyze a query, generate alternatives, and choose the optimal path.

01

Cost Model

The cost model is the mathematical framework that assigns a numerical cost, representing estimated resource consumption, to each operation in a potential execution plan. It is the core analytical engine of a CBO system.

  • Cost Units: Costs are abstract units (e.g., I/O page reads, CPU cycles, network transfer bytes) that model the primary bottlenecks of the system.
  • Statistical Inputs: The model relies on cardinality estimates and data distribution statistics (e.g., histograms, distinct value counts) to predict the size of intermediate results.
  • System Calibration: Effective models are calibrated to the specific hardware profile (e.g., SSD vs. HDD latency, memory bandwidth) of the deployment environment.
02

Cardinality Estimator

The cardinality estimator predicts the number of rows, nodes, or relationships that will be produced by each operation in a query plan. Accurate estimation is the single most critical factor for correct cost calculation.

  • Foundation for Costing: A join that produces 10 rows has a radically different cost than one producing 10 million. The cost model multiplies the cardinality by per-tuple cost factors.
  • Relies on Statistics: Uses pre-computed statistics like histograms on property values, degree distributions for nodes, and correlation estimates between predicates.
  • Biggest Source of Error: Estimation errors, especially for complex graph pattern joins, compound multiplicatively through a plan, leading the optimizer to choose a severely suboptimal execution path.
03

Plan Space Generator

The plan space generator is responsible for enumerating the set of semantically equivalent alternative execution plans for a given query. It applies transformation rules to explore the search space.

  • Logical Transformations: Includes query rewriting techniques like predicate pushdown, join reordering, and subquery flattening to create new logical plan shapes.
  • Physical Implementations: For each logical operator (e.g., a join), it generates multiple physical implementations (e.g., hash join, index nested loop join, merge join).
  • Search Strategy: Uses algorithms like dynamic programming or randomized search (e.g., Genetic Algorithm) to navigate the combinatorial explosion of possible plans, pruning dominated plans early.
04

Statistics Manager

The statistics manager collects, stores, and maintains the metadata about the data distribution within the knowledge graph that is essential for the cardinality estimator and cost model.

  • Data Profiling: Creates histograms for property value ranges, calculates average node degree per relationship type, and tracks the number of distinct labels.
  • Refresh Policies: Manages when statistics are updated (e.g., after a threshold of data modifications) to prevent optimization decisions from being based on stale information.
  • Storage: Maintains this metadata in a system catalog, often using compact data structures like HyperLogLog for distinct count approximations.
05

Plan Cacher

The plan cacher stores previously optimized execution plans (or their components) to avoid the computational overhead of re-optimizing identical or similar queries.

  • Keyed by Query Fingerprint: Plans are stored using a hash of the normalized query structure and relevant parameters.
  • Invalidation Logic: The cache must invalidate entries when underlying data statistics change significantly or when schema modifications affect the plan's validity.
  • Parameter Sensitivity: For parameterized queries, the system may store a single plan deemed robust or multiple plans keyed by parameter value ranges.
06

Explain & Profile Interface

The explain and profile interface provides visibility into the optimizer's decisions, allowing database engineers to diagnose performance issues and trust the system's choices.

  • Explain Plan: Outputs the chosen execution plan with estimated costs and cardinalities at each step, without running the query.
  • Profile Execution: Runs the query and collects actual runtime metrics (rows produced, time spent) for each operator, highlighting discrepancies between estimates and reality.
  • Debugging Tool: This feedback loop is essential for tuning statistics, identifying problematic query patterns, and validating the cost model's accuracy.
QUERY OPTIMIZATION STRATEGIES

CBO vs. Heuristic Optimization

A comparison of the two primary paradigms for optimizing graph and database queries, focusing on their underlying mechanisms, performance characteristics, and suitability for different workloads.

Optimization FeatureCost-Based Optimization (CBO)Heuristic Optimization

Core Principle

Selects the plan with the lowest estimated resource cost using a statistical model.

Applies a predefined set of rule-of-thumb transformations to the query plan.

Decision Basis

Relies on detailed metadata: cardinality estimates, data distribution histograms, and index statistics.

Relies on logical query structure and syntactic patterns (e.g., 'push selections down').

Plan Space Exploration

Evaluates multiple alternative execution plans (often hundreds or thousands).

Typically follows a single, deterministic transformation path.

Adaptability to Data

High. Plan choice changes with data volume, value distribution, and index availability.

Low. Rules are static and do not adapt to specific data characteristics.

Optimization Overhead

High. Requires significant CPU and memory for cost calculation and plan comparison.

Low. Rule application is generally fast with minimal computational cost.

Predictability & Consistency

Variable. Different data states can produce radically different plans for the same query.

High. The same logical query always receives the same transformed plan.

Optimality Guarantee

No guarantee, but aims for a locally optimal plan based on the cost model's accuracy.

No optimality guarantee; aims for a 'good enough' plan based on accepted wisdom.

Primary Use Case

Complex, ad-hoc analytical queries (OLAP) with joins over large, variable datasets.

Predictable, high-throughput transactional queries (OLTP) with simple, repetitive patterns.

Dependency on Statistics

Critical. Requires accurate, up-to-date statistics; degrades severely with stale metadata.

None. Operates purely on the query's syntactic form.

Handling of Correlated Data

Can model correlations if statistics (e.g., multi-column histograms) are available.

Cannot model or adapt to data correlations.

GRAPH QUERY OPTIMIZATION

Cost-Based Optimization (CBO)

Cost-Based Optimization (CBO) is a query optimization strategy that evaluates multiple potential execution plans using a cost model to select the one with the lowest estimated resource consumption.

01

Core Mechanism: The Cost Model

The cost model is the mathematical heart of CBO. It assigns an estimated numerical cost to each operation in a candidate query plan, representing predicted consumption of I/O, CPU, and network resources. Costs are derived from:

  • Cardinality estimates for intermediate results.
  • Statistical metadata (e.g., histograms, distinct value counts).
  • Hardware-specific constants (e.g., disk seek time, memory bandwidth). The optimizer's goal is to find the plan with the lowest aggregate cost, simulating execution before it runs.
02

Cardinality Estimation: The Critical Input

Accurate cardinality estimation—predicting the number of nodes, edges, or paths returned by a graph pattern—is paramount for CBO. Inaccurate estimates lead the optimizer to choose highly inefficient plans. Techniques include:

  • Maintaining statistics on label distributions, property value frequencies, and degree (connection count) histograms.
  • Using correlation-aware models for queries with multiple predicates.
  • Employing graph sampling to estimate the selectivity of complex path patterns, which is notoriously difficult in interconnected data.
03

Plan Space Exploration

The optimizer explores a vast space of semantically equivalent execution plans. For a graph query, this involves evaluating permutations of:

  • Join/Expand Ordering: The sequence in which nodes and relationships are matched (e.g., (a)-[:KNOWS]->(b)-[:WORKS_AT]->(c)).
  • Physical Operators: Choosing between a traversal, an index seek, or a hash join for each step.
  • Predicate Application: Deciding when to filter properties (WHERE n.name = 'Alice'). Algorithms like dynamic programming or heuristic branch-and-bound search are used to navigate this combinatorial space efficiently.
04

Graph-Specific Cost Factors

CBO in graph systems must model costs unique to graph traversal:

  • Traversal Cost: Function of average degree, fan-out, and path depth. A deep, branching traversal has high cost.
  • Index Utilization: Cost of an index seek on a node label/property vs. a full label scan.
  • Cache Locality: Leveraging index-free adjacency—where nodes store direct pointers to neighbors—dramatically reduces the I/O cost of traversals compared to index lookups.
  • Intermediate Result Size: The cost of materializing intermediate path results in memory, which can explode with poor join ordering.
05

Contrast with Heuristic Optimization

CBO is often contrasted with Heuristic Optimization (Rule-Based Optimization).

  • Heuristic: Applies fixed rules (e.g., 'apply selective filters early', 'use index if available') based on logical query structure. It is fast and predictable but can't adapt to data distribution.
  • CBO: Uses a data-driven cost model. It can make counter-intuitive choices (e.g., using a seemingly non-selective index) that are optimal for the specific data, leading to better performance for complex, variable queries. Modern optimizers typically combine both: use heuristics to prune the plan space, then apply CBO to choose the best among the remaining candidates.
06

Adaptive & Runtime Optimization

To mitigate errors in static cost estimates, systems employ Adaptive Query Processing (AQP). If runtime statistics (e.g., actual cardinality) deviate significantly from estimates, the engine can:

  • Re-optimize mid-query, switching to a better execution strategy.
  • Use progressive sampling to refine cardinality estimates before full execution.
  • Employ materialization points to avoid re-computing expensive sub-plans. This creates a feedback loop, making CBO systems more robust to statistical anomalies and changing data.
COST-BASED OPTIMIZATION (CBO)

Frequently Asked Questions

Cost-based optimization (CBO) is the dominant strategy in modern database and graph query engines for selecting the most efficient execution plan. It moves beyond simple rule-of-thumb heuristics by using a detailed cost model to estimate and compare the resource consumption of many alternative plans. This section answers the most common technical questions about how CBO works, its core components, and its application in graph databases.

Cost-based optimization (CBO) is a query optimization strategy that evaluates multiple potential execution plans using a cost model to select the one with the lowest estimated resource consumption (e.g., I/O, CPU, memory, network). It works by generating a space of semantically equivalent plans, estimating the cost of each operation within those plans based on database statistics, and choosing the plan with the minimal aggregate cost.

The process typically involves four stages:

  1. Logical Plan Generation: The query parser transforms the declarative query (e.g., Cypher, SPARQL, SQL) into an initial logical plan tree.
  2. Plan Space Exploration: The optimizer applies equivalence rules (e.g., join commutativity, predicate pushdown) to generate numerous alternative logical plans.
  3. Cost Estimation: For each candidate plan, the optimizer's cost model uses cardinality estimates and system parameters (e.g., disk seek time) to calculate a numerical cost for each operation (scan, join, filter).
  4. Plan Selection: The plan with the lowest total estimated cost is selected for conversion into a physical execution plan.
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.