Sub topic 7
Spark as the engine underneath
This chapter assumes you know basic SQL and Python, and that you have seen the compute options (clusters, SQL warehouses, serverless) from the previous chapter. You do not need prior Spark experience.
Why Spark sits under the platform
Apache Spark is an open source engine for processing data in parallel across many machines. Databricks was founded by the people who created Spark, and Spark is the main engine behind notebooks, jobs, and SQL on the platform. When you run a query against a Delta table, Spark (or Photon, a native engine that Databricks runs under the Spark API) usually does the work.
You rarely need to manage Spark directly. You do need a working model of it, because most performance problems and surprising errors come from how Spark splits and runs work.
The working model
A Spark application has three parts.
- Driver. One process that runs your program, builds a plan, and coordinates the work.
- Executors. Processes on worker machines that run tasks and hold data in memory or on disk.
- Tasks. Small units of work. Each task processes one partition, which is a slice of the data.
On a Databricks cluster, the driver runs on the driver node and executors run on the worker nodes. Both run in the compute plane, inside your cloud account (or in Databricks-managed infrastructure for serverless).
DataFrames and lazy evaluation
A DataFrame is a table-like object with named, typed columns. You describe what you want with DataFrame methods or with SQL. Both go through the same optimizer, so a SQL query and an equivalent DataFrame program usually perform the same.
Spark uses lazy evaluation. Operations fall into two kinds:
- Transformations describe a new DataFrame, such as
select,filter,groupBy, andjoin. They return immediately and do no work. - Actions force execution, such as
count,collect,write, anddisplay.
Spark records the transformations as a plan. When an action runs, the optimizer (called Catalyst) rewrites the plan. It can push filters down to the file scan, skip columns you do not use, and choose a join strategy. Then Spark executes it.
Here is the aggregation from the earlier worked example, with the plan made visible.
from pyspark.sql import functions as F
df = spark.table("main.tutorial.orders")
totals = (
df.filter(F.col("amount") > 20)
.groupBy("customer_id")
.agg(F.sum("amount").alias("total_amount"))
)
# No data has been processed yet. This prints the plan only.
totals.explain()
# This is an action. It runs the job and shows the result.
display(totals)spark is a predefined session in Databricks notebooks, so you do not create it yourself. explain() is a good habit when a query is slow. Look for the filter appearing in the scan node, which means Spark pushed it down to the data read.
Narrow and wide operations
How expensive an operation is depends on whether it needs data from other partitions.
| Kind | Examples | Data movement | Cost |
|---|---|---|---|
| Narrow | `filter`, `select`, `withColumn` | None. Each task works on its own partition. | Low |
| Wide | `groupBy`, `join`, `distinct`, `orderBy` | A **shuffle**: rows are redistributed across the network so related rows land together. | High |
A shuffle writes intermediate data to disk and sends it between executors. Spark splits a job into stages at each shuffle boundary. In the example above, the filter runs in the first stage. The groupBy forces a shuffle, and the final sum runs in a second stage.
When a job is slow, the usual cause is a shuffle that moves too much data, or a few partitions that hold far more rows than the rest.
Where Delta Lake fits
Spark reads and writes Delta tables through the Delta transaction log, which is how the table gets ACID guarantees on plain files. Each write is a job: tasks write new Parquet files, then the driver commits one entry to the log. If a job fails midway, the half-written files are never added to the log, so readers do not see them.
This is also why DESCRIBE HISTORY works. Each commit is a log entry that Spark can read back.
Common errors and gotchas
Collecting too much to the driver
collect() and toPandas() pull every row to the driver node, which is a single machine. On a large table this causes out-of-memory errors. Filter or aggregate first, or use limit().
# Risky on a large table: all rows go to the driver.
rows = spark.table("main.tutorial.orders").collect()
# Safer: bring back only a small, aggregated result.
small = (
spark.table("main.tutorial.orders")
.groupBy("customer_id")
.count()
.limit(100)
.toPandas()
)Running the same plan more than once
Because evaluation is lazy, each action recomputes the whole plan from the source. If you call count() and then display() on an expensive DataFrame, Spark does the work twice. Write the intermediate result to a table, or use cache() when the DataFrame is reused several times and fits in memory. Note that caching is not guaranteed on every compute type, and a table write is the more durable choice.
Too many or too few partitions
Shuffles produce a number of output partitions set by spark.sql.shuffle.partitions. Too many gives many tiny tasks with scheduling overhead. Too few gives large tasks that spill to disk. Recent Databricks runtimes use adaptive query execution, which adjusts this at run time, so change the setting only when you have measured a problem.
Python code that bypasses Spark
Plain Python loops, pandas operations, and Python UDFs (user-defined functions) behave differently from built-in Spark functions. Built-in functions run inside the engine and can be optimized. A Python UDF sends rows out to a Python process and back, which is much slower. Prefer functions from pyspark.sql.functions when one exists.
Data skew
Skew means a few keys hold most of the rows, for example one customer_id with millions of orders. The task that handles that key runs long while others finish. In the Spark UI, you see one task far slower than the rest in a stage. Adaptive query execution can split skewed join partitions, which helps in many cases.
Looking at what Spark did
The Spark UI shows jobs, stages, and tasks for a run. On a cluster, you reach it from the cluster page. In a notebook, you can follow the link under a cell's output. Check three things:
- Which stage took the most time.
- Whether task durations in that stage are even or have a long tail.
- How much data was shuffled or spilled to disk.
Serverless compute and SQL warehouses expose query profiles instead, which show the same operators and timings for each query.
How this connects to compute choices
The cluster you pick sets the executor count and machine size, so it limits how much parallelism Spark has. Autoscaling adds workers when tasks queue up and removes them when idle. More workers help wide, parallel work. They do not help a job that is dominated by one skewed task or by a driver bottleneck such as collect().
Exercise
A notebook cell runs df.filter("amount > 20").groupBy("customer_id").count() and returns instantly with no result shown, and nothing appears in the Spark UI. Then you add .show() and the job runs. Explain what happened, and say how many stages you expect and why.
Show answer
The first version only defined transformations, and Spark evaluates lazily, so it built a plan without reading any data. .show() is an action, which forces Spark to execute the plan. Expect two stages. The filter is a narrow operation and runs in the first stage along with the scan and a partial aggregation. The groupBy needs rows with the same customer_id together, which causes a shuffle, and the final count runs in a second stage after that shuffle.
Exercise
A job joins a large orders table to a customers table and takes two hours. In the Spark UI, 199 of 200 tasks in the join stage finish in under a minute, and one task runs for the remaining time. Name the likely problem, and give two things you could try.
Show answer
This is data skew: one join key holds a very large share of the rows, so one task gets most of the data. You could rely on or enable adaptive query execution skew handling so Spark splits the large partition, or you could filter out or separately handle the hot key (for example, process it in its own query and union the results). Adding more workers would not help, because the work is concentrated in one task.