Jobs, stages and tasks
The Spark UI talks about jobs, stages and tasks. They are how Spark splits your program into work for the cluster, and reading them is the first step in finding why a job is slow. This lesson shows how one action becomes a job, why it splits into stages, and what a task is.
Step 2 · Spark internals · Bronze · How a job runs, lesson 5 of 5
On this page
Read first: Transformations vs actions · Partitions (skip if you know them)
In plain words first
Moving house: the whole move is one job. It has phases that cannot overlap: everything must be packed before the van leaves, and everything unloaded before you unpack. Those phases are stages. Within a phase, each helper packing one room is a task.
Spark starts a new stage wherever data has to be moved between machines, because, like the van, that cannot start until everything before it is done.
Job, stage, task
-
Actionaction: An operation that needs a result (count, show, write), so Spark has to run the job. Learn more →
write,count, ... -
Job
One per action (sometimes more)
-
Stages
Split at shufflesshuffle: 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 →
-
Tasks
One 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 →, per stage
Within a stage, Spark pipelines every narrow operation: a task reads its partition, filters, projects and computes in one pass, without materialising anything in between. A stage ends where rows have to be regrouped across the cluster, which is a shuffle.
Walk through a query
Query · the code
The command
orders.filter("status = 'PAID'") \ .join(customers, "customer_id") \ .groupBy("country").agg(F.sum("amount")) \ .write.parquet("out")
Stage 1 · scan orders
customer_id. One task per input partition, say 400 tasks.Stage 2 · scan customers
customer_id. Runs in parallel with stage 1, since it does not depend on it.Stage 3 · join + partial agg
country. 200 tasks before AQEAQE: Adaptive Query Execution: Spark re-plans a running query using the real data sizes it has measured. Learn more → coalescing.Stage 4 · final agg + write
If customers were small enough to broadcastbroadcast join: A join where the small table is copied to every machine, so the big table never has to be shuffled. Learn more →, stages 2 and 3 would merge into stage 1: no shuffle for the join, so no stage boundary.
Reading the Spark UI
| Tab | What to look for |
|---|---|
| Jobs | Which action is slow. Unexpected extra jobs come from schema inference, count() calls or sort sampling. |
| Stages | The slow stage, its shuffle read and write sizes, and spillspill: Writing data to local disk because it does not fit in memory. Slower, but the job keeps running. Learn more → to memory or disk. |
| Stage detail | The task-time distribution: if the max task takes 10 minutes and the median 5 seconds, you have skewskew: When one key has far more rows than the others, so one task does most of the work while the rest wait. Learn more →. |
| SQL / DataFrame | The physical plan with row counts per operator, after AQE changes. |
| Executorsexecutor: A worker process on a cluster machine that runs tasks and holds data in memory. Learn more → | GC time, failed tasks, memory use per executor. |
Failures and retries
- A failed task is retried up to
spark.task.maxFailurestimes (4 by default) before the job fails. - If shuffle files from a lost executor are needed, Spark re-runs the parts of the previous stage that produced them: lineage makes this possible without checkpointscheckpointing: RDD checkpointing: rdd.checkpoint() (or df.checkpoint()) saves the data to reliable storage and cuts its lineage, so a long chain of steps never has to be recomputed from the start after a failure. Learn more →.
- With speculation on (
spark.speculation), Spark launches a backup copy of unusually slow tasks and uses whichever finishes first. It helps with slow machines, not with skew.
Where tasks run: data locality
The task scheduler tries to run each task close to its data. It records a locality level for every task, shown in the stage detail page:
| Level | Meaning |
|---|---|
PROCESS_LOCAL | Data is in the same executor JVM, for example a cachedcache: Keeping a computed DataFrame in memory (or on disk) so later actions reuse it instead of recomputing it. Learn more → partition |
NODE_LOCAL | Data is on the same machine: a local HDFS block, or shuffle files on that node |
RACK_LOCAL | Data is on another machine in the same rack |
ANY | Data is elsewhere and is read over the network |
NO_PREF | No location matters, as with object storage such as S3, ADLS or GCS |
If no slot is free at the best level, the scheduler waits up to spark.locality.wait (3 seconds) before trying the next level down. On object storage every task is NO_PREF, so locality does not matter. With cached data on a busy cluster, tasks waiting for a PROCESS_LOCAL slot can leave other cores idle; lowering spark.locality.wait helps.
Exchange nodes in explain()) is the fastest way to estimate how expensive a query is.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: Label each step of a job so the Spark UI tells you which step is slow.
from pyspark.sql import functions as F def step(name): spark.sparkContext.setJobDescription(name) # shown in the Jobs and SQL tabs orders = spark.range(0, 500_000).withColumn("customer", F.col("id") % 1000) step("orders: count per customer") per_customer = orders.groupBy("customer").agg(F.count("*").alias("orders")) per_customer.write.mode("overwrite").parquet("lab/jobs/per_customer") step("orders: top customers") top = (spark.read.parquet("lab/jobs/per_customer") .orderBy(F.desc("orders"), "customer").limit(5)) top.write.mode("overwrite").parquet("lab/jobs/top_customers") spark.sparkContext.setJobDescription(None) spark.read.parquet("lab/jobs/top_customers").orderBy("customer").show()
Output from a real run
+--------+------+ |customer|orders| +--------+------+ | 0| 500| | 1| 500| | 2| 500| | 3| 500| | 4| 500| +--------+------+
What to notice:
- The output is just the result: the top 5 customers, each with 500 orders (500,000 orders over 1,000 customers).
- The labels are not in this output. Open the Spark UI while it runs: the Jobs and SQL tabs show orders: count per customer and orders: top customers instead of generic names.
Goal: Count how many jobs, stages and tasks a single query creates.
from pyspark.sql import functions as F sc = spark.sparkContext sc.setJobGroup("lab-stages", "join + groupBy") spark.conf.set("spark.sql.autoBroadcastJoinThreshold", -1) # force a shuffle join orders = spark.range(0, 1_000_000).withColumn("customer", F.col("id") % 1000) customers = spark.range(0, 1000).selectExpr("id AS customer", "id % 3 AS tier") orders.join(customers, "customer").groupBy("tier").count().collect() tracker = sc.statusTracker() for job_id in sorted(tracker.getJobIdsForGroup("lab-stages")): stages = [tracker.getStageInfo(s) for s in tracker.getJobInfo(job_id).stageIds] print(f"job {job_id}: tasks per stage {[s.numTasks for s in stages if s]}") sc.setJobGroup(None, None)
Output from a real run
job 44: tasks per stage [4] job 45: tasks per stage [4] job 46: tasks per stage [4, 4, 1] job 47: tasks per stage [4, 4, 1, 1]
What to notice:
- One
collect()produced four jobs. With AQE on, Spark runs each shuffle stage as its own small job. - Each number in a list is one stage's task count: 4 tasks for the stages that read the data (one per core), then 1 after the shuffle.
- In the Spark UI, the SQL tab groups these jobs under one query.
Common mistakes
- Looking at average task time only — Skew hides in the maximum. Check the distribution.
- Assuming one action is one job — Schema inference, sort sampling and broadcasts can add jobs.
- Blaming the last stage — The slow part is often an earlier stage; the UI shows each stage's time.
Key takeaways
- An action creates a job; shuffles split it into stages; partitions become tasks.
- Narrow operations are pipelined inside a stage.
- The Spark UI task-time distribution reveals skew.
- Failed tasks are retried, and lost shuffle output is recomputed from lineage.
Interview prep
THE QUESTION
"How many stages does a groupBy followed by a join of two large tables on a different key have?"
Avoid: guessing a number without explaining the rule. The interviewer wants to hear "stages are cut at shuffles" and then count the shuffles.
Follow-ups · answer out loud, then open
Follow-up"What is the difference between a job, a stage and a task, in one sentence each?"
Scenario"The stage view shows a median task time of 5 seconds and a max of 25 minutes. What do you check next?"
groupBy(key).count() on the input, then fix it with AQE skew handling, broadcasting, salting or by handling the hot key separately. If sizes are equal, look at that executor instead: GC, a bad disk or a slow node.Trap"Does turning on spark.speculation fix skew?"
Check yourself
3 questionsWhat always marks a boundary between two stages?
Show the answer
A shuffle. Stages are split wherever rows must be redistributed across the cluster.
A stage reads 300 partitions. How many tasks does it run?
Show the answer
300. One task per partition in a stage.
In the stage view, max task time is 12 minutes and the median 4 seconds. What is the likely problem?
Show the answer
Data skew. A few tasks processing far more data than the rest is the signature of skew.
Practise this
Interview problems on spark performance, graded on hidden tests
Keep going
Up next · new module: Shuffles and joins · 6 min readNarrow vs wide transformations
Which operations move data across the network, and why the shuffle is the most expensive step.
Related lessons
Data skew and saltingSpark internals · 6 min read
Catalyst and physical plans
Previous: Partitions
Primary sources: Web UI guide · Cluster mode overview