Cluster Sizing: Beginner
| Knob | What it sets | What it limits |
|---|---|---|
| `spark.executor.instances` | How many executor processes start | The job's totals, by multiplying the other 2 knobs |
| `spark.executor.cores` | CPU cores in each executor | How many tasks 1 executor runs at the same moment |
| `spark.executor.memory` | Heap size of each executor's JVM | How much data the tasks on that executor hold at once |
Cores turn into slots
Memory belongs to the executor
spark.executor.memory sets the heap of 1 executor JVM. Every task running on that executor draws from it, and so does any data you cached there. Tasks on different executors share nothing: a task on executor 3 cannot borrow free memory from executor 7. Spark reads the value as a size string such as 16g or 512m; write the unit every time, so the next reader doesn't have to guess it.
A configured session
This is the session for the nightly rollup from the intro. The knobs go on the builder, before getOrCreate() starts the application, and each value is passed as a string.
The driver hands tasks to 25 executors, and each runs 4 of them at a time on its own 16g heap. Executors 3 to 24 are left out of the drawing.
Reading a config at a glance
| Instances | Cores | Memory | Slots | Total heap |
|---|---|---|---|---|
| 4 | 8 | 32g | 32 | 128GB |
| 50 | 2 | 8g | 100 | 400GB |
| 10 | 16 | 16g | 160 | 160GB |
spark.executor.cores while memory stays put loads more tasks onto the same heap, and the Memory per Core section shows how that turns a passing job into a failing one.A job runs on 10 executors, each with 2 cores and 8g of memory. You change only spark.executor.cores to 4 and restart. What does the job get now?
| Setting | Default | What the job gets |
|---|---|---|
| `spark.executor.instances` | 2 | 2 executors |
| `spark.executor.cores` | 1 | 1 slot in each executor, 2 in the job |
| `spark.executor.memory` | 1g | 1GB of heap per executor |
| `spark.driver.memory` | 1g | 1GB of heap for the driver |
These defaults apply when executors are requested at a fixed count. In standalone mode an executor takes every free core on its worker unless spark.executor.cores is set, and local[*] on a laptop runs 1 process with a slot per CPU core.
2 slots against 1,600 tasks
| Resource | Value |
|---|---|
| Executors | 2 |
| Cores each | 1 |
| Slots | 2 |
| Heap each | 1GB |
| Turns for 1,600 tasks | 800 |
| Resource | Value |
|---|---|
| Executors | 25 |
| Cores each | 4 |
| Slots | 100 |
| Heap each | 16GB |
| Turns for 1,600 tasks | 16 |
The cluster sits idle
Memory runs short too
Spotting the defaults
- ▸The Executors tab lists 2 executors, each showing 1 core.
- ▸A stage's progress bar never shows more than 2 tasks running.
- ▸The session code and the launch command contain no
spark.executor.*setting. - ▸Each task's duration looks normal while the stage as a whole takes hours.
A job reads 40GB in 128MB partitions, each task takes 30 seconds, and the session sets no resource knobs. Roughly how long does the first stage take?
How Spark splits the heap between tasks
| Executor memory | Cores | Tasks at once | Heap per task, at most |
|---|---|---|---|
| 1g (the default) | 1 | 1 | 1GB |
| 16g | 2 | 2 | 8GB |
| 16g | 4 | 4 | 4GB |
| 16g | 8 | 8 | 2GB |
| 32g | 8 | 8 | 4GB |
An executor has spark.executor.memory at 24g and spark.executor.cores at 6. One task needs about 5GB of working memory for its partition. What happens while all 6 cores are busy?
More cores, less memory each
Say the nightly rollup runs well on 16g executors with 4 cores. Someone raises the cores to 8 to finish sooner and leaves the memory alone. Slots double, and every task's ceiling drops from 4GB to 2GB. Tasks that read and filter keep working. Tasks on the reduce side of the shuffle that used up to 4GB now spill: when a task reaches its ceiling, Spark writes part of its working data to local disk and reads it back later. The job still finishes, but the stage slows down and can give back the time the extra slots were meant to save. Data a task cannot write out in pieces, such as a very large row, can make it fail with an out-of-memory error instead, and a task that fails the same way on every retry takes the job down with it.
| Running task | Ceiling |
|---|---|
| task 1 | 4GB |
| task 2 | 4GB |
| task 3 | 4GB |
| task 4 | 4GB |
| Running task | Ceiling |
|---|---|
| task 1 | 2GB |
| task 2 | 2GB |
| task 3 | 2GB |
| task 4 | 2GB |
| task 5 | 2GB |
| task 6 | 2GB |
| task 7 | 2GB |
| task 8 | 2GB |
The change that keeps the extra slots is to raise memory along with the cores: 32g with 8 cores puts every ceiling back at 4GB. Memory per core is the ratio to hold steady whenever an executor's shape changes.
Which tasks need the room
Giving each task more memory
Raise spark.executor.memory, or run fewer tasks at once on the same heap. Fewer tasks comes from lowering spark.executor.cores, or from raising spark.task.cpus, which sets how many cores each task claims and defaults to 1. An executor with 8 cores and spark.task.cpus at 2 runs 4 tasks at a time, each with up to a quarter of the pool.
Executors run with 16g and 8 cores, and grouping tasks are running out of memory. Which single change raises the memory ceiling of each running task?
Data that travels back to the driver
| What the job does | What lands on the driver |
|---|---|
| `collect()` or `toPandas()` | Every row of the result |
| `take(10)` or `first()` | The rows asked for, and no more |
| `count()` | One number from each task, added up |
| A broadcast join | The whole small side, gathered before it goes out to the executors |
| Every finished task | A status report with the task's metrics |
Watching the result shrink
from pyspark.sql import functions as Fper_title = views.groupBy("title").agg(F.sum("minutes").alias("total_minutes"))per_title.collect()
Every reduction placed before collect() runs on the executors and shrinks what crosses to the driver. Put the same collect() ahead of the groupBy and all 12 rows arrive; at production scale that is the gap between a few kilobytes and many gigabytes.
Run the cell to compare the 2 results you could collect from order_items. The first column counts the rows a raw collect() would bring back; the second counts the rows the driver receives after a groupBy on product_id.
from pyspark.sql import functions as F
items = spark.table("order_items")
items.agg(
F.count("*").alias("rows_if_collected_raw"),
F.countDistinct("product_id").alias("rows_if_collected_per_product"),
).show()Those 2 counts are the 2 sizes a collect() could bring back from the same table. Which one the driver gets depends on where the action sits in the chain: items.collect() sends every line item, while items.groupBy("product_id").agg(F.sum("quantity")).collect() runs the grouping on the executors first and sends 1 row per product. Everything chained before the action runs on the executors, and only the action's result crosses to the driver.
Driver limits that both start at 1GB
spark.driver.memory sets the driver's heap and defaults to 1g. spark.driver.maxResultSize caps the total serialized size of the results 1 action pulls from all partitions, and it also defaults to 1g. When a collect() goes over the cap, Spark aborts the job with an error that names the setting and the size reached, before the driver's heap overflows. Setting the cap to 0 removes it, which trades that clear error for a driver that can run out of memory.
Estimating the result before you collect
| What you collect | Rows | Serialized size | Within the 1g defaults? |
|---|---|---|---|
| Raw views, 3 columns | 1,000,000,000 | 60GB | No: far over `maxResultSize` |
| Minutes per title per hour | 480,000 | 28.8MB | Yes |
| Minutes per title | 20,000 | 1.2MB | Yes |
The serialized size is what maxResultSize measures. Once the rows land, the driver turns them into objects that take several times that space, and a Python program then copies them into Python rows in its own process. Leave room for both when you size the driver, set maxResultSize a little above the largest result you mean to collect, and keep both at 1g when the largest thing coming back is a summary.
spark.driver.cores defaults to 1. The driver schedules tasks and runs your own code between actions, so extra driver cores pay off only when that code does heavy work on collected data. A job that writes its output from the executors rarely needs more than 1 or 2.
- Aggregate or filter on the executors before any collect()
- Write large results to storage from the executors with df.write
- Raise driver memory and maxResultSize together, sized from the result
- Use take(n) to inspect a few rows instead of collecting the whole result
- Set maxResultSize to 0 to make the error go away
- Give the driver 64g so that a billion-row collect() survives
- Size the driver from the input; the output is what reaches it
- Broadcast a table of several GB, which the driver gathers first
A notebook calls toPandas() on a 2.5GB result and fails with an error naming spark.driver.maxResultSize. Which plan fixes it?
When getOrCreate() starts a session, Spark asks the cluster for executors of the shape you configured, and the cluster launches each as a JVM whose heap size and core count are fixed on the command line that starts it. A running JVM cannot raise its maximum heap, and the cluster has reserved those exact cores and that memory on particular machines. So Spark reads the executor knobs once, at launch, and the executors keep them until the session stops.
SQL settings live somewhere else. Catalyst reads settings such as spark.sql.shuffle.partitions each time it plans a query, and a query is planned when an action runs, so a value changed between 2 actions shapes the second one.
| Setting | Read when | Changed on a running session |
|---|---|---|
| `spark.executor.instances` | The session starts | Refused with an error |
| `spark.executor.cores` | Executors launch | Refused with an error |
| `spark.executor.memory` | Executors launch | Refused with an error |
| `spark.driver.memory` | The driver process starts | Refused with an error |
| `spark.sql.shuffle.partitions` | Each query is planned | Applies from the next action |
| `spark.sql.autoBroadcastJoinThreshold` | Each query is planned | Applies from the next action |
| `spark.sql.adaptive.enabled` | Each query is planned | Applies from the next action |
Trying to change them in place
The first line takes effect at the next action, whose groupBy plans 400 shuffle partitions instead of 200. The second raises an AnalysisException saying it cannot modify the value of a Spark config, spark.executor.memory, and the executors keep their 16g.
A second attempt fails quietly. Calling the builder again with a new spark.executor.memory and then getOrCreate() hands back the session that already exists. Spark applies the runtime SQL settings from the builder, logs a warning about the rest, and the executors keep running at their old size. In a notebook the cell looks like it succeeded.
Changing executor resources for real
spark.stop() releases every executor, and everything they held goes with them, cached DataFrames included. The new session waits for the cluster to launch fresh executors, then recomputes any cache the first time it is used. Driver memory is fixed even earlier: the driver is already running when this code runs, so spark.driver.memory belongs in the launch command or the cluster's configuration, where it is read before the driver starts.
- spark.executor.instances, spark.executor.cores, spark.executor.memory
- spark.driver.memory and spark.driver.cores
- Changed only by stopping the session and starting a new one
- A restart drops the executors and their cached data
- spark.sql.shuffle.partitions
- spark.sql.autoBroadcastJoinThreshold
- spark.sql.adaptive.enabled
- Changed with spark.conf.set, in effect from the next action
A few spark.sql.* settings are static as well. spark.sql.warehouse.dir is read once when the session starts, and setting it later raises an error saying it can't modify a static config.
spark.conf.set, without a restart that throws away the cache.A notebook session started with 16g executors and spark.sql.shuffle.partitions at 200. A teammate runs this cell, then reruns a slow groupBy. What does the groupBy run with?
> A food-delivery company's pricing team runs a daily job that reads 300GB of order events, joins them to a 5MB table of delivery zones, groups by zone and hour, and pulls the result into a notebook to chart surge pricing. The first run came from a notebook with no resource settings and was still going hours later.
16g do shrink is every task's ceiling, 2GB against 4GB at 4 cores.maxResultSize.spark.sql.shuffle.partitions between runs works in the live notebook, while moving to 32g executors means spark.stop() and a new session.spark.executor.instances, spark.executor.cores and spark.executor.memory set how many executors start, how many tasks each runs at once, and the heap those tasks share.spark.sql.* settings are read at every query and can change between actions.How many executors, how many cores, how much memory: the 3 choices that decide how fast a Spark job can go.
- Category
- Spark
- Difficulty
- beginner
- Duration
- 12 minutes
- Challenges
- 11 hands-on challenges
Topics covered: Executors, Cores, and Memory, The Default Resources, Memory per Core, Sizing the Driver, Knobs Fixed at Startup
Lesson Sections
- Executors, Cores, and Memory (concepts: Configuration Tuning)
An executor is a JVM process that the cluster starts for your application and keeps running until the application ends. Each executor owns some CPU cores and a fixed block of memory, and the driver sends it work as tasks, 1 task per partition. Spark lets you choose how many executors start, how many cores each one gets, and how much memory each one gets, through 3 settings. This lesson calls them the 3 knobs, because together they decide how much of the cluster your job can use. Cores turn into
- The Default Resources
Leave every resource setting out of the builder and Spark still starts, using values from its documentation. Those values are small, so an application that asks for nothing can start on almost any cluster, including a busy shared one. The same small request is also what your production job receives when nobody overrides it. These defaults apply when executors are requested at a fixed count. In standalone mode an executor takes every free core on its worker unless spark.executor.cores is set, and
- Memory per Core (concepts: Memory Management)
Every task an executor is running draws from that executor's 1 heap. Put 4 cores in an executor and 4 tasks share its memory; put 8 cores in it and 8 tasks share the same amount. The number that decides whether a task has room is the executor's memory divided by the tasks running on it, which, with the default of 1 core per task, is memory divided by cores. How Spark splits the heap between tasks Spark gives memory to running tasks from a pool it sets aside inside the heap. It caps each task at
- Sizing the Driver
The driver runs your Python program, plans each query, and schedules every task, while the executors do the reading and the computing. Planning and scheduling take little memory. What fills a driver's heap is data the job sends back to it, so you size a driver from the output of a job, and the size of its input barely enters into it. Data that travels back to the driver A broadcast join collects the whole small table on the driver before sending a copy to every executor, so broadcasting a 2GB ta
- Knobs Fixed at Startup (concepts: Configuration Tuning)
Trying to change them in place Changing executor resources for real Stop the session and start a new one with the new values: A few spark.sql.* settings are static as well. spark.sql.warehouse.dir is read once when the session starts, and setting it later raises an error saying it can't modify a static config.