What you will be able to do
- Explain how file input becomes partitions and how spark.sql.files.maxPartitionBytes controls their size
- Identify which DataFrame operations trigger a shuffle and why a shuffle costs disk, network and serialization
- State the default of spark.sql.shuffle.partitions, say what it controls, and choose a value against data volume and core count
- Choose between repartition and coalesce, and recognise why a skewed key is not fixed by changing the partition count
Key concept
Partition — A partition is one slice of a DataFrame's rows, and it is the unit Spark schedules: each task processes exactly one partition. How many partitions exist at each step decides how much of the cluster can work at once.
1.Partitions and where they come from
A DataFrame is never processed as one block. Spark splits its rows into partitions, and each task works on one partition. The partition count is therefore the ceiling on parallelism for that step: a DataFrame with 4 partitions can keep at most 4 cores busy, however large the cluster is.
When the input is files, the partition count is decided by file sizes. spark.sql.files.maxPartitionBytes sets the maximum number of bytes Spark packs into one partition while reading, and its default is 134217728 bytes, which is 128 MB. A single large file is split into chunks up to that size, so roughly 1 GB of Parquet arrives as about eight partitions. Small files go the other way: Spark packs several of them into one partition, charging each file an estimated open cost of spark.sql.files.openCostInBytes (default 4 MB) so that a partition of many tiny files is not treated as cheap.
These read settings apply only to file-based sources such as Parquet, JSON and ORC. They decide the partitions of the scan, and they have nothing to do with how many partitions exist after a later groupBy or join; that count comes from a different setting, covered further down.
| Setting | Default | What it controls |
|---|---|---|
| spark.sql.files.maxPartitionBytes | 134217728 (128 MB) | Maximum bytes packed into a single partition when reading files |
| spark.sql.files.openCostInBytes | 4194304 (4 MB) | Estimated cost of opening a file, used when putting multiple files into a partition |
| spark.sql.files.minPartitionNum | Default Parallelism | Suggested (not guaranteed) minimum number of split file partitions |
| spark.sql.files.maxPartitionNum | None | Suggested maximum; Spark rescales partitions toward it if the initial count exceeds it |
The function spark_partition_id() tags every row with the partition it lives in, which makes the partition count visible. The example below builds a DataFrame in 9 partitions, redistributes it into 10, and lists the distinct partition ids: 0 through 9.
from pyspark.sql import functions as sf
df = spark.range(0, 64, 1, 9).withColumn(
"name", sf.concat(sf.lit("name_"), sf.col("id").cast("string"))
).withColumn(
"age", sf.col("id") - 32
)
df.repartition(10).select(
sf.spark_partition_id().alias("partition")
).distinct().sort("partition").show()Checkpoint 1 of 9· Check yourself
A job reads about 1 GB of Parquet with default settings. The session also has spark.sql.shuffle.partitions = 200. Roughly how many partitions does the file scan produce, and which setting decides that?
For file-based sources, the size of the files and spark.sql.files.maxPartitionBytes (128 MB by default) decide how many partitions a scan produces, so 1 GB gives about eight. spark.sql.shuffle.partitions applies only after a shuffle, such as a groupBy or a join.
“The maximum number of bytes to pack into a single partition when reading files.”Source: spark.apache.org
Checkpoint 2 of 9· Fill the gap
Which function completes this sample so that it lists the partition each row lives in after repartition(10)?
from pyspark.sql import functions as sf
df = spark.range(0, 64, 1, 9).withColumn(
"name", sf.concat(sf.lit("name_"), sf.col("id").cast("string"))
).withColumn(
"age", sf.col("id") - 32
)
df.repartition(10).select(
sf. ? ().alias("partition")
).distinct().sort("partition").show()spark_partition_id() tags every row with the id of its partition, so the distinct values 0 through 9 show that repartition(10) produced 10 partitions. monotonically_increasing_id gives each row its own id, not its partition's id.
Source: docs.databricks.com2.Sizing the partition count against cores
Each core runs one task at a time, as covered in CPU cores as task slots (parallelism), so the useful question is how the partition count compares with the total core count. Too few partitions and some cores get no task at all. If 4 large partitions land on a 32-core cluster, 28 cores sit idle for the whole stage.
Too many partitions fail differently. Each task carries a fixed cost to schedule and set up, and a partition holding a few kilobytes spends more time on that overhead than on work. Thousands of tiny tasks also read and write in small, inefficient chunks.
Between those two extremes sits the wave problem. Tasks run in waves of one task per core: 200 partitions on 16 cores means 12 full waves and then a thirteenth wave of only 8 tasks, during which half the cluster waits. A count that is a small multiple of the cores keeps every wave full. Spark's own adaptive coalescing uses the same reasoning, since by default it will not merge shuffle partitions below twice the number of cluster cores.
One slow partition causes the same idle time as an uneven last wave. When one or a few tasks take far longer than the rest, the other cores sit idle until they finish. This is why equal-sized partitions matter as much as the total count.
Checkpoint 3 of 9· Check yourself
On a 64-core cluster, a stage runs 20,000 tasks. Each task reads only about 50 KB, the task durations are nearly identical, and yet the stage is slow. What is the most likely cause?
Each task has a fixed scheduling and setup cost. With 50 KB per partition, that overhead outweighs the actual work, and reading in small chunks wastes I/O. Equal task durations rule out skew, and 20,000 tasks is far too many partitions, not too few.
“Very small tasks have worse I/O throughput and tend to suffer more from scheduling overhead and task setup overhead.”Source: docs.databricks.com
3.Shuffles and wide transformations
A shuffle is how Spark moves rows between partitions so that they end up grouped by key. It is needed whenever an operation needs rows that currently sit in different partitions to be in the same one. To sum sales per customer, every row for customer 42 must reach the same task, yet after a file read those rows are spread across every partition and every machine. Spark therefore reads from all partitions and sends each row to the partition that owns its key, an all-to-all exchange.
Operations that need this exchange are called wide transformations, and they are the ones that group or match rows by value. In DataFrame code these are:
groupByfollowed by an aggregation, because all rows of a group must meet in one taskjoin, because matching keys from both sides must be co-locateddistinct, because identical rows must land in the same partition before duplicates can be droppedrepartition, which redistributes rows on purpose
Narrow transformations such as filter, select and withColumn work on each partition where it already is, and nothing crosses the network.
Only the groupBy aggregation. The filters and withColumn work row by row inside each existing partition. The groupBy needs every row of a country in one task, so it shuffles.
Shuffles are expensive because they use every slow resource at once. Map-side tasks serialize their output, sort it by target partition and write it to a local file. Reduce-side tasks then fetch the blocks they need over the network. The intermediate shuffle files stay on disk until the data that depends on them is garbage collected, so a long-running application can fill local disk (the directory is set by spark.local.dir). When the in-memory structures used to organise records do not fit, Spark also spills them to disk, adding more I/O and garbage collection.
Checkpoint 4 of 9· Check yourself
A long-running Spark application runs many joins and aggregations. It caches nothing and writes no output, yet the local disks on its executors keep filling up. What explains this?
For each shuffle, map-side tasks write intermediate files to local disk, in the directory set by spark.local.dir. Spark keeps those files until the data that depends on them is garbage collected, so a long-running application can fill local disk. Narrow transformations never write shuffle files, because their data stays in the partition where it already is.
“these files are preserved until the corresponding RDDs are no longer used and are garbage collected”Source: spark.apache.org
4.spark.sql.shuffle.partitions: the partition count after a shuffle
spark.sql.shuffle.partitions sets how many partitions a DataFrame or SQL shuffle produces for joins and aggregations, and its default is 200. That number is fixed. It does not depend on the input size or on how many cores the cluster has. Because each partition becomes one task, the stage after a shuffle runs 200 tasks by default, as described in Application → job → stage → task.
| Setting | Default | Decides the partitions of |
|---|---|---|
| spark.sql.files.maxPartitionBytes | 134217728 (128 MB) | The file scan at the start of the query |
| spark.sql.shuffle.partitions | 200 | Every shuffle for joins or aggregations |
The default of 200 suits neither small nor large data. Aggregate 50 MB into 200 partitions and you get 200 tasks of about 250 KB each, all overhead. Join 2 TB into 200 partitions and each task gets about 10 GB, which spills to disk. Change the setting for the session with spark.conf.set("spark.sql.shuffle.partitions", "64") or with SET spark.sql.shuffle.partitions = 64 in SQL. Choose a value that keeps each partition a reasonable size for the data volume and that is a multiple of the core count.
With adaptive query execution on, the configured value is only a starting point. At the end of each shuffle Spark knows the real data size and merges small partitions toward spark.sql.adaptive.advisoryPartitionSizeInBytes (64 MB by default), so a query configured for 200 may run its next stage with far fewer tasks. The mechanics are covered in AQE coalescing of shuffle partitions. Databricks also accepts the value auto, which picks the count from the query plan and input size, and it uses auto as the default on its own compute, but open-source Spark's default is 200.
Checkpoint 5 of 9· Match them up
Match each setting or value to the partition decision it controls in a query that reads Parquet files and then aggregates them
Tap a term, then the definition that fits it.
The file scan and the shuffle get their partition counts from different settings: maxPartitionBytes sizes the read, and spark.sql.shuffle.partitions (default 200) sets the count after a join or aggregation. With AQE on, that count is only a starting point, because Spark merges small partitions toward the advisory size. Databricks' auto value picks the count from the plan.
“Configures the number of partitions to use when shuffling data for joins or aggregations.”Source: spark.apache.org
Checkpoint 6 of 9· Exam question
By default, before any Adaptive Query Execution coalescing takes place, how many partitions does Spark use for the shuffle produced by a groupBy or join operation, per the spark.sql.shuffle.partitions configuration?
Correct answer: B — 200
- A. Eight is far below Spark's documented default and is not a value tied to
spark.sql.shuffle.partitions. - B. The default value of
spark.sql.shuffle.partitionsis 200, which sets the initial number of partitions Spark uses for shuffles triggered by wide operations likegroupByandjoinbefore any adaptive coalescing runs. - C. 2000 is a commonly suggested tuning value for large clusters, but it is not the out-of-the-box default shipped with Spark.
- D. The shuffle partition count is a fixed configuration value, not something Spark derives automatically from the number of executor cores available in the cluster.
5.Changing partitions on purpose: repartition, coalesce and skew
repartition is a shuffle you ask for. repartition(n) produces n partitions, and repartition(n, "col") also places rows by a hash of the column, so equal values land together. The result is hash partitioned. repartitionByRange places rows by sorted ranges of the column instead. Both move every row across the network.
coalesce(n) only reduces the partition count, and it avoids a shuffle by merging partitions that already exist. If you ask for more partitions than you have, the count stays where it is. The catch is parallelism. A drastic coalesce(1) can push all the upstream work onto one node. repartition(1) adds a shuffle, but the upstream partitions still run in parallel before the final merge.
from pyspark.sql import functions as sf
spark.range(0, 10, 1, 3).coalesce(1).select(
sf.spark_partition_id().alias("partition")
).distinct().sort("partition").show()
# +---------+
# |partition|
# +---------+
# | 0|
# +---------+| Aspect | coalesce(n) | repartition(n) |
|---|---|---|
| Data movement | Narrow dependency, no shuffle | Adds a shuffle step |
| Requesting more partitions than exist | Stays at the current number | Not limited to the current number |
| Effect of a drastic reduction such as n = 1 | Computation may run on fewer nodes than you like | Upstream partitions still execute in parallel |
The partition count also sets the output file count, because each partition writes its own file. That is why df.coalesce(1) is the cheap way to get a single output file from a 400-partition DataFrame. A different method, DataFrameWriter.partitionBy, is easy to confuse with these. It belongs to the writer, not the DataFrame, and it lays the output out on disk in one directory per column value. It does not change in-memory partitions, and it does not give you one file.
Skew is the case where no partition count helps. Hash partitioning sends every row with the same key to the same partition, because those rows must be together to compute the result. If one join key holds 40% of the rows, raising spark.sql.shuffle.partitions from 200 to 2,000 still puts that whole key in one partition, and coalesce would only merge it with others and make it larger. Persisting with a storage level such as MEMORY_AND_DISK changes where cached partitions are kept, not how rows are spread across them. The fix that targets skew is AQE's skew join handling (spark.sql.adaptive.skewJoin.enabled, default true). In sort merge and shuffle hash joins it splits an oversized partition into roughly even tasks at runtime. It only does this when the partition is larger than both 256 MB and 5 times the median partition size.
Checkpoint 7 of 9· Fill the gap
The goal is to collapse this 3-partition DataFrame into a single partition by merging the existing partitions, with no shuffle step. Which method belongs in the blank?
from pyspark.sql import functions as sf
spark.range(0, 10, 1, 3). ? (1).select(
sf.spark_partition_id().alias("partition")
).distinct().sort("partition").show()
# +---------+
# |partition|
# +---------+
# | 0|
# +---------+coalesce creates a narrow dependency. It merges partitions that already exist, so no rows go through a shuffle. repartition(1) would also end with one partition, but it adds a shuffle step. partitionBy is a writer method that sets the directory layout on disk, not the in-memory partitions.
Source: docs.databricks.comCheckpoint 8 of 9· Exam question
A Spark job performs a wide join between two large tables where one join key accounts for roughly 40% of all rows, so one shuffle partition holds far more data than the rest and its task runs much longer than the others. Which approach directly targets this specific partition imbalance?
Correct answer: A — Enable AQE skew join handling by leaving spark.sql.adaptive.skewJoin.enabled set to true, letting Spark split the oversized shuffle partition into smaller tasks at runtime.
- A. AQE's skew join optimization detects a partition that is disproportionately larger than the median and splits it (replicating the matching side as needed) into several roughly evenly sized tasks. This is the mechanism built specifically to fix a single oversized shuffle partition without touching the rest of the job.
- B. Raising the total shuffle partition count spreads out the non-skewed keys further but does nothing for a key that already dominates the data — that key's rows still land on one logical partition regardless of how many total partitions exist. It does not address the root cause of the imbalance.
- C. Coalescing after the shuffle merges partitions together locally, which would combine the already-oversized partition with others and make the imbalance worse, not better. Coalesce reduces partition count; it has no mechanism to split a large partition apart.
- D. Changing the storage level affects how a DataFrame is cached for reuse, not how work is distributed across a shuffle. Spilling to disk might avoid an out-of-memory crash but the single task still has to process all of the skewed key's rows, so the runtime imbalance remains.
Checkpoint 9 of 9· Exam question
A DataFrame currently has 400 partitions after several transformations. An engineer needs to write it out as a single file for a downstream system that expects one file per day, and wants to avoid an expensive full shuffle if possible. Which call accomplishes this?
Correct answer: A — df.coalesce(1) reduces the partition count by merging existing partitions locally, avoiding a full shuffle while still producing one output file.
- A. Coalesce reduces the number of partitions by combining existing partitions on the same executor wherever possible, so it can produce a single output partition without redistributing every row across the network. This makes it the lowest-cost way to reach one output file when reducing partition count.
- B. This call does produce exactly one partition and one file, but it forces every row to move across the cluster in a full shuffle, which is unnecessary network and CPU cost when the goal is simply fewer output files.
- C. Hash-partitioning by a column into a single partition still requires Spark to shuffle every row to compute the target partition, so this also pays the full shuffle cost the scenario is trying to avoid, and the column argument is pointless when there is only one partition to hash into.
- D. Partitioning the writer output by a column creates one subdirectory and file set per distinct value of that column, so it produces many files rather than the single combined file the downstream system expects.
Sources
(10)
Every claim above is drawn from one of these pages, quoted as it was written on the date shown.
- 1.https://docs.databricks.com/aws/en/spark/confOfficial docs
“The maximum number of bytes to pack into a single partition when reading files.”
↩︎ Partitions and where they come from - 2.https://spark.apache.org/docs/latest/rdd-programming-guide.htmlSecondary source
“During computations, a single task will operate on a single partition”
↩︎ Partitions and where they come from“The shuffle is Spark’s mechanism for re-distributing data so that it’s grouped differently across partitions.”
↩︎ Shuffles and wide transformations“but they must be co-located to compute the result.”
↩︎ Shuffles and wide transformations“and join operations like cogroup and join.”
↩︎ Shuffles and wide transformations“The Shuffle is an expensive operation since it involves disk I/O, data serialization, and network I/O.”
↩︎ Shuffles and wide transformations“Shuffle also generates a large number of intermediate files on disk.”
↩︎ Shuffles and wide transformations“During computations, a single task will operate on a single partition”
↩︎ Key concept“these files are preserved until the corresponding RDDs are no longer used and are garbage collected”
↩︎ Checkpoint - 3.https://spark.apache.org/docs/latest/sql-performance-tuning.htmlSecondary source
“This is used when putting multiple files into a partition.”
↩︎ Partitions and where they come from“Configures the number of partitions to use when shuffling data for joins or aggregations.”
↩︎ spark.sql.shuffle.partitions: the partition count after a shuffle“control the number of output files just like coalesce, repartition and repartitionByRange”
↩︎ Changing partitions on purpose: repartition, coalesce and skew“Configures the number of partitions to use when shuffling data for joins or aggregations.”
↩︎ Exam trap 1“The maximum number of bytes to pack into a single partition when reading files.”
↩︎ Checkpoint - 4.
“The resulting DataFrame is hash partitioned.”
↩︎ Partitions and where they come from - 5.
“The other cores sit idle while those tasks finish, which results in poor cluster utilization and longer jobs.”
↩︎ Sizing the partition count against cores“Spill is most common during data shuffling.”
↩︎ Shuffles and wide transformations - 6.https://docs.databricks.com/aws/en/optimizations/aqeOfficial docs
“Very small tasks have worse I/O throughput and tend to suffer more from scheduling overhead and task setup overhead.”
↩︎ Sizing the partition count against cores“Two times the number of cluster cores”
↩︎ Sizing the partition count against cores“The default number of partitions to use when shuffling data for joins or aggregations.”
↩︎ spark.sql.shuffle.partitions: the partition count after a shuffle“pick an optimal number and size of post-shuffle partitions”
↩︎ spark.sql.shuffle.partitions: the partition count after a shuffle“The target size after coalescing. Coalesced partitions are close to, but no larger than, this size.”
↩︎ spark.sql.shuffle.partitions: the partition count after a shuffle“Set it to auto to enable auto-optimized shuffle”
↩︎ spark.sql.shuffle.partitions: the partition count after a shuffle“For Structured Streaming, you can't change this value between query restarts from the same checkpoint location.”
↩︎ spark.sql.shuffle.partitions: the partition count after a shuffle“Turns skew join handling on or off.”
↩︎ Changing partitions on purpose: repartition, coalesce and skew“AQE treats a partition as skewed only when both of these conditions are true”
↩︎ Changing partitions on purpose: repartition, coalesce and skew“by splitting (and replicating if needed) skewed tasks into roughly evenly sized tasks”
↩︎ Exam trap 2 - 7.
“the stage spends a lot of time shuffling data between executors for joins or aggregations”
↩︎ Shuffles and wide transformations - 8.
“this operation results in a narrow dependency”
↩︎ Changing partitions on purpose: repartition, coalesce and skew“this may result in your computation taking place on fewer nodes than you like”
↩︎ Changing partitions on purpose: repartition, coalesce and skew“If a larger number of partitions is requested, it will stay at the current number of partitions.”
↩︎ Exam trap 3 - 9.https://docs.databricks.com/aws/en/pyspark/reference/classes/dataframe/repartitionByRangeOfficial docs
“The resulting DataFrame is range partitioned.”
↩︎ Changing partitions on purpose: repartition, coalesce and skew - 10.https://docs.databricks.com/aws/en/pyspark/reference/classes/dataframewriter/partitionByOfficial docs
“Partitions the output by the given columns on the file system.”
↩︎ Changing partitions on purpose: repartition, coalesce and skew“Partitions the output by the given columns on the file system.”
↩︎ Exam trap 4