Jobs, stages & tasks

Apache Spark · Spark Architecture

Theory

Spark turns your code into three levels of work. A job is created each time you call an action such as count(), collect(), show() or write. The driver splits each job into stages at shuffle boundaries: all the narrow steps that can run without moving data between machines (read, filter, map, select) are pipelined into one stage, and a wide step like groupBy, join or reduceByKey starts a new stage. Each stage runs as a set of tasks, one task per partition, and tasks are what executors actually run.

For example, reading orders in 3 partitions, mapping to (region, amount) and then reduceByKey into 2 partitions gives 1 job with 2 stages: stage 1 has 3 tasks that read, map and write shuffle files, and stage 2 has 2 tasks that fetch the shuffled data and add up the amounts. The Spark UI shows exactly this hierarchy, which is where you go to find the slow stage or the one straggling task.

Why we use it

Performance tuning starts by reading jobs, stages and tasks in the Spark UI. Too few tasks leaves cores idle, one huge task signals data skew, and every extra stage means a shuffle. Interviewers often ask how Spark decides the number of stages and tasks.

When to use it

Use this model whenever you read the Spark UI, estimate parallelism (tasks per stage vs available cores) or try to cut shuffles. Note that some DataFrame operations, and adaptive query execution, can trigger extra small jobs, so counts in the UI may not match one-action-one-job exactly.

How it works

  1. Call an action (collect, count, write)
  2. Driver creates a job from the plan
  3. DAG scheduler splits the job at shuffle boundaries into stages
  4. Each stage becomes one task per partition
  5. Task scheduler sends tasks to executor cores
  6. Does another stage depend on this one? Yes: Write shuffle files, then start the next stage. No: Return or write the final result.
  7. Job complete

Syntax

action            -> 1 job (sometimes more)
shuffle boundary  -> new stage
partition         -> 1 task per stage
sc.setJobGroup("id", "desc"); sc.statusTracker().getJobIdsForGroup("id")

Example

from pyspark.sql import SparkSession, functions as F

spark = (SparkSession.builder.master("local[1]")
         .config("spark.ui.enabled", "false")
         .getOrCreate())

sc = spark.sparkContext
sales = [("North", 55000.0), ("West", 30000.0), ("North", 1500.0),
         ("South", 52000.0), ("West", 25000.0), ("East", 15000.0)]

sc.setJobGroup("demo", "sales per region")
pairs = sc.parallelize(sales, 3)                         # 3 partitions -> 3 tasks
totals = pairs.reduceByKey(lambda a, b: a + b, numPartitions=2)  # shuffle -> new stage
print(sorted(totals.collect()))                          # action -> job

tracker = sc.statusTracker()
for job_id in tracker.getJobIdsForGroup("demo"):
    stage_ids = sorted(tracker.getJobInfo(job_id).stageIds)
    print("job", job_id, "has", len(stage_ids), "stages")
    for sid in stage_ids:
        print("  stage", sid, "->", tracker.getStageInfo(sid).numTasks, "tasks")

# Output:
# [('East', 15000.0), ('North', 56500.0), ('South', 52000.0), ('West', 55000.0)]
# job 0 has 2 stages
#   stage 0 -> 3 tasks
#   stage 1 -> 2 tasks

Key points

Apache Spark topics

Spark Fundamentals

Spark Architecture

RDDs

DataFrames

Aggregations & Joins

Spark SQL

Window Functions

Cleaning & Complex Types

UDFs

Performance Tuning

Structured Streaming

MLlib & Ecosystem

Interview Prep

T
Tech Town
Log InSign Up Free
Home SQL Python DSA Power BI Snowflake Databricks Spark Gen AI Practice Problems Contest Blog

Master Apache Spark

PySpark and Spark SQL from the ground up: DataFrames, joins, window functions, partitions and performance tuning, Structured Streaming and more. Click any topic in the sidebar to open it right here.

{{ sectionCount }}
Sections
{{ topicCount }}
Topics
Free
Forever
Hands-on practice Practice PySpark Write real PySpark — DataFrames, joins, window functions and Spark SQL — in a live editor with hidden tests and instant checking. Start practising →
Section {{ sec.num }}

{{ sec.label }}

Spark  /  {{ current.sectionLabel }}  /  {{ current.name }}

{{ current.name }}

Theory

{{ current.def }}

Why we use it

{{ rich.why }}

When to use it

{{ rich.when }}

{{ sec.h }}

{{ sec.body }}

{{ sec.body }}

Diagram

{{ rich.dg.caption }}

{{ tb.title }}
{{ c.v }}
{{ rich.dg.op }}
➜
{{ rich.dg.output.title }}
{{ c.v }}
{{ nd.label }}
{{ nd.sub }}
{{ nd.label }}
{{ nd.sub }}
{{ rich.dg.left.title }}
{{ it }}
{{ rich.dg.right.title }}
{{ it }}
On screen — where to click

{{ rich.ui.title }}

{{ u.text }}
  1. {{ st.n }}{{ st.text }}
{{ rich.ui.title }}
{{ u.text }}
Flowchart — how it works
{{ nd.text }}
{{ nd.text }}
◇ {{ nd.text }}
Yes → {{ nd.yes }}
No → {{ nd.no }}
Syntax
{{ current.syntax }}
Example
{{ current.example }}
Want to run this yourself? Try the same API on Practice PySpark Online right in your browser, or run it locally after pip install pyspark (needs Java 17+), or paste it into a Databricks Free Edition notebook.
Key Points — click to check off as you learn
  • {{ pt.mark }} {{ pt.text }}

Share this topic