Distributed Primitives

This family of questions arrives as a code snippet and a prompt: how many stages will this run, and why? The answer comes down to 2 distinctions. Transformations versus actions decides when work happens. Narrow versus wide decides whether rows move between machines, and moving rows accounts for nearly all of the cost.

Transformations describe, actions execute

filter is a transformation, as are select and groupBy: each returns a new DataFrame and computes nothing, and the driver appends a step to the plan. Actions like write demand a result, and so do count and collect; only then does the driver optimize the full plan and launch a job. Deferring the work pays off because the optimizer sees every step together: a filter written after a join can move before it, and columns no later step reads are never loaded from disk.

events = spark.read.load("/lake/viewing_events/dt=2026-10-22/")
watched = (
    events
    .filter(events.event_type == "play")
    .select("profile_id", "title_id", "country", "minutes")
)
daily = watched.groupBy("profile_id", "title_id", "country").sum("minutes")
daily.write.partitionBy("country").mode("overwrite").save("/lake/daily_watch_time/dt=2026-10-22/")

Narrow or wide: does a row have to move?

A transformation is narrow when each input partition feeds at most 1 output partition. filter on partition 37 needs nothing but partition 37, so the task that read it applies the filter where the rows already sit, and a chain of narrow steps runs inside that task without pausing. A transformation is wide when the rows of an input partition scatter to many output partitions. Summing minutes for each profile and title within a country needs every row for that combination in the same place, and those rows are spread across all 10,000 input files, so they must be regrouped by key. That regrouping is a shuffle, and every shuffle ends a stage and begins the next.

OperationNarrow or wideWhy
`filter`, `select`, `withColumn`NarrowEach row is handled in the partition it already sits in
`union`NarrowInput partitions pass through side by side
`coalesce(n)`NarrowWhole input partitions merge into fewer outputs without scattering
`groupBy` then `agg`WideRows sharing a key must meet in a single partition
`join`, both sides largeWideMatching keys from both tables must land together
`distinct`WideDuplicates can sit in any partition
`orderBy`WideA global order spans every partition
`repartition(n)`WideEvery input partition scatters rows to every output

In SQL the rule reads off the clauses. WHERE and the expressions in the SELECT list are narrow. JOIN, GROUP BY, DISTINCT and ORDER BY are wide, unless the planner broadcasts the small side of a join, which the next section covers. A window function with PARTITION BY is wide too.

Predict the stages

SELECT
  e.country,
  t.genre,
  SUM(e.minutes) AS minutes_watched
FROM viewing_events AS e
JOIN titles AS t
  ON e.title_id = t.title_id
WHERE e.event_type = 'play'
GROUP BY
  e.country,
  t.genre

The query runs in 4 stages. Stage 1 scans viewing_events, applies the WHERE filter inside the scan tasks, and writes rows out keyed by title_id. Stage 2 does the same for titles, and the 2 scans run at the same time because neither needs the other. Stage 3 joins the 2 shuffled outputs and starts summing, but the join key is title_id while the grouping key is country and genre, so the partial sums shuffle again. Stage 4 finishes the aggregate. Notice that the filter added no stage and no network traffic: it ran before any row moved.

Why the distinction matters on retry

Lineage makes narrow failures cheap. If the stage 1 task for partition 37 dies, the rerun reads the same input file and repeats the same filter: 1 file, about 15 seconds of work. A wide step has no such clean edge. One partition of the aggregate depends on shuffle files written by all 10,000 scan tasks, and if an executor holding some of those files is gone, those scan tasks run again before the aggregate can retry.

A chain of narrow steps
  • Runs inside a single task, with no disk write or network hop between steps
  • A failure reruns 1 partition from its source file
  • Partition count stays whatever the input produced
A wide step
  • Ends a stage, and the next stage waits for every upstream task
  • A lost executor can force upstream tasks to rerun
  • Partition count resets to the shuffle setting, 200 by default

Each action is its own job. Calling count and then write on the same DataFrame scans the input twice, unless the DataFrame is cached before the first action.

About this lesson

This section is part of the Distributed Compute: Beginner lesson on DataDriven, the home of data engineering. Lessons cover SQL, Python, Spark, data modeling and pipeline architecture, and each section pairs its explanation with worked examples and practice you run as you go.