Narrow vs wide transformations
Some Spark operations work on each piece of data where it already is; others have to move rows between machines first. The second kind, wide operations, cause the expensive step called a shuffle. This lesson shows how to tell them apart, so you can read a job's cost from its code.
Step 2 · Spark internals · Silver · Shuffles and joins, lesson 1 of 5
On this page
Read first: Jobs, stages and tasks (skip if you know it)
In plain words first
In a library, each shelf can be dusted by whoever stands in front of it: nobody needs another shelf. That is narrow work. Now "put every book by the same author on one shelf": books must be carried across the whole building first. That is wide work, and the carrying is the shuffle.
Narrow and wide
| Narrow (no shuffle) | Wide (shuffle) |
|---|---|
select, withColumn, filter | groupBy().agg(), distinct, dropDuplicates |
explode, union, coalesce(n) | join (unless broadcastbroadcast join: A join where the small table is copied to every machine, so the big table never has to be shuffled. Learn more →), orderBy |
sample, limit 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 → | repartition, window functionswindow function: A function that computes a value for each row from a group of related rows (its window), without collapsing them like groupBy does. Learn more → with partitionBy |
The test: can a tasktask: The work for one partition in one stage, run on one CPU core. Learn more → produce its output by looking only at its own input partition? If yes, it is narrow. Grouping by customer needs every row of a customer, wherever it is, so it is wide.
What a shuffle does
-
Map side
Each task hashes rows by key into N buckets
-
Shuffle write
Buckets are written to local disk
-
Shuffle read
Each reducer fetches its bucket from every mapper over the network
-
Reduce side
Rows of a key are together; work continues
With M map tasks and N reduce partitions, that is up to M × N blocks moved. Everything shuffled is serializedserialization: Turning objects into bytes so they can be sent over the network or stored, and back again. Learn more →, usually compressed, written to disk and read back. On a typical job, shuffles account for most of the run time, which is why the Spark UI shows shuffle read and write sizes for every stagestage: A group of steps Spark can run without moving data between machines. A new stage starts at every shuffle. Learn more →.
Seeing shuffles in a plan
In explain(), every shuffle is an Exchange node. Exchange hashpartitioning(customer_id, 200) means "shuffle by customer_id into 200 partitions". BroadcastExchange is different: it ships a small table to every executorexecutor: A worker process on a cluster machine that runs tasks and holds data in memory. Learn more → instead.
A groupBy in the physical plan
HashAggregate(keys=[country], functions=[sum(amount)])
+- Exchange hashpartitioning(country, 200)
+- HashAggregate(keys=[country], functions=[partial_sum(amount)])
+- FileScan parquet [country,amount]How to shuffle less
- Filter and select early. Fewer rows and columns before the exchange means fewer bytes shuffled. CatalystCatalyst: Spark's query optimizer. It rewrites your DataFrame code into a faster equivalent plan before running it. Learn more → does much of this, but not through UDFsUDF: User-defined function: your own Python function applied to each row. Flexible but much slower than built-in functions. Learn more → or across cachingcache: Keeping a computed DataFrame in memory (or on disk) so later actions reuse it instead of recomputing it. Learn more → boundaries.
- Broadcast small tables so the large side of a join is not shuffled.
- Aggregate before joining when the join is only used to attach attributes to totals.
- Reuse partitioning. If two operations use the same key, Spark can reuse one shuffle; a different key or partition count forces another.
- Bucket tables that are repeatedly joined on the same key: data written pre-shuffled into buckets can be joined without a shuffle, if both sides have matching bucketingbucketing: Writing a table pre-split by a key into a fixed number of files, so later joins on that key skip the shuffle. Learn more →.
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: Make a job shuffle less: drop rows and columns first, aggregate before the join, broadcast the small table.
from pyspark.sql import functions as F orders = spark.range(0, 1_000_000).selectExpr( "id AS order_id", "id % 5000 AS customer_id", "id % 997 AS amount", "CASE WHEN id % 10 = 0 THEN 'REFUNDED' ELSE 'PAID' END AS status") customers = spark.range(0, 5000).selectExpr( "id AS customer_id", "CAST(id % 20 AS STRING) AS region") revenue_by_region = ( orders.where("status = 'PAID'") # narrow: fewer rows to shuffle .select("customer_id", "amount") # narrow: fewer columns to shuffle .groupBy("customer_id") # shuffle 1, on pre-aggregated rows .agg(F.sum("amount").alias("revenue")) .join(customers, "customer_id") # small side: broadcast, no shuffle .groupBy("region") # shuffle 2, tiny .agg(F.sum("revenue").alias("revenue"))) revenue_by_region.write.mode("overwrite").parquet("lab/narrow_wide/revenue_by_region") result = spark.read.parquet("lab/narrow_wide/revenue_by_region") print(result.count(), "regions") result.orderBy("region").show(5)
Output from a real run
18 regions +------+--------+ |region| revenue| +------+--------+ | 1|24899400| | 11|24899903| | 12|24900053| | 13|24900203| | 14|24899356| +------+--------+ only showing top 5 rows
What to notice:
- Only 18 regions, not 20: customers whose id ends in 0 only have refunded orders, and they all live in regions 0 and 10, so those two regions have no paid revenue.
- Regions sort as text (1, 11, 12...) because
regionis a string column. - The order of the steps does the work: the first shuffle moves one pre-summed row per customer instead of every order.
Goal: Count the shuffles (Exchange steps) different operations add to a plan.
import contextlib, io from pyspark.sql import Window, functions as F def exchanges(df): buf = io.StringIO() with contextlib.redirect_stdout(buf): df.explain() return buf.getvalue().count("Exchange ") df = spark.range(0, 100_000).withColumn("k", F.col("id") % 10) by_k = Window.partitionBy("k").orderBy("count") narrow = df.filter("k > 2").withColumn("x", F.col("id") * 2) print("filter + withColumn:", exchanges(narrow)) print("groupBy:", exchanges(df.groupBy("k").count())) print("orderBy:", exchanges(df.orderBy("k"))) print("distinct:", exchanges(df.select("k").distinct())) print("groupBy, then window on the same key:", exchanges(df.groupBy("k").count().withColumn("r", F.rank().over(by_k))))
Output from a real run
filter + withColumn: 0 groupBy: 1 orderBy: 1 distinct: 1 groupBy, then window on the same key: 1
What to notice:
filterandwithColumnadd none: they are narrow, each partition is processed on its own.groupBy,orderByanddistincteach add one: rows must move so equal keys meet.- A window on the same key right after a
groupByadds no second shuffle: the data is already partitioned byk, so Spark reuses it.
Common mistakes
- Calling repartition "to be safe" — Each call is a full shuffle.
- Joining before filtering — Rows that would be filtered out are shuffled for nothing; filter first or check that Catalyst pushes the filter down.
- Window functions with many different partitionBy keys — Each different key is another shuffle.
Key takeaways
- Narrow operations work within a partition; wide ones need a shuffle.
- A shuffle writes, transfers and reads every row involved.
- Shuffles appear as Exchange nodes in explain().
- Filter early, broadcast small tables and reuse partitioning to shuffle less.
Interview prep
THE QUESTION
"Name three transformations that cause a shuffle and three that do not, and explain why."
Avoid: reciting a list without the reason. The test is whether each output partition needs rows from other input partitions.
Follow-ups · answer out loud, then open
Follow-up"Is a window function narrow or wide?"
partitionBy is wide: rows of each window partition must be brought together, so Spark shuffles by the partition keys and sorts by the order keys. A window without partitionBy is worse: everything moves to a single partition.Scenario"A job does groupBy(customer_id), then a join on customer_id, then a window partitioned by customer_id. How many shuffles do you expect?"
Trap"union is a wide transformation because it combines two DataFrames."
Check yourself
3 questionsWhich is a narrow transformation?
Show the answer
withColumn. withColumn computes each row from the row itself.
What appears in a physical plan for a shuffle?
Show the answer
Exchange. Exchange nodes mark data redistribution.
Why does a broadcast join avoid shuffling the large table?
Show the answer
Every executor gets a full copy of the small table, so large-table rows can be joined where they are. With the small side everywhere, no regrouping of the large side is needed.
Practise this
Interview problems on spark performance, graded on hidden tests
Keep going
Up next · Shuffles and joins · lesson 2 of 5 · 5 min readShuffle partitions
The default of 200 shuffle partitions, and how to size them for your data.
Related lessons
Previous: Jobs, stages and tasks
Primary sources: RDD guide: shuffle operations · Performance tuning