What you will be able to do
- Explain where a Spark property set on a cluster, in a notebook or on serverless compute takes effect, and why Databricks recommends keeping most defaults
- Size spark.sql.shuffle.partitions for very small and very large data, and tell it apart from default parallelism and input splits
- Describe how adaptive query execution coalesces shuffle partitions and switches join strategies at runtime, and what the auto setting does
- Use spark.sql.autoBroadcastJoinThreshold to control or disable automatic broadcasting
- Choose between more executor memory and more driver memory, and apply either one on Databricks through the node type
- Re-measure the same stage metrics after changing a parameter to confirm the change helped
Key concept
Shuffle partition count — The number of partitions, and so the number of tasks, that Spark creates when it shuffles data for a join or an aggregation. If there are too many for the data, scheduling overhead dominates. If there are too few, each task holds more data than fits in memory and spills to disk. Most Spark tuning comes down to getting this number right, or letting AQE get it right for you.
1.Where Spark tuning parameters are set, and why defaults usually win
A Spark tuning parameter is a configuration property, a Spark conf, that changes how the engine splits, moves and holds data. Four of them come up again and again: spark.sql.shuffle.partitions, default parallelism, executor and driver memory, and spark.sql.autoBroadcastJoinThreshold. Each one can make a slow stage fast. Each one can also make a fast stage slow when it is set by habit instead of from evidence.
Databricks starts from restraint. It generally recommends against configuring most Spark properties, because a legacy setting carried over from open-source Spark or from an older runtime can override newer defaults that already optimize the workload. A cluster config copied from 2019 that pins shuffle partitions to a fixed number is a typical example. It quietly switches off behaviour the current runtime would otherwise give you.
Where you set a property decides how far it reaches. A property in the compute configuration applies to every notebook and job that runs on that compute resource. A property set inside a notebook applies only to that notebook's SparkSession. That makes a notebook the safe place to try a value before you promote it to a cluster that other workloads share. spark.conf.get shows the value currently in effect.
spark.conf.set("spark.sql.ansi.enabled", "true")Serverless compute narrows these choices further. For notebooks and jobs it supports only a short list of properties, and spark.sql.shuffle.partitions is one of them, with a default of auto instead of a fixed number. Lakeflow pipelines can also take Spark properties for the whole pipeline, for a single compute resource, or for an individual flow, materialized view or streaming table.
Checkpoint 1 of 9· Fill the gap
You want to try a Spark property value in your own notebook before promoting it to a cluster other teams share. Which method completes this line so the value takes effect for the current notebook's SparkSession?
spark.conf. ? ("spark.sql.ansi.enabled", "true")spark.conf.set sets a property inside the notebook, so the change reaches only the current notebook's SparkSession. That makes it a safe place to test a value. spark.conf.get only reads the value currently in effect and changes nothing.
Sources1
2.Sizing spark.sql.shuffle.partitions and where parallelism comes from
Every join or aggregation in Spark SQL or the DataFrame API redistributes rows by key in a shuffle. spark.sql.shuffle.partitions sets how many partitions that shuffle produces, and its classic default is 200. Spark runs one task per partition, so this one number decides how many tasks the post-shuffle stage schedules and how much data each task carries. (Serverless shows auto as its default. That setting is covered in the next section.)
Shuffles are not the only source of parallelism. When Spark reads files, the partition count comes from input splits: spark.sql.files.maxPartitionBytes packs at most 128 MB into each read partition, and the suggested minimum number of split partitions falls back to default parallelism. For RDD parallel collections, Spark normally sets the number of partitions automatically based on the cluster, unless you pass a count to parallelize. None of these change how many partitions a SQL or DataFrame join or aggregation produces. That number belongs to spark.sql.shuffle.partitions, and raising spark.default.parallelism leaves it alone.
Too many partitions for small data. At 50,000 rows, 200 partitions means each task gets a few hundred rows. The stage then spends its time starting and scheduling tasks, not processing data, because very small tasks suffer most from scheduling and task setup overhead. The fix is to lower the count toward the cores you actually have. A common guide is two to four partitions per CPU, and AQE's own coalescing floor is two times the number of cluster cores. Giving executors more memory does nothing here. No task is short of memory; each one is simply too small to be worth its overhead.
Too few partitions for large data. Aggregate 2 TB through the same 200 partitions and each task has to process several gigabytes. Shuffles, joins, sorts and aggregations run in execution memory, and when that runs short, Spark writes data to disk. Spill is most common during data shuffling. Raising spark.sql.shuffle.partitions shrinks each task's share, and Databricks lists too few shuffle partitions as a common cause of memory failures. Executors hold this shuffle data, not the driver, so a bigger driver does nothing for a spilling shuffle.
The broadcast threshold is no way around either problem. It sets the maximum size of a table that Spark sends to every worker during a join. It cannot remove the shuffle from an aggregation, and no sensible threshold would broadcast 2 TB.
| Setting | What it sizes | Default |
|---|---|---|
| spark.sql.shuffle.partitions | Partitions produced by shuffles for joins or aggregations | 200 (auto on serverless) |
| spark.sql.files.maxPartitionBytes | Maximum bytes packed into one partition when reading files | 134217728 (128 MB) |
| spark.sql.files.minPartitionNum | Suggested minimum number of split file partitions | Default Parallelism |
Checkpoint 2 of 9· Check yourself
A nightly DataFrame job aggregates about 2 TB by customer key using the default 200 shuffle partitions. The stage page shows heavy spill to disk in the post-shuffle stage. Which setting change targets the cause of the spill?
With 2 TB going through 200 partitions, each task has to hold several gigabytes and runs out of execution memory. spark.sql.shuffle.partitions sets how many partitions a join or aggregation shuffle produces, so raising it shrinks each task's share. spark.default.parallelism does not change that count. Executors hold the shuffle data, not the driver. The broadcast threshold only applies to joins.
“Configures the number of partitions to use when shuffling data for joins or aggregations.”Source: spark.apache.org
Checkpoint 3 of 9· Exam question
A data engineer runs a Spark SQL query that joins and aggregates a dataset of only 50,000 rows. The Spark UI shows the shuffle stage spawns 200 tasks, most finishing in under 100ms with only a handful of rows each, and cluster utilization stays low because scheduling overhead dominates the stage. Which change is most likely to reduce elapsed time for this stage?
Correct answer: B — Lower spark.sql.shuffle.partitions to a value closer to the available core count so each shuffle partition holds a meaningful share of the small dataset.
- A.
spark.default.parallelismsets the partition count for RDD-based operations and operations without an explicit partitioner, not for SQL or DataFrame shuffles. Raising it would not change the 200 shuffle tasks produced by this join and aggregation. - B.
spark.sql.shuffle.partitionsdirectly controls the number of partitions produced by SQL and DataFrame shuffle operations, and it defaults to 200 regardless of input size. Lowering it toward the core count means each partition carries enough rows to justify a task, cutting scheduling overhead. - C. Executor memory headroom is not the bottleneck when tasks already finish in under 100ms with only a few rows each. The problem is too many undersized tasks, not insufficient memory per task.
- D. The broadcast threshold governs how join inputs are distributed at planning time; it has no effect on a standalone aggregation stage's shuffle partition count. Raising it would not reduce the number of tiny tasks in this stage.
Checkpoint 4 of 9· Exam question
A job aggregates a 2 TB dataset while spark.sql.shuffle.partitions is left at its default of 200. The Spark UI shows each shuffle task processing several gigabytes of data, heavy spill to disk, and stage durations far longer than comparable jobs on smaller data. Which change should be applied and re-measured first?
Correct answer: A — Increase spark.sql.shuffle.partitions so each shuffle partition holds a smaller amount of data and disk spill is reduced.
- A. Raising the shuffle partition count spreads a fixed volume of data across more, smaller partitions, so each task handles less data and spills less to local disk. This directly targets the observed multi-gigabyte-per-task spill pattern.
- B. A 2 TB dataset is far larger than any practical broadcast threshold, and forcing a broadcast of that size would exhaust executor memory rather than fix the spill. The broadcast threshold governs join planning, not aggregation shuffle sizing.
- C.
spark.default.parallelismapplies to RDD-based operations and does not override the SQL-specific shuffle partition setting for DataFrame or SQL aggregations. Raising it would not change the aggregation's shuffle partition count. - D. Shuffle spill happens on the executors that hold the shuffle data, not on the driver, so increasing driver memory has no effect on executor-side spill during this aggregation.
3.Adaptive query execution: letting Spark size shuffles at runtime
Before a query runs, the optimizer picks a plan from estimates of the data size. Those estimates go wrong when statistics are missing or stale, when the data is skewed, and in the later steps of a complex query. Adaptive query execution (AQE) re-optimizes the plan while the query runs. At the end of each shuffle or broadcast exchange, Databricks has accurate statistics for the data produced so far, and AQE uses them to make better choices. AQE is enabled by default, and queries benefit from it without any changes.
AQE has four features:
- It changes a sort merge join into a broadcast hash join when the actual data turns out small enough.
- It coalesces small post-shuffle partitions into reasonably sized ones.
- It splits skewed tasks in sort merge and shuffle hash joins into roughly even pieces.
- It detects and propagates empty relations, the parts of a query that return no rows.
Coalescing only merges partitions, so it can only lower the count. Its starting point, the initial number of shuffle partitions, equals spark.sql.shuffle.partitions unless you set it separately. Spark picks the right number at runtime only once that initial number is large enough. A 2 TB job pinned at 200 stays at 200 or below, which is why raising the setting is still the right first move for the spilling aggregation. On the 50,000-row job, by contrast, coalescing works in your favour by merging the tiny partitions.
Databricks removes the guesswork with one value. Setting spark.sql.shuffle.partitions to auto turns on auto-optimized shuffle, which picks the partition count from the query plan and the size of the input data. Databricks gives this as the first remedy for spill, for heavy shuffle I/O and for memory failures caused by too few partitions. It's also why fixed manual partition counts are mostly unnecessary on current runtimes. For Structured Streaming, the value can't change between restarts from the same checkpoint location.
| Property | Default | Effect |
|---|---|---|
| spark.databricks.optimizer.adaptive.enabled | true | Turns AQE on or off |
| spark.sql.adaptive.coalescePartitions.enabled | true | Turns partition coalescing on or off |
| spark.sql.adaptive.advisoryPartitionSizeInBytes | 64MB | Target size after coalescing |
| spark.sql.adaptive.coalescePartitions.minPartitionSize | 1MB | Coalesced partitions are no smaller than this |
| spark.sql.adaptive.coalescePartitions.minPartitionNum | Two times the number of cluster cores | Don't set it: it overrides minPartitionSize |
You can confirm that AQE acted by reading the plan. DataFrame.explain() after execution shows the final plan. SQL EXPLAIN doesn't run the query, so it shows only the initial plan. Coalescing appears as a CustomShuffleReader node with the Coalesced property, and a runtime join switch appears as a different physical join node from the one in the initial plan.
Checkpoint 5 of 9· Check yourself
A team runs several jobs with AQE on. Their data volumes range from a few thousand rows to several terabytes. They want Databricks to size the shuffle partitions for each query, so they no longer have to keep a fixed number per job. What should they configure?
Setting spark.sql.shuffle.partitions to auto turns on auto-optimized shuffle, which picks the count from the query plan and the input data size. Coalescing can only merge partitions, so it cannot raise a count of 200. You shouldn't set minPartitionNum, because it overrides minPartitionSize. The initial partition number comes from spark.sql.shuffle.partitions, not from spark.default.parallelism.
“Set it to auto to enable auto-optimized shuffle, which sets this number based on the query plan and the query input data size.”Source: docs.databricks.com
4.spark.sql.autoBroadcastJoinThreshold: when Spark broadcasts on its own
In a broadcast join, the small side is copied to every worker so the large side never has to shuffle. spark.sql.autoBroadcastJoinThreshold decides when Spark makes that choice by itself. It is the maximum size in bytes of a table that Spark will broadcast, with a default of 10 MB. Tables under the threshold are broadcast without any hint. Setting the value to -1 turns automatic broadcasting off.
The threshold controls only automatic broadcasting. A BROADCAST hint still takes priority even when statistics put the table above the threshold, so -1 doesn't stop hinted broadcasts. Databricks also runs a separate runtime switch: spark.databricks.adaptive.autoBroadcastJoinThreshold, default 30MB, is the size at which AQE turns a sort merge join into a broadcast hash join during execution. A broadcast planned before the query runs usually performs better than one AQE plans at runtime, because AQE may already have shuffled both sides before it learns the real sizes.
Raising the threshold has a cost. Every executor must hold the broadcast table, and Databricks names a large broadcast as a common cause of executor memory failures. Before raising any limit, it advises checking for broadcast hints on large tables and reviewing the runtime broadcast threshold. Raise the threshold only when the plan shows a sort merge join against a table you know is small. Set it to -1 when automatic broadcasts of tables that are too large are causing memory failures.
SELECT /*+ BROADCAST(r) */ * FROM src s JOIN records r ON s.key = r.keyCheckpoint 6 of 9· Fill the gap
spark.sql.autoBroadcastJoinThreshold is set to -1 on this cluster. Even so, an engineer wants Spark to copy the small records table to every worker for this one join. Which hint completes the query and still applies despite the -1 setting?
SELECT /*+ ? (r) */ * FROM src s JOIN records r ON s.key = r.keySetting the threshold to -1 turns off only automatic broadcasting. A BROADCAST hint still takes priority, even when statistics put the table above the threshold. MERGE and SHUFFLE_HASH ask for shuffle-based join strategies. REPARTITION only changes partitioning and does not broadcast the table.
Source: spark.apache.org5.Executor and driver memory: set through the node type
The two memory settings serve different processes. Executors are the processes on worker nodes that run computations and store data, so shuffles, joins, sorts and aggregations draw on executor memory. The driver holds the SparkContext, interprets every command run from a notebook and coordinates the executors. When an action such as collect() brings results back, those rows land in driver memory. Only small amounts of data should be collected this way, or the driver runs out of memory.
On Databricks, both memory settings are changed mainly by choosing hardware. The exam calls them spark.executor.memory and spark.driver.memory. In practice, executor memory follows the worker node type, and driver memory follows the driver node type. The driver node type defaults to the worker type, and you can pick a larger driver type with more memory when you plan to collect() a lot of data. Partition settings won't help a failing collect: the rows all end up in one process however many partitions produced them. The detailed symptoms of each kind of failure are covered in driver vs executor out-of-memory errors.
Executor memory is the lever for spill and lost executors. Total executor memory decides how much data fits in memory before Spark spills to disk, and the fix Databricks gives is to use instances with more memory. Out-of-memory errors are often generic, so test the theory before you pay for it: double the memory per core and see whether the failure goes away. For example, move from a worker with 4 cores and 16 GB to one with 4 cores and 32 GB. The ratio of memory to cores matters, not the total. If the job stops failing, or takes longer to fail, memory was the cause.
Checkpoint 7 of 9· Match them up
For each symptom on a Databricks cluster, pick the change you should make first.
Tap a term, then the definition that fits it.
collect() gathers rows into the driver, so the driver node type is the fix. Spill and lost executors happen in executors, so the worker node type is the lever. Doubling memory per core tests whether memory is really the cause. Tiny tasks come from too many partitions, not from too little memory.
“Total executor memory determines how much data fits in memory before Spark spills it to disk. Use instances with more memory.”Source: docs.databricks.com
6.Re-measuring after every change
A tuning change is a hypothesis until a second run confirms it. The Spark UI shows what the cluster actually did: how long each stage took, how much data moved and where tasks failed. That makes it the before-and-after record for any parameter change. How to read those numbers is covered in reading Spark UI stage metrics. The point here is to read the same numbers twice.
Pick the metric that matches the parameter you changed:
- After changing
spark.sql.shuffle.partitionsor switching it toauto, compare the task count and duration of the post-shuffle stage, plus its Shuffle Read and Shuffle Write. Large values there mean the stage spends its time moving data between executors for joins or aggregations. - After moving to a node type with more memory, compare the stage's spill statistics and Peak Execution Memory. If the stage shows no spill statistics at all, it didn't spill.
- After changing the broadcast threshold, compare the physical join node in the final plan, then the stage duration.
Change one parameter at a time and run the same input on the same compute, so the difference has only one explanation. Keep what the numbers support: if more memory fixes the issue, keep the larger worker type. If it doesn't help, or costs more than it saves, revert it and check the next cause, such as too few shuffle partitions, a large broadcast or skew. Then apply the change at the compute level only once the notebook-level experiment has proved it.
Checkpoint 8 of 9· Match them up
You have made one tuning change and are rerunning the same input on the same compute. Match each change to the evidence you should compare against the earlier run.
Tap a term, then the definition that fits it.
Each metric shows the effect of its own parameter. The partition count changes the number of tasks and the shuffle volume. More executor memory shows up as less or no spill. A threshold change only helps if the final plan uses a different join node, such as a broadcast hash join in place of a sort merge join.
“Join strategy change. The current or final plan has a different physical join node than the initial plan.”Source: docs.databricks.com
Checkpoint 9 of 9· Exam question
A notebook calls .collect() on a DataFrame that returns several million summarized rows to the client, and the job fails with a driver out-of-memory error after all executor stages had already completed successfully. Which tuning parameter should be adjusted first for this job?
Correct answer: C — Increase spark.driver.memory so the driver process has more heap space to hold the rows gathered by the collect operation.
- A. The executor stages already completed successfully, and the failure occurs specifically when results are gathered onto the driver, so extra executor heap space would not prevent this crash.
- B. Shuffle partition count affects how data is partitioned during joins and aggregations on the executors; it has no bearing on how much memory the driver needs to hold rows returned by a collect operation.
- C.
.collect()pulls all result rows into the driver process's heap, so a driver-side out-of-memory error after successful executor stages points directly at insufficient driver memory for holding that result set. - D. The broadcast threshold governs whether a join input is distributed to executors during query planning; it does not apply to a collect operation that pulls results back to the client.
Sources
(11)
Every claim above is drawn from one of these pages, quoted as it was written on the date shown.
- 1.https://docs.databricks.com/aws/en/spark/confOfficial docs
“Databricks generally recommends against configuring most Spark properties.”
↩︎ Where Spark tuning parameters are set, and why defaults usually win“legacy Spark configurations can override new default behaviors that optimize workloads.”
↩︎ Where Spark tuning parameters are set, and why defaults usually win“Serverless compute does not support setting most Spark properties for notebooks or jobs.”
↩︎ Where Spark tuning parameters are set, and why defaults usually win - 2.https://docs.databricks.com/aws/en/optimizations/aqeOfficial docs
“The default number of partitions to use when shuffling data for joins or aggregations.”
↩︎ Sizing spark.sql.shuffle.partitions and where parallelism comes from“Very small tasks have worse I/O throughput and tend to suffer more from scheduling overhead and task setup overhead.”
↩︎ Sizing spark.sql.shuffle.partitions and where parallelism comes from“AQE is enabled by default. You don't need to change your queries to benefit from it.”
↩︎ Adaptive query execution: letting Spark size shuffles at runtime“Set it to auto to enable auto-optimized shuffle, which sets this number based on the query plan and the query input data size.”
↩︎ Adaptive query execution: letting Spark size shuffles at runtime“The plan contains a CustomShuffleReader node with the Coalesced property.”
↩︎ Adaptive query execution: letting Spark size shuffles at runtime“The size threshold for switching a sort merge join to a broadcast hash join at runtime.”
↩︎ spark.sql.autoBroadcastJoinThreshold: when Spark broadcasts on its own“A broadcast join that the optimizer plans before the query runs usually performs better than one that AQE plans at runtime.”
↩︎ spark.sql.autoBroadcastJoinThreshold: when Spark broadcasts on its own“The default number of partitions to use when shuffling data for joins or aggregations.”
↩︎ Key concept“Set it to auto to enable auto-optimized shuffle, which sets this number based on the query plan and the query input data size.”
↩︎ Exam trap 4“Join strategy change. The current or final plan has a different physical join node than the initial plan.”
↩︎ Checkpoint - 3.https://spark.apache.org/docs/latest/rdd-programming-guide.htmlSecondary source
“Typically you want 2-4 partitions for each CPU in your cluster.”
↩︎ Sizing spark.sql.shuffle.partitions and where parallelism comes from“Normally, Spark tries to set the number of partitions automatically based on your cluster.”
↩︎ Sizing spark.sql.shuffle.partitions and where parallelism comes from - 4.
“Spill is most common during data shuffling.”
↩︎ Sizing spark.sql.shuffle.partitions and where parallelism comes from“If no spill statistics appear, the stage has no spill.”
↩︎ Re-measuring after every change“Total executor memory determines how much data fits in memory before Spark spills it to disk.”
↩︎ Exam trap 2“Total executor memory determines how much data fits in memory before Spark spills it to disk. Use instances with more memory.”
↩︎ Checkpoint - 5.
“Too few shuffle partitions.”
↩︎ Sizing spark.sql.shuffle.partitions and where parallelism comes from“A large broadcast. Check for broadcast join hints on large tables, and review the runtime broadcast threshold.”
↩︎ spark.sql.autoBroadcastJoinThreshold: when Spark broadcasts on its own“If you suspect a memory issue, verify it by doubling the memory per core to see whether it resolves the problem.”
↩︎ Executor and driver memory: set through the node type“The ratio of memory to cores matters, not the total memory.”
↩︎ Executor and driver memory: set through the node type“If more memory fixes the issue, keep the larger worker type.”
↩︎ Re-measuring after every change - 6.https://spark.apache.org/docs/latest/sql-performance-tuning.htmlSecondary source
“Spark can pick the proper shuffle partition number at runtime once you set a large enough initial number of shuffle partitions”
↩︎ Adaptive query execution: letting Spark size shuffles at runtime“By setting this value to -1, broadcasting can be disabled.”
↩︎ spark.sql.autoBroadcastJoinThreshold: when Spark broadcasts on its own“Configures the number of partitions to use when shuffling data for joins or aggregations.”
↩︎ Exam trap 1“Configures the maximum size in bytes for a table that will be broadcast to all worker nodes when performing a join.”
↩︎ Exam trap 3“Configures the number of partitions to use when shuffling data for joins or aggregations.”
↩︎ Checkpoint - 7.https://docs.databricks.com/aws/en/compute/configureOfficial docs
“The driver node also maintains the SparkContext, interprets all the commands you run from a notebook or a library on the compute resource”
↩︎ Executor and driver memory: set through the node type“The default value of the driver node type is the same as the worker node type.”
↩︎ Executor and driver memory: set through the node type“You can choose a larger driver node type with more memory if you are planning to collect() a lot of data”
↩︎ Executor and driver memory: set through the node type - 8.
“Only collect small amounts of data back to R data frames, or the Spark driver will run out of memory.”
↩︎ Executor and driver memory: set through the node type - 9.https://spark.apache.org/docs/latest/cluster-overview.htmlSecondary source
“which are processes that run computations and store data for your application”
↩︎ Executor and driver memory: set through the node type - 10.
“how long each stage took, how much data moved, and where tasks failed.”
↩︎ Re-measuring after every change - 11.
“the stage spends a lot of time shuffling data between executors for joins or aggregations.”
↩︎ Re-measuring after every change