The full answer
A shuffle is Spark's mechanism for redistributing data across partitions so that rows with the same key end up together. It happens whenever an operation needs data from many input partitions to produce one output partition, and it is usually the most expensive part of a job because it involves disk writes, network transfer, serialisation and sorting.
Operations that cause shuffles
- Aggregations by key:
groupBy().agg(),reduceByKey,groupByKey,distinct. - Joins, unless one side is broadcast or both sides are already partitioned the same way (bucketed tables, storage-partitioned joins).
repartition,repartitionByRange, andorderBy/sort(global sorting).- Window functions with
partitionBy. - Set operations such as
intersectandexcept.
Operations like filter, select, withColumn and union don't shuffle; they work on each partition independently.
How a shuffle works
- Map side: each task in the stage before the shuffle partitions its output by key (hash or range) into as many buckets as there are shuffle partitions, and writes them to local disk as shuffle files.
- Stage boundary: the next stage starts only when the map side is complete.
- Reduce side: each task fetches its bucket from every map task over the network and processes it.
In the Spark UI, a shuffle appears as an Exchange in the SQL plan and as shuffle write and shuffle read sizes on the stages.
Why shuffles are costly
- Data is serialised and written to disk, then read and sent over the network.
- The number of files can be very large: map tasks × reduce partitions.
- Uneven keys cause skew: one reduce task gets far more data than the others.
- Memory pressure leads to spilling during sorts and aggregations.
How to reduce their cost
- Filter and select early so less data is shuffled; Catalyst does much of this automatically.
- Broadcast small tables in joins (automatic below
spark.sql.autoBroadcastJoinThreshold, 10 MB by default, or with abroadcasthint). - Prefer aggregations that combine on the map side: DataFrame aggregations do this automatically; with RDDs, use
reduceByKeyinstead ofgroupByKey. - Right-size shuffle partitions:
spark.sql.shuffle.partitionsdefaults to 200. Adaptive query execution (on by default) merges small partitions after the shuffle, so set the initial number high enough for large jobs. - Handle skew: AQE splits skewed partitions in sort-merge joins; for aggregations, salting the key helps.
- Reuse layouts: bucketed tables, or tables clustered on join keys, avoid repeated shuffles; caching a shuffled result helps when it is reused several times.
- Avoid unnecessary global sorts:
sortWithinPartitionswhen total order isn't needed.
Infrastructure Shuffle files live on executors' local disks, so fast local SSDs help. Dynamic allocation needs shuffle tracking or an external shuffle service so shuffle files outlive executors, and some platforms add remote shuffle services for very large jobs.
Last updated 16 October 2026
Sources