Skip to content
Bronze 7 min read 2 practice problems ↓

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

In plain words first

Think of a restaurant kitchen during service.

The driver: the head chef

Reads the order, plans who cooks what, hands out the work and puts the plates together at the end. There is one.

The executors: the cooks

Each cooks the part of the order they were given, at their own station. There are many, working at the same time.

The cluster manager: the restaurant owner

Decides how many cooks and stations the kitchen gets.

Three roles

Driver

Runs your main program and the SparkSession. Turns DataFrame code into a plan, splits it into stagesstage: A group of steps Spark can run without moving data between machines. A new stage starts at every shuffle. Learn more → and taskstask: The work for one partition in one stage, run on one CPU core. Learn more →, sends tasks to executors, and collects results for actionsaction: An operation that needs a result (count, show, write), so Spark has to run the job. Learn more → like collect().

Executors

JVM processes on worker machines. Each has a number of cores (task slots) and memory. They run tasks, cachecache: Keeping a computed DataFrame in memory (or on disk) so later actions reuse it instead of recomputing it. Learn more → data and write shuffleshuffle: Moving rows between machines so that all rows with the same key end up together. Needed by joins, groupBy and sorting, and usually the most expensive step of a job. Learn more → files.

Cluster manager

Hands out machines. Spark asks it for executors; it starts them. YARN, Kubernetes and Spark's own standalone manager are supported. Mesos was deprecated in Spark 3.2.

What happens when you run a job

  1. 1
    You start an application. The driver process starts and creates a SparkSession.
  2. 2
    The driver asks the cluster manager for executors, for example 10 executors with 4 cores and 16 GB each.
  3. 3
    Your code builds DataFrames. Nothing runs yet: the driver only records a plan.
  4. 4
    An action such as write or count triggers 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 →.
  5. 5
    Tasks are scheduled onto free executor cores. 10 executors with 4 cores run 40 tasks at a time.
  6. 6
    Executors 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.

CodeRuns on
df = spark.read.parquet(...), df.filter(...)Driver: builds the plan only
The filter condition, F.upper(...), joins, aggregationsExecutors, 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 → bodyExecutors, 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 listDriver
Watch out: 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

The driver runs where you launched the application: a laptop, an edge node, a notebook server. Good for interactive work. If that machine disconnects, the job dies.

Cluster mode

The driver runs inside the cluster, on a node the cluster manager picks. Good for scheduled production jobs: nothing depends on the submitting machine.

Sizing an application

SettingMeaning
spark.executor.instancesNumber 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.coresConcurrent tasks per executor
spark.executor.memoryJVM heap per executor
spark.executor.memoryOverheadOff-heap memory per executor (default: the larger of 384 MB and 10% of executor memory)
spark.driver.memoryDriver heap
spark.dynamicAllocation.enabledLet Spark add and remove executors with the workload
PySpark · Setting resources at submit time
# 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.

Production patternPySpark · A job skeleton: settings at startup, results written by the executors
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_id is id % 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.

ExplorePySpark · Where does my code run?
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."

The driver starts and creates the SparkSession; it requests executors from the cluster manager; transformations build a plan lazily; an action creates a job; the DAG scheduler splits it into stages at shuffle boundaries; the task scheduler sends one task per partition to executor cores; executors run tasks and exchange shuffle data; the driver collects the result or the output is written. Mentioning that failed tasks are retried and where Python UDFs run is a plus.

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?"
The UDF body runs on the executors, in Python worker processes started next to each executor JVM; rows are shipped to them in batches. A plain Python loop in your script, and everything that only builds a DataFrame plan, runs on the driver. That is why a UDF can see executor memory limits and why a loop over 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?"
It is running in client mode, so the driver lives on the edge node. Submit in cluster mode so the cluster manager starts the driver inside the cluster; the job no longer depends on the submitting machine. Keep client mode for interactive work, where you want the driver close to you.
Trap"We have 10 nodes with 16 cores each. Should we run one executor per node with 16 cores?"
Usually not. One huge executor has a huge heap with long GC pauses and poor HDFS/S3 client throughput when many tasks share it. A common layout is 3 executors of about 5 cores per node, leaving a core and some memory for the OS and node daemons, then sizing memory per executor from what remains, minus overhead. The exact numbers matter less than explaining the trade-off.

Check yourself

3 questions

Where 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 read
Transformations vs actions
Why nothing runs until you call an action, and what lazy evaluation buys Spark.

Related lessons

Previous: Run Spark on your laptop

Primary sources: Cluster mode overview · Configuration