Sub topic 1
How Spark executes a query
Prerequisites
This chapter assumes you have:
- Basic SQL: SELECT, JOIN, GROUP BY.
- Some familiarity with Databricks workspaces, clusters or SQL warehouses.
- A basic idea of what a Delta table is.
- Awareness of Spark terms such as DataFrame, stage and task. This chapter explains them again in the context of performance.
Later chapters build on this one. Photon, query plans, the Query Profile and join strategies all refer to the stages, tasks and shuffles described here.
The working model
When you run a query, Spark does not execute your SQL text directly. It turns the query into a plan and then splits that plan into units of parallel work. Knowing these steps tells you where time can go.
- Parse and analyze. Spark checks the syntax, then resolves table and column names against the catalog. A DataFrame expression and a SQL statement end up in the same internal form.
- Optimize. The Catalyst optimizer rewrites the logical plan. It pushes filters down toward the data source, prunes unused columns, and reorders or simplifies expressions.
- Plan physically. Spark picks concrete operators, such as a scan, a hash aggregate, or a broadcast hash join. It chooses them using statistics when it has them.
- Split into stages and tasks. The physical plan is cut into stages, and each stage runs as many parallel tasks.
- Execute on the cluster. The driver schedules tasks, and executors run them.
Driver, executors and partitions
The driver is the process that plans the query and schedules the work. Executors are processes on the worker nodes that run tasks and hold data in memory or on local disk.
Data is split into partitions. A partition is a slice of the data that one task processes. If a stage reads 200 partitions, it runs 200 tasks. Each task uses one CPU core at a time, so the number of cores in your cluster sets how many tasks run at once.
This has a practical consequence. If you have 16 cores and 200 tasks, tasks run in waves. If you have 200 cores but only 4 partitions, 196 cores sit idle. Both cases are slow for different reasons.
Narrow and wide operations
Spark classifies operations by how they move data.
| Kind | Examples | Data movement |
|---|---|---|
| Narrow | filter, select, simple expressions | Each output partition depends on one input partition. No data moves between tasks. |
| Wide | GROUP BY, most joins, ORDER BY, DISTINCT | Rows with the same key must end up together, so data moves between executors. |
Narrow operations are cheap and are chained together inside one task. Wide operations require a shuffle.
Shuffles and stage boundaries
A shuffle redistributes data across the cluster so that related rows land in the same partition. Each task in the earlier stage writes its output into shuffle files, split by the target partition. Each task in the later stage then fetches its slice from every earlier task, over the network.
Shuffles are usually the most expensive part of a query because they combine several costs:
- Serializing data and writing it to local disk.
- Sending it over the network.
- Waiting for the slowest task before the next stage can start.
- Possible spill, which happens when a task's data does not fit in memory and Spark writes the overflow to disk.
A shuffle is also where Spark cuts the plan into stages. All the narrow work between two shuffles runs together as one stage. A stage cannot begin until the stage it reads from has finished.
Consider this query:
SELECT c.region, SUM(o.amount) AS total
FROM orders o
JOIN customers c ON o.customer_id = c.customer_id
WHERE o.order_date >= '2024-01-01'
GROUP BY c.region;A plausible execution has these stages:
- Scan
orders, apply the date filter, and prepare for the join. - Scan
customers. - Shuffle both sides by
customer_id, then join them and compute a partial sum per region. - Shuffle by
region, then compute the final sum.
The join and the GROUP BY each need data grouped by a different key. That is why there are two shuffles. If customers is small, Spark can avoid the first shuffle with a broadcast join, which a later chapter covers.
Where time goes inside a task
A task is a loop over the rows or batches in its partition. Its time breaks down into a few parts:
- Reading input. Fetching files from cloud storage and decoding Parquet. Reading fewer files or fewer columns is the most direct saving.
- Computing. Evaluating expressions, filters, hash tables for joins and aggregates.
- Shuffle read and write. Moving data between stages.
- Waiting and overhead. Scheduling delay, garbage collection, and idle time while other tasks finish.
Most tuning in this tutorial reduces one of these. Layout and data skipping reduce reading. Statistics and join choices reduce shuffling. Photon speeds up the computing part.
The computing part matters here because standard Spark runs it on the JVM (Java Virtual Machine). The next chapters explain how that path processes data and how Photon replaces it with native code for supported operators. Photon changes how a task computes. It does not change the stage and shuffle structure described in this chapter.
Lazy evaluation and actions
Spark builds plans lazily. Transformations such as filter, select and join only add to the plan. Work starts when an action runs, such as count, collect, write, or displaying results in a notebook. A SQL statement is an action in itself.
Lazy evaluation lets the optimizer see the whole query before running anything. It also has a side effect when you time code. A cell that defines transformations may finish instantly because nothing ran. Always time a full action, such as writing results or calling count().
from pyspark.sql import functions as F
orders = spark.table("orders")
# Nothing executes here. These lines only build a plan.
plan = (
orders
.filter(F.col("order_date") >= "2024-01-01")
.groupBy("customer_id")
.agg(F.sum("amount").alias("total"))
)
# The action triggers execution.
print(plan.count())Common errors and edge cases
- Too few partitions. Large partitions cause long tasks and can spill to disk. Cores are left idle.
- Too many tiny partitions. Each task has a fixed scheduling cost. Thousands of tiny tasks can spend more time starting than working.
- Skewed keys. If one key holds most of the rows, one task in a shuffle stage does most of the work. The whole stage waits for it. Adaptive query execution can help, and a later chapter covers it.
- Treating a stage count as a cost measure. More stages do not always mean slower. A stage that moves little data can be cheap, and one stage that moves terabytes can dominate the query.
- Timing only the definition. Because of lazy evaluation, the first action often absorbs the whole cost, including reading metadata and warming up.
- Assuming a tuning change alters the plan shape. Many changes only affect how fast tasks run. Check the plan, not only the clock.
Connecting this to the rest of the tutorial
You now have the vocabulary used in the rest of the tutorial:
- A query becomes a plan, then stages, then tasks.
- Shuffles separate stages and are usually the costliest step.
- Task time splits into reading, computing and moving data.
The next chapter looks at the compute part more closely and explains why processing data in columns and in batches is faster than processing it row by row.
Exercise
A query joins a large orders table to a customers table and then runs GROUP BY on region. The Spark UI shows two shuffles. Why are there two, and which part of a task's time does a shuffle add to?
Show answer
The join needs rows with the same customer_id together, and the GROUP BY needs rows with the same region together. Each regrouping by a different key requires its own shuffle, and each shuffle also marks a stage boundary. A shuffle adds to the "shuffle read and write" part of task time: serializing, writing to local disk, network transfer, and waiting for the slowest task. It can also add spill if partitions do not fit in memory.
Exercise
You have a cluster with 64 cores. A stage has only 8 partitions. What happens, and what two kinds of fix could you consider?
Show answer
Only 8 tasks run, so 56 cores are idle and the stage takes as long as its largest partition requires. You could increase the number of partitions, for example by repartitioning or by changing the shuffle partition setting, so more tasks run in parallel. You could also check whether the source data is in too few large files and fix the file layout.