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.
Glossary
Cost Model

What is a Cost Model?
A cost model is the analytical engine within a query optimizer that quantifies the efficiency of potential execution strategies.
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.
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.
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.
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.
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.
- Hash Join:
- System Constants: Formulas rely on calibrated constants (e.g.,
C_page_read,C_tuple_process) that are specific to the hardware and storage engine.
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
ANALYZEcommands or automatically as data changes. Stale statistics render the cost model ineffective.
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.
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.
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.
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 Factor | Low Cost Impact | Medium Cost Impact | High 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 |
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.
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Related Terms
A cost model is a core component of a query optimizer. To understand its role, it's essential to grasp the related concepts in query planning, estimation, and execution that it interacts with.
Cardinality Estimation
The process by which a query optimizer predicts the number of rows or graph elements (e.g., nodes, relationships) that will be returned by a specific operation in a query plan. This prediction is the most critical input to a cost model, as the estimated size of intermediate results directly drives the estimated cost of operations like joins and filters. Poor cardinality estimates are the primary cause of suboptimal plan selection in cost-based optimization.
Cost-Based Optimization (CBO)
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, CBO uses statistical metadata about the data to make informed, quantitative decisions about join ordering, access path selection, and algorithm choice.
Query Plan
A sequence of low-level physical operations (a 'plan') generated by a database optimizer to execute a high-level declarative query. The optimizer uses the cost model to assign a numerical cost to different plan variants. The final selected plan is typically the one with the lowest estimated total cost, representing the engine's best-effort strategy for efficient execution.
Explain Plan
A representation, generated by a database engine, that details the sequence of operations, chosen algorithms, and access methods it will use (or did use) to execute a given query. A key feature of an explain plan is the display of the estimated cost and estimated cardinality for each operation, allowing developers to diagnose performance issues and understand the optimizer's decisions based on the cost model.
Adaptive Query Processing (AQP)
An optimization paradigm where the query execution engine monitors runtime statistics (e.g., actual rows processed) and can dynamically modify the execution plan mid-query. This is used to correct for inaccurate predictions made during static planning, often caused by flaws in the cardinality estimation or cost model. Techniques include re-optimization and mid-query switching of join algorithms.
Heuristic Optimization
A query optimization strategy that applies a set of rule-of-thumb transformations to a query plan based on logical properties and algebraic equivalences, rather than detailed cost estimation. Examples include 'perform selections early' (predicate pushdown). It is often used as a preliminary step before cost-based optimization or in systems where building a detailed cost model is impractical.

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.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us