Skip to content
Bronze 7 min read · spark.sql.files.maxPartitionBytes 2 practice problems ↓

Partitions

Spark splits every DataFrame into pieces called partitions, and each piece is worked on by one core at a time. Too few pieces leave cores idle; too many waste time on overhead. This lesson shows what a partition is, how many you get, and how to change the number.

Step 2 · Spark internals · Bronze · How a job runs, lesson 4 of 5

Read first: Driver, executors and the cluster manager (skip if you know it)

In plain words first

Forty people must grade 10,000 exam papers. Split into 8 piles, 32 people stand around with nothing to do. Split into 10,000 piles of one paper, everyone spends more time walking to fetch the next pile than grading. A few piles per person is right.

The piles are partitions, the people are CPU cores, and grading one pile is one tasktask: The work for one partition in one stage, run on one CPU core. Learn more →.

What a partition is

A DataFrame is split into partitions, each processed by one task on one core. A DataFrame with 8 partitions on a cluster with 40 cores can only use 8 of them in a stagestage: A group of steps Spark can run without moving data between machines. A new stage starts at every shuffle. Learn more →. A DataFrame with 40,000 tiny partitions keeps the scheduler busy launching tasks that each finish in milliseconds.

Where partition counts come from

SituationNumber of partitions
Reading files (ParquetParquet: A columnar file format: values of each column are stored together, so queries read only the columns they need. Learn more →, ORC, CSV, JSON)Files are split into chunks of up to spark.sql.files.maxPartitionBytes (128 MB). Small files are packed together, counting each file as at least spark.sql.files.openCostInBytes (4 MB).
After a shuffleshuffle: Moving rows between machines so that all rows with the same key end up together. Needed by joins, groupBy and sorting, and usually the most expensive step of a job. Learn more → (join, groupBy, distinct)spark.sql.shuffle.partitions (200), then coalesced by AQEAQE: Adaptive Query Execution: Spark re-plans a running query using the real data sizes it has measured. Learn more →
spark.range, parallelizespark.default.parallelism, usually the total number of cores
repartition(n) / coalesce(n)Exactly n (coalesce can only go down)

So a 10 GB Parquet table read with defaults gives about 80 partitions (10 GB / 128 MB), regardless of how many files it has, as long as the files are large enough to split.

PySparkSpark SQL · Inspect and change partitions
df.rdd.getNumPartitions()       # how many right now
df.repartition(64)              # full shuffle into 64 even partitions
df.repartition(64, "customer_id")  # shuffle by key
df.coalesce(8)                  # merge down to 8, no full shuffle
-- SQL hints
SELECT /*+ REPARTITION(64) */ * FROM orders;
SELECT /*+ REPARTITION(64, customer_id) */ * FROM orders;
SELECT /*+ COALESCE(8) */ * FROM orders;

repartition vs coalesce

repartition(n)

Full shuffle. Produces n partitions of roughly equal size. Can increase or decrease. Use it to fix skewedskew: When one key has far more rows than the others, so one task does most of the work while the rest wait. Learn more → or too few partitions, or to cluster by a key before writing.

coalesce(n)

Merges existing partitions without a shuffle. Only decreases. Cheap, but partitions can end up uneven, and it reduces the parallelism of the whole preceding stage.
MethodWhat it doesTypical use
repartition(n, col)Hash-partitions by the column: every row of a key lands in the same partition, but partitions hold unrelated keys in no orderCo-locate keys before a write partitioned by that column, or before repeated work on the key
repartitionByRange(n, col)Samples the column to pick boundaries, then puts contiguous key ranges into each partitionOutput files that each cover a key range (dates, ids), so readers can skip files by min/max statistics
sortWithinPartitions(col)Sorts each partition locally, with no shuffleSorted files for better compression and data skipping, without the cost of a global orderBy
Watch out: coalesce(1) before a write does not just produce one file: because it avoids a shuffle, Spark runs the entire upstream stage, joins and filters included, in a single task. For one output file after heavy work, repartition(1) is often faster, because the heavy part stays parallel.

How many is right?

  • Aim for partitions of roughly 100 to 200 MB of data in memory, a common rule of thumb.
  • Aim for at least 2 to 4 times as many partitions as cores in a stage, so a slow task does not leave the rest of the cluster idle.
  • Check the Spark UI: tasks taking under 100 ms suggest too many partitions; tasks spillingspill: Writing data to local disk because it does not fit in memory. Slower, but the job keeps running. Learn more → to disk or taking many minutes suggest too few or skewed ones.

Not to be confused with table partitioning

A table partitioned on disk (folders like date=2025-03-01/) is a storage layout for skipping data. In-memory partitions are a runtime concept for parallelism. Reading one folder can produce many in-memory partitions, and many small folders can be packed into a few. The Partitioning done right lesson covers table partitioning.

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: Control partition sizes at the three places a job creates them: reading input, shuffling, and writing output.

Production patternPySpark · Partition sizes in a real job: input splits, shuffles and output files
from pyspark.sql import functions as F

# Set once per job: input split size and shuffle partitions.
spark.conf.set("spark.sql.files.maxPartitionBytes", "128m")
spark.conf.set("spark.sql.shuffle.partitions", "64")

events = (spark.range(0, 500_000)
          .withColumn("event_date",
                      F.expr("date_add('2025-03-01', CAST(id % 7 AS INT))"))
          .withColumn("user_id", F.col("id") % 10_000))
daily = events.groupBy("event_date", "user_id").count()

# One task per date before a partitioned write: one file per folder instead of 64.
(daily.repartition("event_date")
      .write.mode("overwrite").partitionBy("event_date")
      .parquet("lab/partitions/daily_users"))

# A small summary for another system: a single file is fine here.
summary = daily.groupBy("event_date").agg(F.sum("count").alias("events"))
(summary.coalesce(1).write.mode("overwrite")
        .option("header", "true").csv("lab/partitions/summary"))
(spark.read.option("header", "true").csv("lab/partitions/summary")
      .orderBy("event_date").show(3))

Output from a real run

+----------+------+
|event_date|events|
+----------+------+
|2025-03-01| 71429|
|2025-03-02| 71429|
|2025-03-03| 71429|
+----------+------+
only showing top 3 rows

What to notice:

  • 500,000 events over 7 days gives about 71,429 events a day: the summary shows the first three days.
  • The summary was written with coalesce(1), so it is a single CSV file: fine for a small table another system will read.
  • The big table was repartitioned by event_date first, so each date folder gets one file instead of up to 64.

Goal: Count partitions, change how many there are, and check how evenly the rows are spread.

ExplorePySpark · Count, change and inspect partitions
from pyspark.sql import functions as F

df = spark.range(0, 1_000_000)
print("spark.range:", df.rdd.getNumPartitions())          # one per core by default
print("repartition(16):", df.repartition(16).rdd.getNumPartitions())
print("coalesce(2):", df.coalesce(2).rdd.getNumPartitions())

# How many rows landed in each partition after repartition(4)?
(df.repartition(4)
   .groupBy(F.spark_partition_id().alias("partition")).count()
   .orderBy("partition")
   .show())

Output from a real run

spark.range: 4
repartition(16): 16
coalesce(2): 2
+---------+------+
|partition| count|
+---------+------+
|        0|250000|
|        1|250000|
|        2|250000|
|        3|250000|
+---------+------+

What to notice:

  • spark.range started with 4 partitions: one per core of the local[4] session.
  • repartition(16) gave 16 and coalesce(2) gave 2.
  • After repartition(4), every partition holds exactly 250,000 rows: an even spread.

Common mistakes

  • coalesce(1) after heavy work — Runs the whole upstream stage in one task. Use repartition(1), or accept several files.
  • repartition before every step — Each call is a full shuffle. Only repartition with a reason.
  • Ignoring partition count when reading many tiny files — Even with packing, millions of files mean millions of file opens. Compact them.

Key takeaways

  • One task per partition per stage: partitions set the parallelism.
  • File reads split into about 128 MB chunks; shuffles produce 200 partitions before AQE.
  • repartition shuffles and balances; coalesce merges without a shuffle.
  • Target roughly 100 to 200 MB per partition and several partitions per core.

Interview prep

THE QUESTION

"What is the difference between repartition and coalesce, and when would coalesce be the wrong choice?"

repartition does a full shuffle and can increase or decrease the count with even sizes; coalesce merges partitions without a shuffle and only decreases. coalesce is wrong after an expensive stage when you reduce drastically, because the whole stage then runs with that low parallelism; it can also produce uneven partitions.

Avoid: "coalesce is always better because it avoids a shuffle". That is exactly when it is wrong: after heavy work, it collapses the whole stage onto a few tasks.

Follow-ups · answer out loud, then open

Follow-up"How does Spark decide how many partitions to create when it reads 500 Parquet files?"
It splits files into chunks of up to spark.sql.files.maxPartitionBytes (128 MB) and packs small files together, counting each as at least openCostInBytes (4 MB). The count depends on total size and file sizes, not the number of files. When the data is small for the cluster, Spark uses smaller splits (about total bytes divided by the default parallelism) so every core gets work.
Scenario"A stage has 8 tasks on a cluster with 200 cores, and each task runs for 20 minutes. What do you do?"
There are too few partitions for the cluster. Find where the 8 comes from: a source with few large unsplittable files (gzip CSV), a coalesce(8) upstream, or a JDBC read without partitioning options. Fix the source (splittable format, numPartitions and bounds for JDBC) or repartition after reading if the later work is heavy.
Trap"Is a partition the same thing as a partition folder like date=2025-01-01?"
No. In-memory partitions are the unit of parallelism at runtime. Table partitions are a storage layout used to skip folders. Reading one folder can produce many in-memory partitions, and many small folders can be packed into one.

Check yourself

3 questions

With defaults, roughly how many partitions does reading a 6.4 GB splittable Parquet table produce?

Show the answer

50. 6.4 GB divided by 128 MB per partition is about 50.

Which can increase the number of partitions?

Show the answer

repartition. coalesce only merges partitions; repartition shuffles into any number.

Why can coalesce(1) make a whole job slow?

Show the answer

Without a shuffle, the entire upstream stage runs in one task. coalesce is narrow, so it reduces the parallelism of the stage it belongs to.

Practise this

Interview problems on spark performance, graded on hidden tests

Keep going

Up next · How a job runs · lesson 5 of 5 · 7 min read
Jobs, stages and tasks
How one action becomes a DAG of stages split at shuffles, and how to read it in the Spark UI.

Related lessons

Previous: Why DataFrames are faster than RDDs

Primary sources: Performance tuning · Configuration