What you will be able to do
- Place application, job, stage and task in order and say what creates each one
- Count the jobs a piece of DataFrame code triggers from the actions it calls
- Count the stages in a job from the shuffles it contains
- Predict how many tasks a stage runs and how they map onto CPU cores
Key concept
Execution hierarchy — A Spark application breaks its work down level by level. Every action starts a job. Every job is cut into stages wherever data has to be shuffled. Every stage runs one task per partition, a partition being a chunk of the dataset's rows that one task processes independently, and each task runs on one executor core.
1.Four levels from application down to task
Spark organises every piece of work into four nested levels: application, job, stage and task. When a query is slow, this hierarchy tells you where to look. The Spark UI is built around it, with a list of jobs, the stages inside each job, and the tasks inside each stage. A five-minute job usually spends its time in one stage, and often in a few tasks within that stage. Once you can read the levels, you can go straight to those tasks.
The application sits at the top. It is your program: one driver plus its own set of executors, which it does not share with any other application. The driver plans the work and the executors run it, as covered in Driver, worker nodes, executors and the cluster manager. This isolation is why two notebooks attached to separate applications cannot read each other's cached data. Each application has its own executor processes, and they stay up for as long as the application runs.
| Level | Created by | How many |
|---|---|---|
| Application | Starting a program with its own driver and executors | One per program |
| Job | An action such as collect or save | One per action |
| Stage | Splitting a job wherever a shuffle occurs | Number of shuffles in the job plus one |
| Task | One partition of a stage's data | One per partition, run on one executor |
Each level depends on the one above it. A task always belongs to exactly one stage, a stage to exactly one job, and a job to exactly one application. The driver does the splitting: it turns your code into jobs, cuts each job into stages, and sends the tasks of each stage to executors. The work only runs on the cluster at the task level, which is why an overloaded driver leaves executors idle even when plenty of work is waiting.
Checkpoint 1 of 7· Match them up
Match each level of the Spark execution hierarchy to what creates it
Tap a term, then the definition that fits it.
Each level is created by something different. A program creates the application. Each action creates a job. Each shuffle splits the job into another stage. Each partition becomes one task that runs on an executor.
“A parallel computation consisting of multiple tasks that gets spawned in response to a Spark action (e.g. save, collect)”Source: spark.apache.org
2.Actions start jobs
A job begins when you call an action. Transformations such as filter and withColumn only add steps to a plan, and nothing runs until an action asks for a result. That model is taught in Transformations, actions and lazy evaluation. For the hierarchy, its consequence is simple: code that only uses transformations starts zero jobs, however long the chain is.
For counting purposes, the rule is one job per action. If you call count() and then collect() on the same DataFrame, two jobs run. Transformations written before them add nothing to the count. They become steps inside each job.
The second action also does not reuse the first one's work. If the DataFrame was not cached or persisted, the second job reads the source again and reapplies every transformation. Spark skips earlier work only when the data is cached or checkpointed. In the Spark UI, those stages appear grey and are labelled as skipped. Two actions on an uncached DataFrame therefore mean two jobs and two full passes over the input. That is why a debugging count() left in a production pipeline costs a whole extra scan.
Checkpoint 2 of 7· Check yourself
A pipeline reads a large Parquet table, applies filter and withColumn, calls count() to log a row total, and then writes the result. The DataFrame is never cached. What happens when the write runs?
Each action starts its own job, and without caching or checkpointing that job recomputes the full lineage from the source. Spark shows stages as skipped only when it can reuse cached or checkpointed data. That is why a debugging count() adds a whole extra scan.
“If the data is checkpointed or cached, then Spark skips recomputing those stages.”Source: docs.databricks.com
Checkpoint 3 of 7· Exam question
A data engineer runs the following PySpark code on a DataFrame orders_df that has not been cached or persisted:
filtered_df = orders_df.filter(orders_df.status == "SHIPPED")
mapped_df = filtered_df.withColumn("total", filtered_df.qty * filtered_df.price)
count_result = mapped_df.count()
collected_rows = mapped_df.collect()
How many Spark jobs does this code trigger?
Correct answer: C — 2 jobs
- A. This is incorrect because
count()andcollect()are both actions, and every action that requests a result from the driver triggers at least one job. - B. This is incorrect because
filterandwithColumnare lazy transformations that build a plan but do not run it; onlycount()andcollect()force execution, and there are two of them. - C. This is correct because
count()andcollect()are each separate actions, and sincemapped_dfwas never cached, each action independently triggers its own job that re-reads and re-applies the filter and column transformations fromorders_df. - D. This is incorrect because there are only two actions in the snippet;
filterandwithColumnare transformations and do not add to the job count on their own. - E. This is incorrect because it overcounts the actions present; only
count()andcollect()request a result, so only two jobs are triggered.
3.Shuffles cut a job into stages
A stage boundary falls wherever data has to be shuffled. Inside a stage, operations are pipelined: each row flows through filter, withColumn and select within the same task, and no data leaves the partition. A shuffle cannot be pipelined like this, because every output partition needs data from every input partition. The details of the shuffle itself are in Shuffles and wide transformations. Here, what matters is that every shuffle ends one stage and starts the next.
For a single chain of operations, the counting rule is: stages = number of shuffles + 1. Narrow operations add nothing, wherever they appear in the chain. Operations that shuffle each add one boundary. These include groupBy with an aggregation, join, distinct, orderBy, and repartition. repartition counts the same way as an aggregation: it moves rows between partitions, so it shuffles.
Here is a worked case. A job reads a DataFrame, filters it, groups it by product_id, and sums a column. The read and the filter run together in stage 1, which also writes the shuffle output. The groupBy aggregation reads that shuffled data in stage 2. That gives two stages for one shuffle. Now put repartition("customer_id") before the filter and keep the groupBy at the end. That adds a second shuffle: stage 1 reads, the repartition shuffle leads into stage 2, which filters, and the groupBy shuffle leads into stage 3. The answer is three stages.
Stages within a job depend on each other in order. The next stage cannot start until every task in the stage before it has finished writing its shuffle output. This is why one slow task holds back everything after it. It is also why the end of each stage is when Spark has accurate statistics about the data, which adaptive optimisation uses to re-plan the rest of the query.
Checkpoint 4 of 7· Check yourself
Consider a job that reads sales_df, filters it, runs groupBy("store_id") with a sum, and ends with collect(). Which one edit raises the job's stage count from two to three?
orderBy shuffles, so it adds a second shuffle and gives 2 + 1 = 3 stages. withColumn, select and extra filters are narrow. They are pipelined inside an existing stage wherever they appear, so they add no stage boundary.
“Spark operators are often pipelined and executed in parallel processes. However, a shuffle or broadcast exchange breaks this pipeline.”Source: www.databricks.com
Checkpoint 5 of 7· Exam question
A developer executes the following code on a DataFrame with 8 partitions:
result_df = sales_df.filter(sales_df.region == "EU") \
.groupBy("product_id") \
.agg(sum("amount").alias("total_amount"))
result_df.show()
How many stages will the resulting Spark job contain?
Correct answer: B — 2 stages
- A. This is incorrect because
groupBy().agg()requires a shuffle to co-locate rows with the same key, and a shuffle always introduces a boundary between stages, so the job cannot run as a single stage. - B. This is correct because
filteris a narrow transformation that runs in the first stage alongside the map-side portion of the aggregation, and the shuffle required bygroupBy().agg()starts a second stage that finalizes the aggregation, giving exactly two stages. - C. This is incorrect because there is only one shuffle-causing operation in this plan;
filterdoes not introduce its own stage boundary since it is a narrow transformation applied within the first stage. - D. This is incorrect because it assumes multiple shuffle boundaries, but only
groupBy().agg()requires data movement between partitions here. - E. This is incorrect because it overstates the number of shuffle boundaries; a single wide operation like this aggregation produces one boundary, not several.
Checkpoint 6 of 7· Exam question
A developer runs the following code on an orders DataFrame:
repartitioned_df = orders_df.repartition("customer_id")
filtered_df = repartitioned_df.filter(repartitioned_df.status == "OPEN")
summary_df = filtered_df.groupBy("customer_id").agg(count("*").alias("open_orders"))
summary_df.collect()
How many stages will the resulting Spark job contain?
Correct answer: C — 3 stages
- A. This is incorrect because the plan contains two operations,
repartitionandgroupBy().agg(), that each require a shuffle, and each shuffle introduces its own stage boundary. - B. This is incorrect because it accounts for only one of the two shuffles in this plan; both
repartitionand the aggregation move data between partitions. - C. This is correct because
repartitionforces a shuffle that ends the first stage,filterthen runs as a narrow transformation inside the resulting stage, andgroupBy().agg()forces a second shuffle that starts a third stage, giving three stages total. - D. This is incorrect because it overcounts the boundaries;
filteris a narrow transformation and does not add a stage on its own between the two shuffles. - E. This is incorrect because it assumes more shuffle-causing operations than are actually present in this plan.
4.Tasks: one partition on one core
The task is where the hierarchy meets the hardware. A partition is a chunk of a dataset's rows that one task processes independently; Spark splits every dataset into partitions so the chunks can be worked on in parallel (see Shuffles and wide transformations). A task processes one partition of one stage, and an executor runs it on one core. A core runs one task at a time, as described in CPU cores as task slots (parallelism). The number of tasks in a stage therefore equals the number of partitions in that stage's data. How many of those tasks run at the same time is capped by the total number of cores across your executors.
Task counts can change from stage to stage within one job. Take a DataFrame read as 8 partitions. Its first stage runs 8 tasks. After a groupBy, the next stage runs one task per shuffle partition, a number set by spark.sql.shuffle.partitions, not by the original 8. On a cluster with 16 cores, the 8-task stage leaves half the cores idle, while a 200-task stage runs in waves of 16.
At the extreme, a stage with exactly one task has no parallelism at all. coalesce(1) and repartition(1) produce such a stage, and so does a window function without PARTITION BY. One core does all the work while the rest of the cluster waits. Adding more workers does not help, because there is only one task to hand out. The fix is to give the stage more partitions.
Checkpoint 7 of 7· Check yourself
A nightly job ends with coalesce(1) before its write, and that final stage takes 40 minutes on a 4-worker cluster. The team doubles the cluster to 8 workers. What happens to that stage's runtime?
A task processes one partition on one core, and coalesce(1) leaves the stage with exactly one task. More workers add cores, but there is no second task to give them. The fix is more partitions, not more hardware.
“A single task means the stage runs with no parallelism, so only one core does the work while the rest of the cluster waits.”Source: docs.databricks.com
Sources
(11)
Every claim above is drawn from one of these pages, quoted as it was written on the date shown.
- 1.
“which jobs ran, how long each stage took, how much data moved, and where tasks failed”
↩︎ Four levels from application down to task - 2.https://docs.databricks.com/aws/en/optimizations/spark-ui-guide/spark-driver-overloadedOfficial docs
“It interprets every command, plans each query, and schedules tasks on the executors.”
↩︎ Four levels from application down to task - 3.https://spark.apache.org/docs/latest/cluster-overview.htmlSecondary source
“User program built on Spark. Consists of a driver program and executors on the cluster.”
↩︎ Four levels from application down to task“Each application gets its own executor processes, which stay up for the duration of the whole application and run tasks in multiple threads.”
↩︎ Four levels from application down to task“A parallel computation consisting of multiple tasks that gets spawned in response to a Spark action (e.g. save, collect)”
↩︎ Actions start jobs“Each job gets divided into smaller sets of tasks called stages that depend on each other”
↩︎ Key concept“A parallel computation consisting of multiple tasks that gets spawned in response to a Spark action (e.g. save, collect)”
↩︎ Checkpoint - 4.https://docs.databricks.com/aws/en/spark/faqOfficial docs
“none of the logic defined by a collection of operations are evaluated until an action is triggered”
↩︎ Actions start jobs“Actions: trigger processing logic to evaluate and output a result.”
↩︎ Exam trap 1 - 5.
“If the data is checkpointed or cached, then Spark skips recomputing those stages.”
↩︎ Actions start jobs“If the data is checkpointed or cached, then Spark skips recomputing those stages.”
↩︎ Exam trap 2 - 6.https://docs.databricks.com/aws/en/ldp/real-timeOfficial docs
“Two-stage stateful (Kafka source + shuffle)”
↩︎ Shuffles cut a job into stages“Three-stage (Kafka source + two shuffles)”
↩︎ Shuffles cut a job into stages“Available task slots must cover all tasks across all query stages.”
↩︎ Tasks: one partition on one core“Two-stage stateful (Kafka source + shuffle)”
↩︎ Exam trap 3 - 7.https://docs.databricks.com/aws/en/optimizations/aqeOfficial docs
“At the end of each shuffle or broadcast exchange, Databricks has accurate statistics for the data produced so far.”
↩︎ Shuffles cut a job into stages - 8.https://www.databricks.com/blog/2020/05/29/adaptive-query-execution-speeding-up-spark-sql-at-runtime.htmlSecondary source
“Each query stage materializes its intermediate result and the following stage can only proceed if all the parallel processes running the materialization have completed.”
↩︎ Shuffles cut a job into stages“Spark operators are often pipelined and executed in parallel processes. However, a shuffle or broadcast exchange breaks this pipeline.”
↩︎ Checkpoint - 9.https://spark.apache.org/docs/latest/rdd-programming-guide.htmlSecondary source
“Operations which can cause a shuffle include repartition operations like repartition and coalesce”
↩︎ Shuffles cut a job into stages“During computations, a single task will operate on a single partition”
↩︎ Tasks: one partition on one core“a collection of elements partitioned across the nodes of the cluster that can be operated on in parallel”
↩︎ Tasks: one partition on one core - 10.
“A single task means the stage runs with no parallelism, so only one core does the work while the rest of the cluster waits.”
↩︎ Tasks: one partition on one core“A single task means the stage runs with no parallelism, so only one core does the work while the rest of the cluster waits.”
↩︎ Exam trap 4 - 11.
“repartition(1) or coalesce(1). These force all data into one partition.”
↩︎ Tasks: one partition on one core