Driver, executors and the cluster manager
Every Spark program, on a laptop or on a thousand machines, runs as one driver and many executors. Knowing which does what explains most errors and most performance problems. This lesson shows the roles, what happens when you run a job, and where your Python code actually runs.
Step 2 · Spark internals · Bronze · Your first Spark session, lesson 2 of 2
On this page
In plain words first
Think of a restaurant kitchen during service.
The driver: the head chef
The executors: the cooks
The cluster manager: the restaurant owner
Three roles
Driver
collect().Executors
Cluster manager
What happens when you run a job
- 1You start an application. The driver process starts and creates a SparkSession.
- 2The driver asks the cluster manager for executors, for example 10 executors with 4 cores and 16 GB each.
- 3Your code builds DataFrames. Nothing runs yet: the driver only records a plan.
- 4An action such as
writeorcounttriggers a job. The driver optimises the plan, cuts it into stages and creates one task per partitionpartition: A chunk of a DataFrame's rows. Spark processes each partition as one task, so partitions decide how much work runs in parallel. Learn more →. - 5Tasks are scheduled onto free executor cores. 10 executors with 4 cores run 40 tasks at a time.
- 6Executors read data, run the tasks and write shuffle files or output. The driver tracks progress and retries failed tasks.
Where does my code run?
This is the question behind many confusing errors.
| Code | Runs on |
|---|---|
df = spark.read.parquet(...), df.filter(...) | Driver: builds the plan only |
The filter condition, F.upper(...), joins, aggregations | Executors, compiled to JVM code |
| A Python UDFUDF: User-defined function: your own Python function applied to each row. Flexible but much slower than built-in functions. Learn more → body | Executors, in Python worker processes next to each executor |
df.collect(), toPandas() | Executors compute; all rows are sent to the driver |
| A plain Python loop over a list | Driver |
collect() on a large DataFrame pulls every row into the driver's memory and is the classic way to crash a driver. Write results to storage, or limit before collecting. spark.driver.maxResultSize (1 GB by default) is the safety net.Client vs cluster mode
Client mode
Cluster mode
Sizing an application
| Setting | Meaning |
|---|---|
spark.executor.instances | Number of executors (when dynamic allocationdynamic allocation: Adding and removing executors while an application runs, to match the amount of work. Learn more → is off) |
spark.executor.cores | Concurrent tasks per executor |
spark.executor.memory | JVM heap per executor |
spark.executor.memoryOverhead | Off-heap memory per executor (default: the larger of 384 MB and 10% of executor memory) |
spark.driver.memory | Driver heap |
spark.dynamicAllocation.enabled | Let Spark add and remove executors with the workload |
# spark-submit --master yarn --deploy-mode cluster \ # --num-executors 10 --executor-cores 4 --executor-memory 16g app.py spark = (SparkSession.builder .config("spark.executor.cores", "4") .config("spark.executor.memory", "16g") .getOrCreate())
A common rule of thumb is 4 to 5 cores per executor: fewer wastes memory on per-JVM overhead, more causes contention and long garbage-collection pauses. Total parallelism is executors × cores; aim for a few tasks per core per stage so that slow tasks do not leave cores idle.
Try it yourself
Each example says what it shows, then the output from a real run and what to notice in it, so you can follow without running anything. To try one yourself, paste it into a local Spark session, with spark already created: each builds its own data.
Goal: See the shape of a real Spark job: settings when the session starts, the work done by executors, and the result written to storage.
from pyspark.sql import SparkSession, functions as F def build_session(): # On a cluster, resources usually come from spark-submit; settings can also go here. return (SparkSession.builder .appName("daily-revenue") .config("spark.sql.shuffle.partitions", "64") .getOrCreate()) def run(spark, day): orders = spark.range(0, 100_000).selectExpr( "id AS order_id", "id % 50 AS country_id", "id % 997 AS amount") daily = (orders.groupBy("country_id") .agg(F.sum("amount").alias("revenue"), F.count("*").alias("orders"))) # The executors write the result. Never collect() a large result to the driver. daily.write.mode("overwrite").parquet(f"lab/driver/revenue/day={day}") spark = build_session() run(spark, "2025-03-01") written = spark.read.parquet("lab/driver/revenue/day=2025-03-01") print(written.count(), "countries written") written.orderBy("country_id").show(5)
Output from a real run
50 countries written +----------+-------+------+ |country_id|revenue|orders| +----------+-------+------+ | 0| 993762| 2000| | 1| 993768| 2000| | 2| 993774| 2000| | 3| 993780| 2000| | 4| 993786| 2000| +----------+-------+------+ only showing top 5 rows
What to notice:
- 50 countries were written:
country_idisid % 50, so 100,000 orders become 50 groups of 2,000. - The script never brings the rows back to the driver to save them. The executors write the files themselves; the driver only reads a few back to show you.
Goal: Find out which process runs your Python code: the driver, or the workers.
import os print("driver process:", os.getpid()) def where_am_i(rows): # runs on the executors, in Python worker processes yield (os.getpid(), sum(1 for _ in rows)) result = spark.range(0, 1000, numPartitions=4).rdd.mapPartitions(where_am_i).collect() print("(worker process, rows) per partition:", result)
Output from a real run
driver process: 5010 (worker process, rows) per partition: [(5046, 250), (5044, 250), (5045, 250), (5043, 250)]
What to notice:
- The driver has one process id; the four partitions report four other ids. Your function ran in separate worker processes, not in the driver.
- Each worker handled 250 of the 1,000 rows: one partition each.
- This is the boundary every UDF and RDD function crosses. In local mode the executor lives inside the driver's JVM, but Python code still runs in separate worker processes.
Common mistakes
- Collecting big results to the driver — Driver out-of-memory. Write to storage instead.
- Giving the driver tiny memory while broadcasting — Broadcastbroadcast join: A join where the small table is copied to every machine, so the big table never has to be shuffled. Learn more → tables are built on the driver first. A 1 GB broadcast needs a driver with room for it.
- One huge executor per machine — Long GC pauses and poor throughput. Several medium executors usually work better.
Key takeaways
- The driver plans and schedules; executors run tasks; the cluster manager provides machines.
- DataFrame code builds a plan on the driver; the work runs on executors.
- Client mode keeps the driver on your machine; cluster mode puts it in the cluster.
- Parallelism is executors × cores per executor.
Interview prep
THE QUESTION
"Explain what happens from spark-submit to the job finishing."
Avoid: listing the components ("driver, executors, cluster manager") without saying what happens in which order, or where your code actually runs.
Follow-ups · answer out loud, then open
Follow-up"Where does the code inside a Python UDF run, and where does a plain Python loop run?"
collect() output is driver-side work.Scenario"A nightly job submitted from an edge node dies whenever that node reboots for patching. What would you change?"
Trap"We have 10 nodes with 16 cores each. Should we run one executor per node with 16 cores?"
Check yourself
3 questionsWhere does the body of a Python UDF run?
Show the answer
In Python worker processes on the executors. Executors start Python workers and send them rows for Python UDFs.
8 executors with 5 cores each. How many tasks can run at the same time?
Show the answer
40. Each core is a task slot: 8 × 5 = 40.
Which deploy mode suits a nightly production job?
Show the answer
Cluster mode. In cluster mode the driver runs in the cluster, so the job does not depend on the submitting machine.
Practise this
Interview problems on spark performance, graded on hidden tests
Keep going
Up next · new module: How a job runs · 6 min readTransformations vs actions
Why nothing runs until you call an action, and what lazy evaluation buys Spark.
Related lessons
Jobs, stages and tasksSpark internals · 7 min read
The memory modelSpark internals · 5 min read
Spark Connect
Previous: Run Spark on your laptop
Primary sources: Cluster mode overview · Configuration