Driver, executors and partitions
Part of the free LogicWiz Data Engineering course, Module 12: How Spark runs. The SQL and Python run in the app, on real Postgres and real Python in the browser.
It is 10:20 on Tuesday. Your first job on SwiftKart's new cluster has been running for twenty minutes. The cluster has 4 workers with 8 cores each, 32 cores in all, and the Spark UI says 1 task running. Nora looks at your screen: "Thirty-two cores, one task. Find out who hands out the work, and why it handed out only one piece."
You'll learn to
- Say what the driver, the executors and a partition each do
- Follow one action from your code to tasks on cores
- Work out how many partitions a file read makes
- Tell a sick machine from a slice that is too big
Learn
One boss, many workers
Start with who is in the room. A Spark application is one boss and many workers.
The boss is your own program: the notebook or the script. Spark calls it the driver. It makes the plan, cuts the work into pieces and hands them out. It holds almost no data itself.
The workers are programs on the other machines. Spark calls each one an executor. An executor has a fixed number of cores, and each core does one piece of work at a time. A third program, the cluster manager, only starts the others. It hands out no work.
Think of a restaurant kitchen: one head chef hands out the tickets and the cooks cook. If an executor dies, the driver gives its work to another one. If the driver dies, the application is gone.
Your cluster at 10:20
A driver beside four executors with eight cores each; one core on the first executor runs a task and the other thirty-one are free.
Read it left to right: the driver hands out work and the four executors do it. Right now 1 core of 32 is busy.
A slice of rows, a slice of work
Spark never hands a worker the whole table. It cuts the rows into slices. Each slice is called a partition.
The work a step does on one partition is called a task. The rule that explains your stuck job is short: one task per partition, and one core runs one task at a time.
So a step runs min(partitions, cores) tasks at once. On your 32 cores, 400 partitions keep every core busy. 8 partitions make only 8 tasks, and 24 cores wait.
Real Spark hides its partitions. This module uses minispark, a tiny Spark-like engine in plain Python, so you can look inside them.
Cut a list into partitions
import minispark as ms
orders = [1001, 1002, 1003, 1004, 1005, 1006, 1007, 1008, 1009, 1010]
rdd = ms.parallelize(orders, 3)
print(rdd.getNumPartitions())
print(rdd.glom())
print(rdd.sizes())
parallelize cuts the list into 3 slices that sit next to each other. glom() shows the rows inside each partition and sizes() counts them. minispark speaks the RDD API that DataFrames are built on (open minispark.py and read it). Serverless compute has no RDD API: there you write DataFrames and get the same partitions.
What happens when you press run
You call orders.count(). Three parts of the driver take over, one after the other.
First, the work is cut into rounds. A round is called a stage, and the part that cuts is the DAGScheduler. A new stage starts wherever rows have to move between machines (Lesson 12.3 is about that move).
Second, each stage becomes one task per partition. The TaskScheduler offers those tasks to free cores. If a task fails it tries again, up to 4 attempts.
Third, the scheduler backend sends each task to its executor and collects the status reports.
Step through it for a table that arrives as 96 partitions.
count() on 96 partitions, step by step
A count on a table of 96 partitions: the call reaches the driver, the DAGScheduler cuts two stages, the TaskScheduler runs 96 tasks on 32 cores, then one last task adds the counts and the result returns.
You call count(). Until this line nothing ran. The call reaches the driver as job 0.
The DAGScheduler cuts the job. A count needs two rounds: count each partition, then add the counts. That is two stages: stage 0 with 96 tasks and stage 1 with one.
The TaskScheduler hands out stage 0. 96 partitions make 96 tasks. The 32 cores take the first 32, and each task counts its own partition.
Three waves later, stage 0 is done. 96 / 32 = 3 waves. Every task has written its small count where the next stage can fetch it. Only now may stage 1 start.
Stage 1 adds the counts. One task sums the 96 numbers, and the answer travels back to your code: 412,803,117 orders.
Read each step top to bottom: the driver decides, the executors do. A DataFrame count() is always two stages: a count inside every partition, then one task that adds them up.
Remember: the DAGScheduler cuts a job into stages, the TaskScheduler places one task per partition on free cores, and the executors run them.
The trap: asking the boss to carry the data. That count sent one number back to the driver. collect() and toPandas() send every row. The driver adds up what the tasks send back, checks it against spark.driver.maxResultSize (1 GB by default) and stops the job with "Total size of serialized results of 412 tasks (1024.6 MiB) is bigger than spark.driver.maxResultSize (1024.0 MiB)". Raising the limit only moves the crash to the driver's own memory. Aggregate, limit() or write to storage instead.
Who is who on 4 workers with 8 cores each
| Piece | What it is | On this cluster |
|---|---|---|
| Driver | Your program: plans and hands out work | The driver node runs your notebook |
| Executor | A program on a worker that runs tasks and holds data | One per worker: 4 executors |
| Core | Runs one task at a time | 4 x 8 = 32 tasks at once |
| Partition | A slice of the rows | A year of orders read as 400 partitions |
| Task | One stage's work on one partition | 400 tasks in 13 waves of up to 32 |
Partitions decide how many tasks there are. Cores decide how many run together. 400 / 32 = 12.5, so 13 waves, and the last wave has only 16 tasks while 16 cores wait. With 384 partitions (12 x 32) there are 12 full waves, and each task is about 4% bigger (400 / 384).
Four partitions, four tasks
import minispark as ms
orders = ms.read_csv('data/orders.csv', 4)
print('partitions:', orders.getNumPartitions())
print('rows per partition:', orders.sizes())
delivered = orders.filter(lambda r: r['status'] == 'delivered')
print('after the filter:', delivered.getNumPartitions(), 'partitions')
print('rows per partition:', delivered.sizes())
The 80 orders are read as 4 partitions of 20 rows, so the filter runs as 4 tasks. Each task filtered its own slice: 20 rows became 9, 9, 7 and 4. No row left its partition, so nothing crossed the network (Lesson 12.3 calls such a step narrow). The partitions are now uneven, and every later step inherits that.
Who decided on one partition?
Your job has one task, so its input arrived as one partition. Who decided that? The file reader did, with a small sum.
It wants every core to have something to read, and no slice bigger than 128 MB. So it works out a split size:
- Add up the file sizes, plus 4 MB for every file (the cost of opening it).
- Divide by the number of cores. That is the bytes per core.
- The split size is the bytes per core, but never under 4 MB and never over 128 MB.
Take 2 files of 100 MB on 32 cores:
- 104 + 104 = 208 MB
- 208 / 32 = 6.5 MB per core
- 6.5 sits between 4 and 128, so the split size is 6.5 MB
Spark cuts each file into pieces of that size, then packs the pieces into partitions.
Four reads on 32 cores
| Input | Bytes per core | Split size | Partitions |
|---|---|---|---|
| 96 files of 128 MB (12 GB) | 96 x 132 / 32 = 396 MB | 128 MB | 96: 128 + 4 leaves no room for a second file |
| 2 files of 100 MB | 208 / 32 = 6.5 MB | 6.5 MB | 32: a small input is cut finer to fill every core |
| 1,000 files of 1 MB | 5,000 / 32 = 156 MB | 128 MB | 39: each file counts 5 MB, so 26 share a partition |
| 1 gzip CSV of 6 GB | 6,148 / 32 = 192 MB | 128 MB | 1: gzip cannot be split |
The packing rule: pieces go in largest first, a piece starts a new partition when it would push the current one past the split size, and every piece also counts its 4 MB opening cost. One more detail for Parquet: a split is a range of bytes, and a row group is read by the task whose range holds the row group's middle. So if each 100 MB file is one row group, the 32 partitions give 2 busy tasks and 30 that read nothing.
Check the table with minicatalyst
import minicatalyst as mc
MB = mc.MB
reads = {
'96 files x 128 MB': [128 * MB] * 96,
'2 files x 100 MB': [100 * MB] * 2,
'1,000 files x 1 MB': [1 * MB] * 1000,
}
for name, files in reads.items():
split = mc.max_split_bytes(files, cores=32)
parts = mc.file_partitions(files, cores=32)
print(f'{name}: split {split / MB:.1f} MB, {len(parts)} partitions')
gz = mc.file_partitions([6 * 1024 * MB], cores=32, splittable=False)
print('one 6 GB gzip file:', len(gz), 'partition')
minicatalyst is this module's model of Spark's planner. Its file_partitions is twenty lines that follow Spark's own FilePartition code step by step. Open it, then change cores and watch the two-file read follow the core count. Look at the last line of the output: that one is your job.
The culprit: a file that cannot be cut
Now look at your job's input. It is the nightly export, one file: orders.csv.gz, 6 GB.
A gzip file cannot be read from the middle. A reader has to start at the first byte. Spark says such a file is not splittable, so the split sum never applies. The whole 6 GB becomes one partition. One partition means one task, and one task means one core. The other 31 wait.
Calling repartition after the read spreads the later steps over the cluster, but the read itself is still one task. The real fix is at the source: ask for Parquet, an uncompressed CSV, or many smaller files.
How many tasks can read at once
Bars compare the partitions made by four reads on 32 cores: 96, 32 and 39 for the splittable inputs, and 1 for the gzip file.
One bar per read: the longer the bar, the more tasks the read step can run. The red bar is the job from 10:20.
A sick machine gets a second copy
Sometimes one task is slow for a different reason: its machine is sick. A failing disk, a noisy neighbour.
Spark can start a second copy of a slow task on another executor. The first copy to finish wins and the other is killed. This is called speculation, and it is off by default (spark.speculation).
With it on, the driver waits until most tasks of a stage have finished. Then any task that has run much longer than the typical finished one gets a copy. In Spark 3.x "most" is 75% and "much longer" is 1.5 times the median. Spark 4.0 is less eager: 90% and 3 times.
Speculation would not have saved your job. A copy of your task reads the same 6 GB file.
Speculation on a sick executor (Spark 3.x defaults)
Five tasks on four cores; three finish around 21 seconds, the slow task T2 gets a copy at 32 seconds on a free core, and the copy finishes at 46 seconds, ending the stage.
Each row is one core and time runs left to right. floor(0.75 x 5) = 3 tasks must finish first. Their median is 21 s, so at 31.5 s T2 gets a copy. Alone, T2 would run to about 75 s. Spark 4.0's defaults wait for 4 tasks and for 3 x 20.5 s, too late to help here.
Remember: speculation rescues a task on a sick machine. It never rescues a task whose slice is too big, because the copy reads the same slice.
Run the task next to its data
When the TaskScheduler places a task, it prefers an executor that already holds the task's input. This preference is called locality. The best case is data cached inside that executor (PROCESS_LOCAL). Next best is data on the same machine (NODE_LOCAL). After that, anywhere.
If the preferred executor is busy, the scheduler waits 3 seconds (spark.locality.wait) before it settles for the next level. With cached data, that wait shows up in the Spark UI as scheduler delay.
Your files are different. Files in object storage (S3, ADLS, GCS) live on no worker at all, so there is nothing to prefer and the task starts at once. Guess what the UI writes in the Locality Level column for such a task.
Workers that come and go
A cluster does not have to stay one size. With dynamic allocation on (spark.dynamicAllocation.enabled, off by default), the driver asks for more executors when tasks have queued for 1 second: 1 more, then 2, 4, 8 while the queue lasts. It gives back an executor that has been idle for 60 seconds.
The catch is the files one stage leaves behind for the next, called shuffle files. They sit on the disk of the executor that wrote them. Remove that executor and the next stage cannot fetch them, so the lost tasks have to run again.
So Spark either keeps such an executor alive while its files are still needed (shuffle tracking), or lets a separate external shuffle service serve the files. On classic clusters, Databricks autoscaling does this job.
A healthy read, on real Spark
Runs on Databricks:
orders = spark.read.parquet("/Volumes/swiftkart/raw/orders_2024")
print(orders.rdd.getNumPartitions())
print(spark.sparkContext.defaultParallelism)
print(spark.conf.get("spark.sql.files.maxPartitionBytes"))
print(spark.conf.get("spark.sql.files.openCostInBytes"))
96
32
134217728b
4194304b
Back to partitions, this time on real Spark. A year of orders as 96 Parquet files of 128 MB, on a classic cluster of 4 workers x 8 cores: 96 partitions, three waves, every core busy. On Databricks classic compute each worker runs one executor that uses all its cores, so the default parallelism is the total of the worker cores. These calls need a real cluster. Serverless compute has no orders.rdd or spark.sparkContext, sizes the machines itself and shows a query profile instead of the Spark UI.
Numbers to remember
| Setting | Default | What it is |
|---|---|---|
| spark.sql.files.maxPartitionBytes | 128 MB | The most one partition of a file read may hold |
| spark.sql.files.openCostInBytes | 4 MB | The cost of opening a file, counted as extra bytes |
| spark.sql.files.minPartitionNum | the default parallelism (total cores) | The core count the split sum divides by. In full: maxSplitBytes = min(maxPartitionBytes, max(openCostInBytes, bytesPerCore)) |
| spark.sql.shuffle.partitions | 200 | The partition count after a shuffle (Lesson 12.3) |
| spark.task.cpus | 1 | Cores one task takes |
| spark.task.maxFailures | 4 | Attempts a task gets before the job fails |
| Task size warning | 1,000 KiB | "Stage 3 contains a task of very large size": usually a big object captured in a function. A stage's code travels to each executor once, as a broadcast, and each task message carries its partition and a reference to that code |
| spark.locality.wait | 3 s | Wait before relaxing a level: PROCESSLOCAL, NODELOCAL, NOPREF, RACKLOCAL, ANY. Per level: .process, .node, .rack |
| spark.speculation | false | Checked every 100 ms. quantile 0.75 and multiplier 1.5 in Spark 3.x; 0.9 and 3 in Spark 4.0 |
| spark.dynamicAllocation.enabled | false | schedulerBacklogTimeout 1 s, executorIdleTimeout 60 s. cachedExecutorIdleTimeout is infinite: an executor holding cached data is never given back |
| spark.dynamicAllocation.shuffleTracking.enabled | used by default since Spark 3.4 | Keeps an executor alive while its shuffle files are needed |
| spark.driver.maxResultSize | 1 GB | The most all tasks together may send back to the driver |
| Cluster managers | standalone, YARN, Kubernetes | Mesos was deprecated in Spark 3.2 and removed in 4.0. Databricks runs its own |
What changed at SwiftKart
You show Dana the red bar. She changes the nightly export from one gzip file to Parquet files of about 128 MB. The next run reads one partition per file, every core has a task, and the Spark UI shows 32 running instead of 1.
Nora writes the rule of thumb on the team page: aim for partitions of 100 to 200 MB, and a few times more partitions than cores. Too few, and cores idle or a task runs out of memory. Too many, and the fixed cost of every task (placing it, starting it, one file per task on a write) takes over.
One thing still puzzles you. The cell that built this whole job finished in 0.3 seconds. Only the count() took time. Lesson 12.2 explains why.
In one line
The driver hands out one task per partition and each core runs one task at a time, so how the input is cut into partitions decides how much of the cluster works.
Interview corner
What happens, step by step, when you call an action?
The DAGScheduler walks the lineage back from the action, cuts it into stages at each shuffle and submits the stages whose parents are done as TaskSets, one task per partition. The TaskScheduler offers those tasks to free cores, preferring executors that hold the data and relaxing locality after spark.locality.wait (3 s), and retries a failing task up to 4 times. The scheduler backend ships each task; the stage's code travels once as a broadcast. Executors run one task per core, and when the final stage finishes the result returns to the driver.
How many partitions does Spark make when it reads a folder of Parquet files?
It computes maxSplitBytes = min(maxPartitionBytes, max(openCostInBytes, bytesPerCore)), with 128 MB, 4 MB and bytesPerCore = total bytes plus 4 MB per file, divided by the default parallelism. Files are cut into pieces of that size and packed largest first, each piece also counting 4 MB. So 12 GB in 128 MB files gives 96 partitions, 200 MB on 32 cores gives 32, and 1,000 files of 1 MB give 39; a gzip file stays one partition. A Parquet row group goes to the task whose range holds its middle, so tiny splits of big row groups leave tasks empty.
When does speculation help, and when does it not?
It helps when one machine is slow, a bad disk or a noisy neighbour: a copy of the task on a healthy executor finishes first. It needs a share of tasks finished (quantile 0.75 in Spark 3.x, 0.9 in 4.0) and fires for tasks slower than 1.5 x (3 x in 4.0) the median. It does not help skew, because the copy processes the same oversized partition, and it costs a second run of the work.
Why can removing an idle executor break a job, and how does dynamic allocation avoid it?
Shuffle files are written to the local disks of the executor that ran the map task. If that executor is removed, the next stage cannot fetch them and Spark reruns the lost map tasks. Dynamic allocation therefore needs an external shuffle service that serves the files after the executor is gone, or shuffle tracking, which keeps executors alive while their shuffle output is still needed. Executors holding cached blocks are kept by default too.