Partitions and files
Part of the free LogicWiz Data Engineering course, Module 12: How Spark runs. The SQL and Python run in the app, on real Postgres and real Python in the browser.
It is 8:15 on Monday. A month ago Tess's dashboard query took 8 seconds. Today it takes 3 minutes, and the table behind it holds 6,000 files of a few hundred KB each. On Tuesday someone reruns one day, and the next morning the table holds only that day. Nobody changed a query. Nora shrugs: "Then the writes did it. Twice."
You'll learn to
- Predict how many files a write makes
- Choose between repartition and coalesce
- Rerun one day without deleting the others
- Say when bucketing removes a shuffle
Learn
Every task writes its own file
Start with the 6,000 files. When Spark writes, each task writes its own file. Two tasks never share one. So 200 tasks write 200 files, even for 50 MB of data.
The nightly job writes with partitionBy("order_date"), which makes one folder per date. Now each task writes one file for every date it holds. The job writes straight after a 200-partition shuffle, so every task holds rows of every date. A month becomes:
200 tasks x 30 dates = 6,000 files
The next picture shows the same thing small: 4 tasks and 5 order statuses.
The same write, before and after grouping
Four write tasks and five status folders: when every task holds every status the write makes twenty files, and after a shuffle by status each folder gets one file.
Four tasks, five statuses. Straight after the read, every task holds orders of every status. Nothing is written yet.
Every task writes its own files. Each of the 4 tasks writes one file into each of the 5 folders: 4 x 5 = 20 files for 80 orders.
Shuffle by status first. Start again, and shuffle the rows by status before the write. Now every status sits in exactly one task.
Write again. Each folder gets one file: 5 files. Task 0 wrote into two folders, and that is fine. What matters is that no status is split across tasks.
Read each step top to bottom: the tasks, then the folders they write into. Files = for every task, the number of folders it holds rows for.
Count the files a write makes
import minispark as ms
orders = ms.read_csv('data/orders.csv', 4)
files = orders.write_files('out/by_status', by='status')
print(len(files), 'files when every task holds every status')
grouped = orders.keyBy(lambda r: r['status']).partitionBy(4).map(lambda kv: kv[1])
files = grouped.write_files('out/by_status', by='status')
print(len(files), 'files after shuffling by status first:')
for f in files:
print(' ', f)
The walkthrough, run for real: 20 files, then 5. write_files replaces the folder, like mode("overwrite"), and writes one JSON Lines file per task per status, named the way Spark names its part files. Look at the file names: returned and shipped both end in part-00000, because they hashed to the same task.
Why thousands of small files hurt
Nothing is wrong with the rows inside those 6,000 files. The cost is in opening them. For every file a reader pays for a listing call, an open and a read of the file's footer, and the table carries metadata for each one. A query over thousands of tiny files spends its time on that overhead, not on data.
This is the small-files problem, and it is why the dashboard went from 8 seconds to 3 minutes.
The fix is the second half of the walkthrough: shuffle by the folder column before you write. Then each date sits in one task and becomes one file. In DataFrame code that is repartition("order_date").
Group by the partition column, then write
Runs on Databricks:
from pyspark.sql import functions as F
(lines
.withColumn("order_date", F.to_date("order_ts"))
.repartition("order_date")
.write.mode("overwrite")
.option("maxRecordsPerFile", 5000000)
.partitionBy("order_date")
.parquet("/Volumes/swiftkart/curated/order_lines"))
files = dbutils.fs.ls("/Volumes/swiftkart/curated/order_lines/order_date=2025-06-01/")
print(len([f for f in files if f.name.endswith(".parquet")]))
1
repartition("order_date") puts each date in one task, so each date folder gets one file (two, if a date passes 5 million rows: that option comes up below). The browser's PySpark cannot partitionBy on write. Module 4 built the same folder layout with DuckDB's PARTITION_BY.
Why keep date folders at all
Order files stored in one folder per day; set a date filter and every file in the other day folders is skipped without being opened.
Folders pay for themselves when queries filter on the column. Set a date filter: Spark skips whole folders, and the plan shows them as PartitionFilters. So partition by a column people filter on that has few values, such as a date. order_id or customer_id would make millions of tiny folders.
Two ways to change the partition count
The fix used repartition. It has a cheaper cousin, and the difference matters.
repartition(n) is a full shuffle. Rows are dealt out like cards, one partition after the other (round robin), into n nearly equal partitions. It can raise or lower the count. repartition(n, "day") sends each row by the hash of the column instead, so all rows of a day meet.
coalesce(n) does not shuffle. Each new partition reads a few neighbouring old ones where they are. It costs nothing, but it can only lower the count, and the sizes stay uneven.
Nora's rule of thumb: coalesce to shrink a little at the end. repartition to grow, to even out sizes, or to group rows by a column.
The same 29 rows, three ways
Three bars on one scale: four uneven partitions after a filter, two uneven ones after coalesce, and two even ones after repartition.
Each bar is the same 29 delivered orders on one scale. coalesce(2) glued neighbours together: free, but 18 rows against 11. repartition(2) moved every row to get 15 and 14.
coalesce against repartition
import minispark as ms
orders = ms.read_csv('data/orders.csv', 4)
delivered = orders.filter(lambda r: r['status'] == 'delivered')
print('after the filter:', delivered.sizes())
print('coalesce(2): ', delivered.coalesce(2).sizes(), '| shuffled', ms.last_job()['shuffled'])
print('repartition(2): ', delivered.repartition(2).sizes(), '| shuffled', ms.last_job()['shuffled'])
The picture, run for real. Watch the last number on each line: coalesce shuffled 0 rows, repartition shuffled all 29.
What each one cost
| Partitions | Rows in each | Rows shuffled | |
|---|---|---|---|
| After the filter | 4 | 9, 9, 7, 4 | 0 |
| coalesce(2) | 2 | 18, 11 | 0 |
| repartition(2) | 2 | 15, 14 | 29 |
coalesce glued partitions 0 and 1, and 2 and 3: free, but uneven. repartition moved every row to get an even split.
The trap: coalesce(1) to "get one nice file". coalesce is narrow, so it joins the stage before it, and a stage runs one task per partition of its last step. coalesce(1) therefore makes that whole stage one task. If the stage also did the joins and aggregations, they all run on one core. repartition(1) keeps the work before it parallel and puts only the final write in one task. Better still, ask whether anyone needs a single file.
When one day is huge, cap the file
Grouping by date can overshoot. A Black Friday date becomes one 20 GB task and one 20 GB file. Two tools cap it.
maxRecordsPerFile, an option on the write. A task starts a new file every n records, so a task with r rows of one date writes ceil(r / n) files.- The
REBALANCEhint (Spark 3.2 and later, needs AQE). Spark shuffles by the column, then AQE splits oversized partitions and merges small ones, so the files come out about the same size.
Take a month in which every date has 2 million rows, capped at 500,000 records per file:
- 2,000,000 / 500,000 = 4 files a date
- 30 dates x 4 = 120 files
Files written for a month of 30 dates
Bars comparing 6,000 files from 200 tasks that each hold every date, 30 files after repartitioning by date, and 120 files when each date of 2 million rows is capped at 500,000 records per file.
One bar per way of writing the same month. The green bars are so short next to the red one that you can hardly see them, which is the point.
How many shuffle partitions?
File counts start with partition counts, so pick the shuffle partition count on purpose. After a shuffle you get spark.sql.shuffle.partitions partitions, 200 unless you change it. Aim for 100 to 200 MB per partition.
A 60 GB shuffle, aiming at 150 MB:
- 60 GB = 60,000 MB
- 60,000 / 150 = 400 partitions
With AQE on (the default), set the number generously and let Spark merge the partitions that turn out small. AQE never raises the count, so a number that is too low stays too low.
Without AQE, too high means thousands of tiny tasks, and tiny files if the result is written. Too low means huge tasks that spill to disk. Lesson 12.10 shows how AQE picks its target size.
The rerun that wiped the month
Now the second mystery. A late file arrived, so someone reran one day: a DataFrame that held only 7 June, written with mode("overwrite") and partitionBy("order_date"). The next morning the table held only 7 June.
An overwrite of a partitioned table has two modes, chosen by spark.sql.sources.partitionOverwriteMode:
static, the default: delete first, then write.dynamic: replace only the partitions that receive rows in this write.
Step through both.
Rerunning 7 June into a table of 1 to 7 June
A table with seven date folders is overwritten by a DataFrame holding only 7 June: in static mode all seven folders are deleted and only 7 June is written back, in dynamic mode six folders stay untouched and 7 June is replaced.
Before the rerun. The table holds seven days. The DataFrame you are about to write holds only 7 June.
Static mode deletes first. Spark deletes every partition that matches the partition spec of the statement. A DataFrame write has no spec, so that is every partition of the table.
Then it writes what it was given. Only 7 June comes back. Six days are gone, and no error was raised.
The same rerun in dynamic mode. Nothing is deleted ahead. Only the partitions that receive rows in this write are replaced, and that is 7 June alone.
Same code, same DataFrame, two very different tables. The only difference is one setting.
Remember: to rerun one day, write with .option("partitionOverwriteMode", "dynamic"). The option on the write wins over the session setting.
Bucketing: shuffle once, when you write
One more idea about layout. If two big tables are joined on the same key every night, you can do the shuffle once, when you write them. This is called bucketing.
df.write.bucketBy(64, "customer_id").sortBy("customer_id").saveAsTable("orders_b") sends each row to one of 64 buckets with the same sum a shuffle uses: hash of the key, mod 64. Each bucket goes to its own files, and the table's entry in the catalog records the bucket count and the column.
Join two tables bucketed on the join key with the same count, and bucket 3 of one already holds the same keys as bucket 3 of the other. The planner adds no Exchange on either side.
The costs: it works only through saveAsTable and spark.table, each write task makes up to one file per bucket, and Delta does not support bucketing at all.
Two bucketed tables join without a shuffle
Runs on your laptop:
spark.conf.set("spark.sql.autoBroadcastJoinThreshold", -1)
spark.conf.set("spark.sql.adaptive.enabled", "false")
orders.write.bucketBy(8, "customer_id").sortBy("customer_id").saveAsTable("orders_b")
customers.write.bucketBy(8, "customer_id").sortBy("customer_id").saveAsTable("customers_b")
spark.table("orders_b").join(spark.table("customers_b"), "customer_id").explain()
== Physical Plan ==
*(3) Project [customer_id#1, order_id#0, status#3, country#24]
+- *(3) SortMergeJoin [customer_id#1], [customer_id#20], Inner
:- *(1) Sort [customer_id#1 ASC NULLS FIRST], false, 0
: +- *(1) Filter isnotnull(customer_id#1)
: +- *(1) ColumnarToRow
: +- FileScan parquet spark_catalog.default.orders_b[order_id#0,customer_id#1,status#3] Batched: true, Bucketed: true, ..., SelectedBucketsCount: 8 out of 8
+- *(2) Sort [customer_id#20 ASC NULLS FIRST], false, 0
+- *(2) Filter isnotnull(customer_id#20)
+- *(2) ColumnarToRow
+- FileScan parquet spark_catalog.default.customers_b[customer_id#20,country#24] Batched: true, Bucketed: true, ..., SelectedBucketsCount: 8 out of 8
Real Spark 3.5 in local mode (pip install pyspark), shortened. Look for the word Exchange: it is nowhere. Bucket 3 of one table meets bucket 3 of the other in the same task. The Sort stays because each bucket holds several files.
On Databricks, Delta tables fight small files for you: optimized writes shuffle data into fewer, larger files as they are written, auto compaction merges small files after a write, and OPTIMIZE compacts on demand. Liquid clustering takes the place of both Hive-style partitioning on high-cardinality columns and bucketing. For reruns, Delta Lake supports dynamic mode from 2.0 and offers replaceWhere for an explicit range such as one date; the two cannot be combined on one write. You still choose sensible partitions. Module 13 shows the commands.
Numbers to remember
| Setting or name | Default or value | What it is |
|---|---|---|
| spark.sql.shuffle.partitions | 200 | Partitions after a shuffle. Aim at 100 to 200 MB each |
| spark.sql.adaptive.coalescePartitions.initialPartitionNum | optional | A second place to set the starting number of shuffle partitions when AQE is on |
| spark.sql.execution.sortBeforeRepartition | true | repartition(n) first sorts each input partition locally, so a retried task deals the same rows to the same places |
| repartitionByRange(n, "day") | a third kind of repartition | Samples the column and cuts it into sorted ranges |
| spark.sql.files.maxRecordsPerFile | 0 (no limit) | Or .option("maxRecordsPerFile", n) on one write |
| REBALANCE hint | Spark 3.2 and later, needs AQE | SQL: /+ REBALANCE(orderdate) /. Splits and merges towards the advisory size, 64 MB |
| spark.sql.sources.partitionOverwriteMode | static | dynamic replaces only the partitions that receive data |
| A bucket file | part-00003-<job id00017.c000.snappy.parquet | Holds bucket 17. The bucket id is the Murmur3 hash of the key, mod the bucket count. Hive's bucketing uses another hash |
| spark.sql.bucketing.coalesceBucketsInJoin.enabled | false | Lets two tables with different bucket counts join without a shuffle |
| Files from a bucketed write | up to tasks x buckets | 200 tasks x 64 buckets = 12,800 files |
What changed at SwiftKart
The nightly write gets three small changes.
It calls repartition("order_date") before the write, so a day is one file, not 200. It sets maxRecordsPerFile for the busy days. And it writes with partitionOverwriteMode set to dynamic, so rerunning 7 June replaces 7 June and nothing else.
You rebuild the six lost days from the raw files and rewrite the old month once. Tess's dashboard is quick again, and Nora adds a line to the runbook: "Count the files after every write."
One cost is left. The nightly report cleans the orders with three joins, then writes five summaries from the result, and the three joins run five times. Lesson 12.6 is about keeping a result: caching and persistence.
In one line
Every task writes one file for each folder it holds rows for, so group rows by the folder column before a write, cap big files, and overwrite in dynamic mode so a rerun replaces only its own day.
Interview corner
What is the difference between repartition and coalesce?
repartition(n) is a full shuffle: round-robin (after a local sort, so retries are deterministic) or by hash of the given columns, producing n even partitions; it can raise or lower the count. coalesce(n) is narrow: each output partition reads several neighbouring input partitions, so there is no shuffle, but it can only lower the count, leaves sizes uneven, and lowers the parallelism of the whole stage it belongs to.
What is the small-files problem, and how do you fix it?
Thousands of tiny files make every read pay listing, open and footer costs per file, so queries slow down even though the data is small. It usually comes from many tasks each writing a file per partition value: 200 tasks x 30 dates = 6,000 files. Fix it by repartitioning by the partition column before writing, capping big partitions with maxRecordsPerFile or the REBALANCE hint, and compacting (Delta OPTIMIZE, optimized writes, auto compaction).
How do you rerun one day of a partitioned table without losing the others?
With the default static partitionOverwriteMode, an overwrite with partitionBy deletes every existing partition first, so a one-day DataFrame leaves a one-day table. Set partitionOverwriteMode to dynamic, per write as an option or for the session, so only partitions present in the new data are replaced; on Delta, use replaceWhere with the date range. Then check the partition count and row totals after the write.
When does bucketing remove a shuffle, and why is it rare today?
When two catalog tables are bucketed on the join or grouping key with the same bucket count, their scans are already hash-partitioned the way the operator needs, so no Exchange is added. It needs saveAsTable, matching counts (or coalesceBucketsInJoin), produces up to one file per bucket per task, is incompatible with Hive bucketing, and is not supported by Delta, where liquid clustering does the job.