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
On this page
Show code in
Every code block on the page follows this.
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
| Situation | Number 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, parallelize | spark.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.
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)
coalesce(n)
| Method | What it does | Typical 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 order | Co-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 partition | Output 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 shuffle | Sorted files for better compression and data skipping, without the cost of a global orderBy |
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.
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_datefirst, 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.
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.rangestarted with 4 partitions: one per core of thelocal[4]session.repartition(16)gave 16 andcoalesce(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?"
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?"
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?"
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?"
Check yourself
3 questionsWith 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 readJobs, 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