Sub topic 17
Reading query plans, shuffles and caching
This chapter assumes you can build DataFrames, chain transformations, and run an action such as show() or count() in a Databricks notebook. It also assumes you know that transformations are lazy. You will learn to read the output of explain(), spot shuffles, and decide when cache() helps.
Why plans matter
When you call a transformation, Spark records what you asked for. It does not run anything yet. When you call an action, the Catalyst optimizer turns your request into an optimized plan and then into a physical plan. The physical plan is what the cluster executes.
If a cell is slow, the plan usually shows why. It tells you what Spark reads, how it joins, and where it moves data between machines.
Calling explain
Start with a join from earlier in the tutorial. explain() prints the physical plan without running the query.
from pyspark.sql import functions as F
orders = spark.createDataFrame(
[
(1, "alice", "2024-01-05", 120.0),
(2, "bob", "2024-01-06", 75.5),
(3, "alice", "2024-02-10", 30.0),
(4, "carol", "2024-02-11", None),
],
"order_id INT, customer STRING, order_date STRING, amount DOUBLE",
)
orders = orders.withColumn("order_date", F.to_date("order_date"))
customers = spark.createDataFrame(
[("alice", "US"), ("bob", "DE")],
"customer STRING, country STRING",
)
joined = orders.join(customers, on="customer", how="left")
joined.explain()You can ask for more detail with a mode argument:
joined.explain("formatted")prints a numbered, easier-to-read layout.joined.explain("extended")also prints the parsed, analyzed and optimized logical plans.joined.explain("cost")adds size statistics when Spark has them.
How to read a plan
Read a physical plan from the bottom up. The bottom nodes read data. Each node above it transforms the output of the node below.
The names you will see most often are:
| Node | Meaning |
|---|---|
| `Scan` / `FileScan` | Reads files or a table. Look here for pushed filters and the columns selected. |
| `Filter` | Drops rows that fail a condition. |
| `Project` | Chooses or computes columns. |
| `Exchange` | A shuffle: data is redistributed across the cluster. |
| `HashAggregate` | Computes aggregates. A partial one runs before a shuffle and a final one runs after it. |
| `BroadcastHashJoin` | Sends the small side to every executor, so the large side is not shuffled. |
| `SortMergeJoin` | Shuffles and sorts both sides, then merges them. |
| `AdaptiveSparkPlan` | Adaptive query execution (AQE) may change the plan while the query runs. |
Two things to know about the output:
- Plans for small in-memory data such as the example above may show a
LocalTableScaninstead of a file scan. - With AQE on,
explain()shows the initial plan. The final plan can differ, and you can see it in the Spark UI after the query runs.
What a shuffle is
A shuffle moves rows between machines so that rows with the same key end up on the same partition. It writes intermediate data to disk and sends it over the network. It is usually the most expensive part of a query.
In a plan, a shuffle appears as an Exchange node. Operations that commonly cause one are:
groupByaggregations- joins that cannot use a broadcast
distinctanddropDuplicatesorderByon the whole dataset- window functions with
partitionBy
Operations such as select, filter and withColumn do not need a shuffle. Each partition handles its own rows.
The partial aggregate step is why aggregations are cheaper than they look. Each partition first shrinks its own data, so less data crosses the network.
Spotting a shuffle in your own query
Run explain() on a grouped query and find the Exchange.
summary = (
orders
.groupBy("customer")
.agg(
F.count("*").alias("order_count"),
F.sum("amount").alias("total_amount"),
)
)
summary.explain()You should see a HashAggregate above an Exchange hashpartitioning(customer, ...), above another HashAggregate. Compare that with a plain filter:
orders.filter(F.col("amount") > 50).explain()This plan has no Exchange, so it needs no shuffle.
Broadcast joins
When one side of a join is small, Spark can send a full copy to every executor. The large side then stays where it is. This removes the shuffle of the large table.
Spark chooses this automatically when it believes one side is below spark.sql.autoBroadcastJoinThreshold, which is 10 MB by default. You can request it with a hint.
hinted = orders.join(F.broadcast(customers), on="customer", how="left")
hinted.explain()Look for BroadcastHashJoin in the output. The hint is a request. Spark can still refuse it for some join types, and a broadcast of a table that is too large can run the driver or executors out of memory.
Caching
cache() tells Spark to keep a DataFrame's result so later actions can reuse it. It is lazy too. Nothing is stored until an action runs.
joined = orders.join(customers, on="customer", how="left")
joined.cache()
joined.count() # an action that materializes the cacheAfter this, further actions on joined read the stored data instead of repeating the scan and the join. Release the memory when you are done:
joined.unpersist()When caching helps
- You reuse one expensive result several times in the same notebook session.
- The result is much smaller than the source data, for example after a heavy filter or aggregation.
- You are exploring interactively and each step runs actions on the same base DataFrame.
When caching does not help
- You use the result only once. Caching adds cost and gives nothing back.
- The data is large. It can spill to disk or be evicted, and then you pay for storing it and recomputing it.
- The underlying files change. A cached result can be stale until you unpersist and recompute.
- You cache too early. Cache after the expensive work you want to reuse, not on the raw input.
Checking that the cache is used
Run explain() after caching. A cached DataFrame appears as InMemoryTableScan with an InMemoryRelation under it. If you do not see these nodes, the cache was not filled yet or Spark is not using it.
The Spark UI has a Storage tab. It lists cached DataFrames with their size and the share held in memory.
Common mistakes
- Calling
cache()and never running an action. Nothing is stored. Runcount()or another action. - Using
count()to fill the cache and expecting the whole dataset to be stored. Some operations may read only part of the data, so check the Storage tab if the numbers matter. - Reading
explain()top down. The data flow starts at the bottom. - Assuming a hint always works. Confirm in the plan that you got a
BroadcastHashJoin. - Caching to fix a slow query without looking at the plan. A missing filter, a skewed key or an unneeded shuffle is usually the real cause.
- Forgetting
unpersist(). Cached data holds cluster memory for the whole session.
A short workflow for a slow cell
- Find the action that triggers the work. Earlier lines are lazy.
- Run
explain("formatted")on the DataFrame. - Read from the bottom. Check the scan for the columns and filters you expect.
- Count the
Exchangenodes and ask whether each one is needed. - Check the join type. Look for a
SortMergeJoinwhere a small table could be broadcast. - Open the Spark UI for the finished query and look for a few tasks that take much longer than the rest. That points to skew.
- Cache only a result you will reuse.
Exercise
You run df.groupBy("customer").count().explain(). Where in the output do you find the shuffle, and which two nodes surround it?
Show answer
The shuffle is the Exchange hashpartitioning(customer, ...) node. A partial HashAggregate sits below it, which runs on each partition before the shuffle. A final HashAggregate sits above it, which combines the partial results after rows with the same customer are together.
Exercise
A teammate writes big.cache() and then runs big.filter(...).show() once. The next cell reads big again in a different notebook session after the cluster restarts. Does the cache help in either case, and why?
Show answer
Neither case benefits. cache() is lazy, and the single show() fills the cache only as far as that action reads, with no later action to reuse it. After a restart, or in a different session, the cached data does not exist, because the cache lives in the memory and disk of the running cluster for the current session.