FullStack AI Hub
Studio
lesson depth
Mastery
not started · 0%

Spark Catalyst: Logical Plans, Physical Plans, and AQE

Trace Spark SQL queries through Catalyst analysis and rewrites into physical operators, then see how AQE adjusts shuffle stages from runtime statistics.

Freshness: current•13 min read•Data Engineering and Databases
Full Technical Reference Document

Mental model

Spark SQL turns a DataFrame or SQL expression into a logical plan, resolves it against schemas and catalog metadata, rewrites the plan, and chooses physical operators for execution. Catalyst performs the logical optimization and planning; adaptive query execution (AQE) can revise eligible physical choices after shuffle stages reveal runtime sizes and skew.

A DataFrame transformation usually records a description rather than immediately moving rows. That laziness lets Spark combine projections and filters across chained expressions. The eventual plan determines whether a filter can be pushed to a data source, which side of a join is broadcast, where an Exchange shuffles keys, and how many tasks process the resulting partitions.

Learning outcomes

  • Distinguish parsing, analysis, logical optimization, and physical planning in a Spark SQL query.
  • Explain which runtime measurements AQE uses to change a plan after a shuffle boundary.
  • Use EXPLAIN and the Spark UI to compare an expected join or partition strategy with the executed plan.

Theory

Catalyst begins with an unresolved logical tree. For SQL, the parser creates relation, projection, filter, and expression nodes; the DataFrame API builds equivalent logical operations through its methods. The analyzer resolves table and column names through the catalog, assigns types, expands aliases, and checks whether operators are valid. A missing column or incompatible expression fails here, before a task is sent to executors.

The optimizer applies rule batches to a resolved logical plan. A filter may move below a join when semantics allow it; unused columns can be pruned before a scan; constant expressions can be folded. Available table and column statistics inform cost-based decisions such as join ordering, but statistics are only as useful as their freshness and coverage. Catalyst then enumerates physical strategies supported by the query's join type and chooses operators such as a broadcast hash join or sort-merge join. The physical plan may contain an Exchange, which partitions rows across executors by a key and creates a stage boundary.

EXPLAIN EXTENDED exposes the parsed, analyzed, optimized logical, and physical plans. EXPLAIN COST includes statistics when they are available, while formatted output presents a physical-plan outline and details. Reading those plans connects source code to real cost: a Filter before a scan may reduce I/O, while a SortMergeJoin preceded by two exchanges indicates data movement on both sides. A plan that looks plausible still needs to be checked against runtime metrics.

AQE adds runtime feedback at shuffle boundaries. Spark materializes map-side shuffle output, collects actual sizes and partition statistics, and can then re-optimize remaining work. It can coalesce contiguous small post-shuffle partitions, split skewed partitions (replicating the other side where necessary), or convert a sort-merge join to a broadcast or shuffled-hash strategy when runtime sizes and configuration permit. AQE cannot recover time already spent scanning the input or writing shuffle map output, and an initial EXPLAIN taken before execution may show an adaptive plan that is not final.

Suppose a filtered join produces 8 GiB of evenly distributed shuffle data and the advisory target is 64 MiB per task. The estimated coalesced task count is:

Ncoalesced=⌈SshufflePtarget⌉N_{coalesced}=\left\lceil\frac{S_{shuffle}}{P_{target}}\right\rceil

Here S_shuffle is shuffle output in bytes, P_target is the target bytes per partition, and N_coalesced is a count of tasks. Since 8 GiB is 8,192 MiB, the estimate is 8,192 MiB / 64 MiB = 128 post-shuffle partitions, rather than 800 tiny partitions from the initial setting. Real data is uneven, so Spark may retain more partitions or split a hot partition instead of reaching exactly 128.

Join statistics can change the plan too. If the filtered dimension is 48 MiB and a 64 MiB broadcast threshold is configured, broadcasting it to 12 executors moves roughly 576 MiB of serialized payload in aggregate before transport and hash-table overhead. A sort-merge join may shuffle the much larger fact side as well. The broadcast is a useful candidate only if the built hash relation fits safely in each executor's memory; a threshold is not a proof that a broadcast is cheap.

Parse SQL or DataFrame expressions
Resolve names and types
Rewrite the logical plan
Choose physical operators
Adapt shuffle stages from runtime statistics
Conceptual teaching model synthesized from:apache-spark-docs,apache-spark-aqe-docs,spark-explain-docs

Trade-offs

Rule-based rewrites avoid moving work to the cluster when a projection or filter can reduce a scan, but the optimizer cannot infer facts that are absent from the schema, statistics, or expression semantics. Accurate table statistics can improve join ordering; collecting them costs work and stale statistics can make a previously sensible plan poor. Hints give an operator a preference, yet Spark may ignore a hint that the join type cannot support, and a forced broadcast can exhaust executor memory.

AQE can reduce task scheduling overhead for small partitions and limit the damage from skew, but it reacts after a stage has materialized. More initial shuffle partitions create smaller map outputs and finer adaptation at the cost of metadata and task scheduling. Fewer initial partitions can constrain parallelism before AQE sees the actual distribution. Choose settings from observed shuffle bytes, task duration percentiles, spill, and executor memory, not from input row count alone.

Failure modes and misconceptions

SymptomLikely mechanismInvestigation
One reducer dominates stage durationA hot key or uneven partition has concentrated work.Compare per-task input and duration; check AQE skew-join settings and key frequency before salting.
Many tiny tasks and high scheduler overheadThe initial shuffle count is excessive for the actual output.Compare map output bytes with task count and inspect whether AQE coalesced the partitions.
Broadcast join spills or executor OOMsThe build side expanded beyond the serialized estimate or was replicated too widely.Measure executor memory and relation size; remove an unconditional hint or raise the threshold only after capacity testing.
EXPLAIN differs from the Spark UIThe displayed plan was captured before AQE used completed shuffle statistics.Compare the initial adaptive plan with the final plan and per-stage SQL metrics in the UI.
Filter remains above a scanThe predicate or data source cannot support the expected pushdown.Inspect the scan's pushed filters and verify the data type and source implementation.

The optimizer does not guarantee the fastest plan for every data distribution. A logical optimization can reduce rows yet increase skew; a broadcast can remove a shuffle but create executor memory pressure. Treat plan shape as a hypothesis and confirm it with task-level evidence.

Decision scenario

A query joins a 2 TiB event table to a 48 MiB account dimension. The median stage is fast, but four reducers take six times longer because one account owns 38% of the filtered events. Keep the current query semantics, inspect the final adaptive plan and per-task shuffle metrics, then compare AQE skew splitting with a controlled key-salting experiment. Broadcast is plausible under a 64 MiB threshold, but verify the expanded hash relation fits each executor; do not increase shuffle partitions blindly when one key is the source of the tail.

Implementation pattern

This example keeps filters and required columns close to their scans, lets statistics and AQE choose the join implementation, and prints plans before running the action. The final adaptive plan and task skew should also be inspected in the Spark SQL UI after execution.

python
from pyspark.sql import SparkSession, functions as F
​
spark = SparkSession.builder.appName("catalyst-plan-review").getOrCreate()
spark.conf.set("spark.sql.adaptive.enabled", "true")
spark.conf.set("spark.sql.shuffle.partitions", "800")
spark.conf.set("spark.sql.adaptive.coalescePartitions.parallelismFirst", "false")
spark.conf.set("spark.sql.adaptive.advisoryPartitionSizeInBytes", str(64 * 1024 * 1024))
spark.conf.set("spark.sql.autoBroadcastJoinThreshold", str(64 * 1024 * 1024))
​
events = (spark.read.parquet("s3a://lake/events")
.where((F.col("event_date") >= "2026-11-01") &
(F.col("event_date") < "2026-12-01"))
.select("account_id", "request_id", "event_date"))
accounts = (spark.read.parquet("s3a://lake/accounts")
.select("account_id", "region"))
regional = (events.join(accounts, "account_id", "inner")
.groupBy("region")
.agg(F.countDistinct("request_id").alias("requests")))
regional.explain(mode="extended")
regional.explain(mode="formatted")
regional.write.mode("overwrite").parquet("s3a://reports/region-counts")
spark.stop()
Reflect before revealing the guide

Prerequisites & Related Concepts (2)

Private notes

0 words
Recommended Free Track
Free · Verifiable Credential

FS-201Production LLM Engineer

Design an observable full-stack LLM product from capability validation through interfaces retrieval evaluation security and operations.

37 concepts~35h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.

Next