CertSafari
    Databricks Certified Associate Developer for Apache Spark· Lessons

    Domain 1 · Lesson 5/32

    Spark partitions, shuffles and spark.sql.shuffle.partitions

    Configure Spark partitioning in distributed data processing, including shuffles and partitions

    17 min read
    2.86% of exam
    10 sources
    Published 21 Oct 2026
    Docs as of 17 Oct 2026

    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.

    Read-side settings that decide how many partitions a file scan produces
    SettingDefaultWhat it controls
    spark.sql.files.maxPartitionBytes134217728 (128 MB)Maximum bytes packed into a single partition when reading files
    spark.sql.files.openCostInBytes4194304 (4 MB)Estimated cost of opening a file, used when putting multiple files into a partition
    spark.sql.files.minPartitionNumDefault ParallelismSuggested (not guaranteed) minimum number of split file partitions
    spark.sql.files.maxPartitionNumNoneSuggested 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.

    Inspecting partitions with spark_partition_id after repartition(10)python
    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?

    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()

    Sources1234

    2.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?

    Sources56

    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:

    • groupBy followed by an aggregation, because all rows of a group must meet in one task
    • join, because matching keys from both sides must be co-located
    • distinct, because identical rows must land in the same partition before duplicates can be dropped
    • repartition, 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.

    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?

    Sources275

    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.

    Two settings, two different partition counts in the same query
    SettingDefaultDecides the partitions of
    spark.sql.files.maxPartitionBytes134217728 (128 MB)The file scan at the start of the query
    spark.sql.shuffle.partitions200Every 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.

    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?

    Sources63

    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.

    coalesce(1) collapses three partitions into one without a shufflepython
    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|
    # +---------+
    coalesce versus repartition when reducing the partition count
    Aspectcoalesce(n)repartition(n)
    Data movementNarrow dependency, no shuffleAdds a shuffle step
    Requesting more partitions than existStays at the current numberNot limited to the current number
    Effect of a drastic reduction such as n = 1Computation may run on fewer nodes than you likeUpstream 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|
    # +---------+

    Checkpoint 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?

    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?

    Sources893106

    Sources

    (10)

    Every claim above is drawn from one of these pages, quoted as it was written on the date shown.

    1. 1.
      “The maximum number of bytes to pack into a single partition when reading files.”
      ↩︎ Partitions and where they come from
    2. 2.
      “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. 3.
      “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. 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
    5. 6.
      “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
      “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
    6. 7.
      “the stage spends a lot of time shuffling data between executors for joins or aggregations”
      ↩︎ Shuffles and wide transformations
    7. 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
    8. 10.
      “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

    Spotted a mistake, or was something unclear? Tell us.