Sub topic 4
Cores, Memory, and Partitions
This chapter assumes you know the basic Spark vocabulary: jobs, stages, tasks, partitions, and shuffles. It also assumes you can run a notebook on a Databricks cluster. The goal is to connect the cluster's cores and memory to the number of partitions Spark processes at once, because that link decides whether a cluster is the right size for a job.
From cores to task slots
Each worker node runs one Spark executor on Databricks. An executor has a number of CPU cores, and each core can run one task at a time. A core is therefore a task slot.
The total number of task slots is the sum of cores across all workers. The driver does not run tasks for normal Spark jobs, so its cores do not count.
A stage splits its work into tasks, and each task processes one partition. If a stage has 400 partitions and the cluster has 100 slots, Spark runs the tasks in 4 waves. Each wave fills every slot, and the next wave starts as slots free up.
This gives a rule of thumb for judging parallelism:
- Fewer partitions than slots leaves cores idle. You paid for capacity that the stage cannot use.
- Partitions in a small multiple of the slot count (about 2 to 4 times) keep every core busy and smooth out uneven task durations.
- Far more partitions than slots means many tiny tasks. Scheduling overhead then grows relative to the useful work.
Memory per task
Executor memory is shared by all tasks running at the same time. A worker with 32 GB of memory and 8 cores gives each running task roughly 4 GB of working room, before Spark's own overhead is subtracted.
Spark divides the executor heap into regions. Execution memory holds shuffle buffers, sort buffers, and hash tables. Storage memory holds cached data. The two regions share space and can borrow from each other, but cached data can be evicted while execution data cannot.
The size of a partition matters as much as the count. A partition that is too large for its share of memory causes spills, where Spark writes intermediate data to local disk. In the worst case it causes an out-of-memory error. A common target is partitions of roughly 100 to 200 MB of in-memory data.
This leads to two ways to fix a memory problem:
- Make partitions smaller, which means more partitions.
- Give each task more memory, which means choosing a node type with a higher memory-to-core ratio.
Adding more workers of the same type does not help a task that is too big for its own slot. It only adds more slots with the same limit.
Shuffle partitions
Narrow operations such as filters and maps keep the partition count of their input. When the input is read from files, the count depends on file sizes and the setting spark.sql.files.maxPartitionBytes, which defaults to 128 MB.
Wide operations such as joins and aggregations trigger a shuffle. After a shuffle the partition count comes from spark.sql.shuffle.partitions, which defaults to 200. That default is unrelated to your cluster size, so it is often wrong:
- On a large cluster with 2,000 slots, 200 shuffle partitions use only a tenth of the cores.
- On a small job with a few megabytes of data, 200 partitions produce 200 tiny tasks.
Adaptive query execution (AQE) reduces this problem. When it is enabled, Spark can coalesce small shuffle partitions after a shuffle and can split skewed partitions in joins. AQE is on by default in current Databricks runtimes, but it adjusts partitions at run time and does not change the cluster size. A cluster that is too small stays too small.
Checking your cluster
This notebook cell reports the values you need to compare slots against partitions.
total_cores = spark.sparkContext.defaultParallelism
shuffle_partitions = spark.conf.get("spark.sql.shuffle.partitions")
aqe_enabled = spark.conf.get("spark.sql.adaptive.enabled")
print(f"Default parallelism (approx. total cores): {total_cores}")
print(f"Shuffle partitions: {shuffle_partitions}")
print(f"Adaptive query execution enabled: {aqe_enabled}")defaultParallelism is an approximation of the total core count. On Databricks it usually equals the sum of worker cores, but check the cluster's Metrics tab if the number matters.
Compare the numbers like this:
| Observation | Likely meaning | Typical response |
|---|---|---|
| Shuffle partitions far below total cores | Cores sit idle during shuffle stages | Raise `spark.sql.shuffle.partitions` or rely on AQE |
| Shuffle partitions far above total cores and data is small | Many tiny tasks | Lower the setting, or let AQE coalesce |
| Tasks spill to disk or fail with out-of-memory errors | Partitions too big for per-task memory | Increase partitions, or use a memory-optimized node type |
| Few tasks run much longer than the rest | Data skew | Enable AQE skew handling, or salt the join key |
Adjusting partitions in code
You can set the shuffle partition count for a session, or repartition a DataFrame explicitly.
# Match shuffle parallelism to roughly 2-3 waves of the cluster's slots.
slots = spark.sparkContext.defaultParallelism
spark.conf.set("spark.sql.shuffle.partitions", str(slots * 2))
df = spark.range(0, 50_000_000)
# Repartition before a wide operation to spread the work evenly.
balanced = df.repartition(slots * 2)
print(balanced.rdd.getNumPartitions())repartition itself triggers a full shuffle, so use it only when the input has too few or badly skewed partitions. To reduce the partition count without a full shuffle, use coalesce.
Putting it together
The relationship runs in both directions. Cluster size sets the number of slots and the memory per slot. Data volume and partition settings set the number and size of tasks. A well-sized cluster is one where the two match: every slot has work, and every task fits in its memory share.
When you later choose autoscaling bounds, the same logic applies. Extra workers only help a stage that has enough partitions to use them. A stage with 16 partitions gains nothing from a cluster with 200 slots.
Exercise
A cluster has 10 workers with 8 cores each. A shuffle stage uses the default 200 partitions, and each task spills to disk because partitions average 1.5 GB. Would adding 10 more workers of the same type fix the spills? What would you change instead?
Show answer
No. The cluster has 80 slots, so the 200 tasks already run in about 2.5 waves, and each task still gets the same memory share on the new nodes. The spill comes from partitions that are too large for the per-task memory. Raise the shuffle partition count (for example to 1,000 or more so partitions fall near 100 to 200 MB), or choose a memory-optimized node type that gives each core more memory. Adding workers would only shorten the job if the task size were already acceptable.
Exercise
A job runs on a cluster with 160 total cores, and spark.sql.shuffle.partitions is 200 with AQE disabled. The final aggregation stage processes only 40 MB of data. Name one problem this configuration causes and one way to fix it.
Show answer
The stage creates 200 tiny tasks of about 0.2 MB each, so scheduling overhead dominates the useful work. Fixes include lowering spark.sql.shuffle.partitions for this job (for example to 8 or 16) or enabling AQE so Spark coalesces the small shuffle partitions automatically.