Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 1 of 6 · Concept · 25 min · revision 2

From Clusters to Stages: How Spark Runs Your Code

Why Spark replaced chains of MapReduce jobs, what the driver, the executors and the cluster manager each do, why transformations wait for an action, and how one job splits into stages at every shuffle, checked with a job you run in local mode.

Contentsand lesson path

What you will learn

  • Explain Spark's driver and executor model, how a cluster manager (standalone, YARN or Kubernetes) provides executors, lazy transformations versus actions, and how a job splits into stages and tasks at shuffle boundaries.

Prerequisites: Python Foundations

01. Why it matters

A Spark job that finishes in seconds on a sample can take hours, or fail, on the full data. The code is the same, so the difference lies in how Spark runs it: which process does the work, when the work starts, and how much data crosses the network. If you know those three things, you can read a slow job in the Spark UI and predict the cost of a change before you make it.

This lesson builds that picture, and you check each idea on a real job in local mode on your own machine, with no cluster.

02. From MapReduce to Spark

Cluster computing splits one computation across many machines, because the data does not fit on one machine or one machine would take too long. Google described MapReduce in 2004, and Apache Hadoop made it open source. A map step reads a block of input and emits key-value pairs; the framework then groups the pairs by key across the network, which is called the shuffle; a reduce step sees all values for one key and writes the result to the distributed file system, HDFS. Hadoop also made data locality popular: it ran each map task on a machine that already stored that block. Today most data lives in object storage such as S3, which is remote from the compute anyway, so locality matters less and the size of each shuffle matters more.

The weak point of MapReduce was multi-step work. A pipeline with a join and two aggregations became a chain of jobs, and each job wrote its full output to HDFS for the next one to read again. Spark, started at UC Berkeley in 2009, keeps the whole pipeline as one plan. Steps that need no shuffle run one after another in memory, and intermediate data goes to local disk mainly at shuffle boundaries. DataFrames and Spark SQL add the Catalyst optimiser, which rewrites the plan before it runs, for example by pushing filters down to the file reader.

03. Driver, executors and the cluster manager

A running Spark program is an application, with two kinds of process.

  • The driver runs your program. It holds the SparkSession, turns your DataFrame code into a plan, splits the plan into tasks and sends them out. It also receives small results, such as the number from count().
  • The executors run on worker machines. Each runs tasks on its share of the data, keeps the shuffle files it writes and can cache data. Its cores, or task slots, say how many tasks it runs at once.

The cluster manager starts the executors: it hands out machines, memory and cores, but does not plan or run your job. Spark 4.3 supports three: its own standalone manager, Hadoop YARN, and Kubernetes, where the driver and executors run as pods. You pick one with the --master option of spark-submit, for example yarn or k8s://https://host:6443. The plan and the stages of a job are the same on all three. In local mode, local[4], there is no cluster manager: the driver and one executor share one Java process with 4 task slots, which is enough to see plans, stages and tasks as a cluster shows them.

In PySpark, Python talks to the driver's Java process through a bridge called Py4J. A DataFrame call only builds a plan in Java, so rows stay out of Python unless you collect them or apply a Python function to them.

The SparkSession is your entry point for reading data, running SQL and holding settings. Since Spark 3.4 there is a second way to get one, Spark Connect: SparkSession.builder.remote("sc://host:15002") makes your program a thin client that sends unresolved plans over gRPC to a server that hosts the driver. DataFrame code stays the same, but the client cannot reach driver internals, so spark.sparkContext, used below, is not available. There you read the same numbers from the Spark UI and its REST API, as lesson 4 does.

04. A first job in local mode

Spark 4.3 runs on Java 17, 21 or 25 and Python 3.11 or newer; its documentation marks Java 25 releases before 25.0.3 as deprecated. Install a full JDK or JRE 21, for example Eclipse Temurin, and check it with java -version. Create a folder spark-lab/, run every command of this skill from inside it, and set up a virtual environment. The sql extra installs pandas and PyArrow, which Spark uses for Python functions; PySpark 4.3 warns that it does not fully support pandas 3 yet, so the command keeps pandas below 3.

Terminal · one-time setup
java -version
python3 -m venv .venv
source .venv/bin/activate
python -m pip install "pyspark[sql]==4.3.0" "pandas<3" pytest
Illustrative output
openjdk version "21.0.12.1" 2026-08-18 LTS
OpenJDK Runtime Environment Temurin-21.0.12.1+1 (build 21.0.12.1+1-LTS)

The script builds a million fake trips with spark.range, keeps fares above 10 and sums the fare per zone. It first turns adaptive query execution (AQE) off, to show the plain plan, then repeats the query with AQE on, the default. The status tracker of the SparkContext reports which jobs, stages and tasks ran.

Python · spark-lab/first_job.py
from pyspark.sql import SparkSession, functions as F

spark = (
    SparkSession.builder.master("local[4]")
    .appName("first-job")
    .config("spark.sql.adaptive.enabled", "false")  # AQE off for this demo only
    .getOrCreate()
)
spark.sparkContext.setLogLevel("ERROR")
sc = spark.sparkContext
tracker = sc.statusTracker()
print("Spark", spark.version, "| master", sc.master, "| slots", sc.defaultParallelism)

# 1. Transformations only: Spark records a plan and runs nothing.
sc.setJobGroup("demo", "first job")
trips = spark.range(0, 1_000_000, numPartitions=4).select(
    (F.col("id") % 50).alias("zone_id"),
    (F.col("id") % 37 + 3).alias("fare"),
)
paid = trips.filter(F.col("fare") > 10)
per_zone = paid.groupBy("zone_id").agg(F.sum("fare").alias("revenue"))
print("jobs after transformations:", tracker.getJobIdsForGroup("demo"))

# 2. The plan: look for Exchange, the shuffle between two stages.
per_zone.explain()



def show_jobs(group):
    for job_id in sorted(tracker.getJobIdsForGroup(group)):
        for stage_id in sorted(tracker.getJobInfo(job_id).stageIds):
            stage = tracker.getStageInfo(stage_id)
            ran = f"{stage.numCompletedTasks} of {stage.numTasks} tasks ran"
            print(f"  job {job_id}, stage {stage_id}: {ran}")


# 3. An action: now Spark runs a job.
rows = per_zone.collect()
print("zones:", len(rows))
show_jobs("demo")

# 4. The same query with adaptive query execution (AQE) on, the default.
spark.conf.set("spark.sql.adaptive.enabled", "true")
sc.setJobGroup("aqe", "same job with AQE")
per_zone_aqe = paid.groupBy("zone_id").agg(F.sum("fare").alias("revenue"))
print("zones:", len(per_zone_aqe.collect()))
show_jobs("aqe")
spark.stop()
Terminal
python first_job.py

Spark first prints some warnings to standard error, for example about the native Hadoop library; they are left out below. The numbers after # are expression ids.

Expected output
Spark 4.3.0 | master local[4] | slots 4
jobs after transformations: []
== Physical Plan ==
*(2) HashAggregate(keys=[zone_id#1L], functions=[sum(fare#2L)])
+- Exchange hashpartitioning(zone_id#1L, 200), ENSURE_REQUIREMENTS, [plan_id=23]
   +- *(1) HashAggregate(keys=[zone_id#1L], functions=[partial_sum(fare#2L)])
      +- *(1) Project [(id#0L % 50) AS zone_id#1L, ((id#0L % 37) + 3) AS fare#2L]
         +- *(1) Filter (((id#0L % 37) + 3) > 10)
            +- *(1) Range (0, 1000000, step=1, splits=4)


zones: 50
  job 0, stage 0: 4 of 4 tasks ran
  job 0, stage 1: 200 of 200 tasks ran
zones: 50
  job 1, stage 2: 4 of 4 tasks ran
  job 2, stage 3: 0 of 4 tasks ran
  job 2, stage 4: 1 of 1 tasks ran

05. Transformations wait for an action

Look at jobs after transformations: []. The script had built, filtered and grouped a DataFrame, yet Spark had run no job. Methods such as select, filter, withColumn, join and groupBy().agg() are transformations: each returns a new DataFrame that describes a bigger plan, and returns at once. This is lazy evaluation.

Work starts only at an action, a call that needs an answer: count(), collect(), show(), first() or a write. Each action starts one or more jobs. Waiting lets Catalyst optimise the whole plan as one piece: above, the filter sits directly on Range, and a partial sum runs before the shuffle.

Two details surprise people. spark.read.parquet(path) runs one small job to read a file footer and learn the schema, unless you pass .schema(...), but it reads no rows. And every action runs the plan again from the source: count() and then show() on one DataFrame read the input twice, unless you cache it. explain() shows a plan without running it; read it from the bottom up, from the source to the result.

06. Jobs, stages and tasks

A job is the work for one action. Spark cuts it into stages, and each stage into tasks: one task per partition, a slice of the rows that one core processes. Here numPartitions=4 made 4 partitions, so the first stage ran 4 tasks. A stage ends where a step needs rows from other partitions.

  • A narrow transformation, such as filter, select or withColumn, works on each partition alone, so Spark pipelines a chain of them inside one task.
  • A wide transformation, such as groupBy, join, distinct or orderBy, needs all rows with the same key together. Spark must shuffle: each task of the first stage writes its rows into files split by key, and each task of the next stage fetches one split from all of them.

In the plan, the shuffle is the Exchange operator: hashpartitioning(zone_id, 200) sends each row to one of 200 partitions by a hash of zone_id. The next stage cannot start until every shuffle file is written, so each Exchange is a stage boundary. Hence two stages: 4 tasks read and pre-aggregate, then 200 tasks finish the sums. The 200 is the default of spark.sql.shuffle.partitions, whatever the data size. partial_sum below the Exchange means each first-stage task sums its own rows per zone, so it writes at most 50 rows instead of about 196,000. Shuffles go through disk and network, so shrinking rows before an Exchange saves real time.

With AQE on, Spark ran the first stage as its own job (job 1), measured the shuffle output, and only then planned the rest. Job 2 lists stage 3, but 0 of its 4 tasks ran: it repeats stage 2, so the UI marks it as skipped and reuses the shuffle files. AQE also saw that 200 partitions would hold only 50 small rows and merged them into one task. Expect these extra jobs and skipped stages in the Spark UI of every job in this skill.

07. Check your understanding

Practice check · 3 questions

Driver, stages and cluster managers

Each question describes a job like the one in this lesson. Pick the best answer.

Q1. AQE is off and the session is `local[4]`. How many stages and tasks run for this write? spark.range(0, 1_000_000, numPartitions=8) .filter("id % 3 = 0") .withColumn("half", col("id") / 2) .write.parquet("out")
Q2. On a 40 GB table, `trips.write.parquet(path)` works, but `rows = trips.collect()` kills the driver with an out-of-memory error. What explains the difference?
Q3. A team moves a nightly PySpark job from YARN to Kubernetes without changing its code. What changes in how the job runs?
Practice only: not graded, not saved, not evidence.

08. Apply it

The practice project joins a year of trips with a zone lookup and writes daily metrics per zone. Predict its shape with this lesson first:

  1. Group first_job.py by zone and id % 7. Predict the rows the first stage writes to the shuffle, then check.
  2. Add .orderBy("revenue") before collect() and predict the number of Exchange operators.
  3. With AQE off, set spark.sql.shuffle.partitions to 8 and watch the second stage.

09. Review prompt

Without looking back, explain in your own words:

  • what the driver, an executor and the cluster manager each do, and what changes in local mode;
  • why jobs after transformations printed an empty list, and which calls start a job;
  • why an Exchange in the plan always means a new stage;
  • why the second stage had 200 tasks with AQE off, and 1 task with AQE on;
  • what you lose, and what stays the same, when the session comes from Spark Connect.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check