advanced
Catalyst Optimizer
10 min readLast updated: 2026-07-09
Overview
The Catalyst Optimizer is the heart of Spark SQL. Learn how it analyzes, optimizes, and compiles your queries into physical JVM execution plans.
What You Will Learn
In this lesson, you will learn:
- Query Lifecycle: Logical analysis, logical plan, physical plan stages.
- Rule-Based Optimization: Replacing plans with equivalent optimized trees.
- Cost-Based Optimization (CBO): Choosing plans based on statistical costs.
Detailed Concept Explanation
The Catalyst Optimizer automatically optimizes Spark SQL and DataFrame queries. It compiles query representations into Java bytecode executed in JVM cores.
The Optimization Lifecycle
- Analysis: Resolves table and column names against a schema catalog to produce an Analyzed Logical Plan.
- Logical Optimization: Applies rule-based transformations to optimize the plan (e.g. constant folding, predicate pushdown, projection pruning) to produce an Optimized Logical Plan.
- Physical Planning: Generates multiple physical plans and selects the most efficient plan based on Cost-Based Optimization (CBO) statistics (like table sizes or index keys).
- Code Generation: Compiles the selected physical plan into Java bytecode at runtime (using Janino compiler), running as if written by hand.
Code Examples
Python (PySpark) Implementation
python
from pyspark.sql import SparkSession
spark = SparkSession.builder.appName("Catalyst").getOrCreate()
data = [("A", 10), ("B", 20)]
df = spark.createDataFrame(data, ["key", "val"])
# Filter and select (Catalyst combines this so val is filtered first, and key is kept)
result = df.filter(df.val > 10).select("key")
result.explain(True)
Execution Plan Diagram (Python & Scala)
Execution Plan Diagram
SparkSession.builder
createDataFrame
filter(val > 10).select(key)
explain(True)
Scala Implementation
scala
import org.apache.spark.sql.SparkSession
val spark = SparkSession.builder().appName("CatalystScala").getOrCreate()
import spark.implicits._
val df = Seq(("A", 10), ("B", 20)).toDF("key", "val")
val result = df.filter($"val" > 10).select("key")
result.explain(true)
Interview Perspective
Describe the query execution phases of Spark SQL.
Spark SQL query execution follows these phases:
- An unresolved logical plan is analyzed against the Catalog.
- The analyzed logical plan is optimized using rule-based transformations.
- The optimized logical plan is translated into multiple physical plans.
- The cost-based optimizer selects the best physical plan based on database statistics.
- The selected physical plan is compiled into Java bytecode using Whole-Stage Code Generation.