Partitions and file layout
Part of the free LogicWiz Data Engineering course, Module 4: Storage and file formats. The SQL and Python run in the app, on real Postgres and real Python in the browser.
It is 9:20 on Thursday. Tess's dashboard asks one thing, "what happened yesterday?", and the cloud bill shows every run scanning three years of events. Nora finds a second problem in the same folder: a streaming job has been adding a tiny file every few seconds, the count has passed two million, and a query now spends longer listing files than reading them.
You'll learn to
- Split a table into one folder per day with DuckDB
- Explain how a filter skips folders, and when it cannot
- Count what a file layout costs in requests and tasks
- Choose a partition key and a file size with arithmetic
Learn
One folder for three years
Nora opens the events table in the cloud console. It is one folder, holding every file from the last three years. A question about yesterday has no way to find yesterday. It has to open everything.
The fix is old and plain: give each day its own folder. orders/order_date=2025-06-01/, orders/order_date=2025-06-02/, and so on, each holding ordinary Parquet files with that day's rows. Splitting a table into folders by the value of a column is called partitioning, and the column is the partition key.
The column=value folder name is the Hive-style convention, after the tool that made it popular. Almost every engine reads it: Spark, DuckDB, Athena, Trino, BigQuery and Snowflake external tables.
Try it on SwiftKart's 80 orders. First, a guess.
Write the orders, one folder per day
import duckdb, os
os.makedirs("lake", exist_ok=True)
duckdb.sql("""
COPY (SELECT *, CAST(order_ts AS DATE) AS order_date FROM 'data/orders.csv')
TO 'lake/orders' (FORMAT PARQUET, PARTITION_BY (order_date))
""")
folders = sorted(os.listdir("lake/orders"))
print(len(folders), "partitions")
for folder in folders[:3]:
print(folder, os.listdir(f"lake/orders/{folder}"))
PARTITION_BY (order_date) writes one folder for each different value. DuckDB needs the parent folder (lake) to exist. By default it also refuses to write into a folder that is not empty, which stops two runs from mixing. DuckDB 1.0 keeps order_date inside each file as well; Spark does not.
The folder name does the filtering
Now ask for one day: WHERE order_date = DATE '2025-06-03'.
Before it lists or opens a single file, the engine compares the filter with the folder names. Thirteen names cannot match, so thirteen folders are dropped. This is called partition pruning. It is the cheapest speed-up in data engineering: a question about one day out of three years touches about 0.1% of the data.
There is one catch. Pruning works only when the filter is on the partition column itself. Write the same day as CAST(order_ts AS DATE) and you get the same rows, but the engine cannot tell from order_ts which folders to skip. A filter on another column, such as status = 'returned', cannot use the names either.
The same day, asked two ways
A folder tree with one folder per order date. A filter on order_date keeps one folder and skips thirteen by name; the same day written as a cast of order_ts reads all fourteen folders.
The table on disk. Fourteen days of orders, fourteen folders, one small file in each.
Filter on the partition column.
WHERE order_date = DATE '2025-06-03'. The engine reads the folder names, keeps one and drops thirteen without opening them.The same day, asked through another column.
WHERE CAST(order_ts AS DATE) = DATE '2025-06-03'returns the same six rows. But the names are aboutorder_date, notorder_ts, so the engine opens all fourteen folders to find them.
Read the right-hand column of each step: it says what happened to that folder. Same answer in steps 2 and 3, fourteen times the reading in step 3.
Files arranged in one folder per day; setting a date filter greys out every folder the reader can skip without opening a single file in it.
Set a one-day filter, then a three-day range. The greyed folders are never opened: their names alone rule them out.
Prune with a filter, or read one folder
import duckdb, os
os.makedirs("lake", exist_ok=True)
duckdb.sql("""
COPY (SELECT *, CAST(order_ts AS DATE) AS order_date FROM 'data/orders.csv')
TO 'lake/orders' (FORMAT PARQUET, PARTITION_BY (order_date))
""")
q = """
SELECT COUNT(*)
FROM read_parquet('lake/orders/*/*.parquet', hive_partitioning = true)
WHERE order_date = DATE '2025-06-03'
"""
print(duckdb.sql(q).fetchone()[0], "orders on 3 June, through the filter")
print(duckdb.sql("EXPLAIN " + q).fetchall()[0][1])
one_day = duckdb.sql("SELECT COUNT(*) FROM 'lake/orders/order_date=2025-06-03/*.parquet'").fetchone()[0]
print(one_day, "orders on 3 June, reading one folder")
In the plan, the scan box shows File Filters: (order_date = ...): DuckDB applied the filter to the file paths. Pointing the reader straight at one folder is the same pruning done by hand, and it is what a daily job usually does.
Remember: pruning reads folder names. Filter on the partition column itself, or every folder gets opened. Inside the folders that are left, row-group statistics (Lesson 4.2) can skip more: the two stack.
Every file is a request
That fixes the three-year scan. The two million files are a different problem.
SwiftKart's lake sits on object storage: Amazon S3, Azure's ADLS or Google's GCS. There, a folder is only a shared start of file names, and every action is a web request. Listing files is a request that returns at most 1,000 names. Reading one Parquet file takes at least two more: one for the footer, one for the column chunks. Each request waits roughly 100 to 200 ms for its first byte.
So the clock and the bill both count files, not bytes. A layout that is cheap to read has few, large files.
Reading one folder on object storage
A query engine sends list requests to object storage and gets file names back a thousand at a time, then for every file sends one request for the footer and one for the column chunks.
Read it top to bottom: each solid arrow is one request, each dashed arrow its answer. The two GETs at the bottom repeat for every file.
The small-files arithmetic: 1 TB of orders
| 128 MB files | 1 MB files | |
|---|---|---|
| Files | 8,192 | 1,048,576 |
| LIST requests (1,000 keys each) | 9 | 1,049 |
| GETs for one full scan (2 a file) | 16,384 | 2,097,152 |
| GET cost per full scan ($0.0004 per 1,000) | $0.007 | $0.84 |
| Spark read tasks (128 MB, +4 MB per file) | 8,192 | about 40,000 |
| Footers to parse | 8,192 | 1,048,576 |
Spark packs files into read tasks of up to 128 MB (spark.sql.files.maxPartitionBytes) and charges every file an extra 4 MB for opening it (spark.sql.files.openCostInBytes). So each 1 MB file counts as 5 MB, and 26 of them fill a task. Each footer read is a request with its own wait; a million of them is minutes of waiting before any data arrives.
Where two million files came from
Small files have three usual sources.
- A streaming job that writes every few seconds. That is SwiftKart's case.
- A partition key that is too fine, such as the hour on a small table.
- Many writers at once. A Spark job runs as parallel tasks, and each task opens its own file in every folder it has rows for. With 200 tasks and 365 date folders, one run can leave 200 x 365 = 73,000 files.
The third one surprises people. Step through it with small numbers: 3 tasks and 3 days.
Three tasks write three days
Three Spark tasks write into three date folders. With mixed rows every task writes a file into every folder, nine files; after shuffling by the partition key each task writes into one folder, three files.
Rows arrive mixed. Each task holds rows from all three days, so each task writes a file into every folder. 3 tasks x 3 folders = 9 small files.
Shuffle by the partition key first.
repartition("order_date")sends all of one day's rows to one task. Now each task writes into one folder: 3 files, each three times larger.
Count the arrows: each arrow is one file written. Nine in the first step, three in the second.
Fewer, bigger files
The cures all push the same way.
- Shuffle by the partition key before writing, as in the picture, so each task owns a few folders.
- Compact: rewrite many small files into a few large ones. Delta's command is
OPTIMIZE; Iceberg's isrewrite_data_files. - Write streams less often, so each write carries more rows.
What size should a file be? Between 128 MB and 1 GB is the usual range, and Iceberg aims at 512 MB. Much bigger than that, and every rewrite gets heavy and skipping gets coarse.
The next example shows the other extreme on 80 orders: one file, one file per day, one file per order.
One file, 14 files, 80 files
import duckdb, os
def folder_stats(path):
files = [os.path.join(root, f) for root, _, names in os.walk(path) for f in names]
return len(files), sum(os.path.getsize(f) for f in files)
src = "SELECT *, CAST(order_ts AS DATE) AS order_date FROM 'data/orders.csv'"
duckdb.sql(f"COPY ({src}) TO 'one.parquet' (FORMAT PARQUET)")
duckdb.sql(f"COPY ({src}) TO 'by_day' (FORMAT PARQUET, PARTITION_BY (order_date))")
duckdb.sql(f"COPY ({src}) TO 'by_order' (FORMAT PARQUET, PARTITION_BY (order_id))")
print(f"{'one file':10} 1 file, {os.path.getsize('one.parquet')} bytes")
for path in ["by_day", "by_order"]:
n, size = folder_stats(path)
print(f"{path:10} {n} files, {size} bytes")
The same 80 orders take over 5 times the space in 14 day folders, and about 25 times in 80 order folders, because every file repeats its own footer, schema and page headers. On a real lake the file count hurts more than the bytes: every file is a request.
Pick the key with arithmetic
A good partition key is a column most queries filter on, with a moderate number of values that grows slowly. For orders and events that is almost always the date, sometimes date plus region.
Before you choose, work out how much one folder will hold.
- SwiftKart's orders grow 50 GB a day. A daily folder holds 50 GB: 400 files of 128 MB. Healthy.
- Hourly folders would hold about 2 GB each. Still fine.
- Folders by
customer_idwould be millions of folders of a few KB each. No. - A table that grows 50 MB a day should not be split by hour: that is 24 files of 2 MB a day. Arguably it should not be partitioned at all.
Candidate keys for SwiftKart orders
| Key | Folders after 3 years | Verdict |
|---|---|---|
| orderdate | about 1,100 | good: nearly every report filters on dates |
| orderdate then country | about 1,100 x 25 | only if most queries filter on both; watch for small files |
| status | 5 | poor: few queries filter on it alone, and folders are very uneven |
| customerid | millions | bad: tiny files everywhere |
| orderts to the second | one per order | bad: one file per row |
Databricks' rule of thumb: do not partition a table under about 1 TB, and aim for at least 1 GB per partition.
Let the table hide the folders
Hive-style folders have the weakness you met above: people must remember to filter on order_date and not on order_ts. The layout leaks into every query, and changing it means rewriting the table and the queries.
Apache Iceberg (a table format, met in Lesson 4.4) keeps the partitioning in the table's own metadata, as a transform of a real column: day(order_ts), bucket(16, customer_id). Writers work out the partition value. Readers filter on order_ts as usual, and Iceberg turns that into a filter on the day partitions. This is called hidden partitioning.
The scheme can also change for new data only, while old files keep theirs and are still pruned correctly. That is partition evolution.
Hidden partitioning on an Iceberg table (Spark SQL)
Runs on Databricks:
CREATE TABLE lake.swiftkart.orders (
order_id BIGINT, customer_id BIGINT, order_ts TIMESTAMP, status STRING, amount DECIMAL(12, 2))
USING iceberg
PARTITIONED BY (day(order_ts));
-- the filter is on order_ts; Iceberg prunes day partitions from it
SELECT SUM(amount) FROM lake.swiftkart.orders
WHERE order_ts >= TIMESTAMP '2025-06-03' AND order_ts < TIMESTAMP '2025-06-04';
-- evolve: new data is also bucketed by customer; old files are not rewritten
ALTER TABLE lake.swiftkart.orders ADD PARTITION FIELD bucket(16, customer_id);
Look at the WHERE: it filters on order_ts, and Iceberg still prunes by day. This runs on Spark with the Iceberg runtime and a catalog named lake (Databricks, EMR or a laptop). The browser's engines have no Iceberg, so it is shown, not run.
You will see dt=2025-06-01/ and year=2025/month=06/day=01/ folders all over S3 and ADLS. Spark writes them with df.write.partitionBy("order_date"), and Athena and Hive register them as table partitions. Newer systems hide the layout. Delta gets part of the way with generated columns (order_date DATE GENERATED ALWAYS AS (CAST(order_ts AS DATE))), from which it works out partition filters, and Databricks now recommends liquid clustering over partitioning for new tables. Snowflake's micro-partitions and BigQuery's partitioned and clustered tables also decide file boundaries for you. The idea is the same everywhere: skip what a filter cannot match.
The trap: too many partitions, and the wrong filter. Partitioning by a column with many values, or by hour on a small table, multiplies files and makes queries slower, not faster. And pruning needs the partition column itself in the filter: on a Hive-style table WHERE order_date = ... prunes, while WHERE CAST(order_ts AS DATE) = ... returns the same rows and reads every folder. You can spot it in the plan: the scan has no partition filter.
Numbers to remember
| What | Number | Good to know |
|---|---|---|
| One S3 list request | at most 1,000 keys | ListObjectsV2 |
| S3 request prices | LIST $0.005 per 1,000; GET $0.0004 per 1,000 | S3 Standard in us-east-1; LIST is billed like PUT |
| First byte of a request | roughly 100 to 200 ms | AWS's own figure |
| S3 request rate | at least 3,500 writes a second per prefix | A burst on a new prefix gets 503 Slow Down while S3 scales |
| Spark read task | 128 MB, plus 4 MB per file | spark.sql.files.maxPartitionBytes, spark.sql.files.openCostInBytes |
| Target file size | 128 MB to 1 GB | Iceberg aims at 512 MB (write.target-file-size-bytes); Parquet's docs recommend 512 MB to 1 GB row groups |
| Partition column in Spark's files | not stored | Every row in a folder has the same value, so the reader takes it from the path as text and casts it (spark.sql.sources.partitionColumnTypeInference.enabled, on by default) |
| A null partition value | folder HIVEDEFAULTPARTITION | |
| Iceberg transforms | year, month, day, hour, bucket(16, customerid), truncate(10, sku) | The values live in manifests (Lesson 4.6), not in folder names |
What changed at SwiftKart
The events table is now one folder per day. Tess's dashboard filters on the partition column, so the query that scanned three years opens yesterday's folder and nothing else. The streaming job writes less often, and a nightly compaction rewrites its small files into large ones, so listing is quick again.
A folder of files is still only a folder of files. Nothing stops two jobs from writing into it at once, or a reader from seeing half a write. Lesson 4.4 looks at what teams build on top: the data lake, the warehouse, and the lakehouse that tries to be both.
In one line
Give each day its own folder so a filter on that column skips the rest by name, and keep files few and large (128 MB to 1 GB), because on object storage every file costs requests.
Interview corner
What is partition pruning, and when does it fail?
When a table is partitioned into folders by a column, a filter on that column lets the planner skip every folder whose value cannot match, using only the folder names, before listing or opening files. It fails when the filter is on a different column or on an expression of another column, such as CAST(order_ts AS DATE) on a table partitioned by order_date, because the engine cannot map it to folders. Iceberg's hidden partitioning and Delta's generated columns exist to close that gap.
Explain the small-files problem with numbers.
1 TB in 128 MB files is 8,192 files; in 1 MB files it is over a million. Listing a million keys takes about 1,050 LIST requests in sequence, reading them needs at least 2 GETs each, so over 2 million requests per full scan, and Spark charges every file 4 MB of open cost, packing 26 one-megabyte files per task, so roughly 40,000 tasks instead of 8,192. Each footer parse and each request adds latency. The fix is compaction to 128 MB to 1 GB files, shuffling by the partition key before writing, and fewer, larger streaming writes.
How do you choose a partition key and a granularity?
I pick the column most queries filter on, usually a date, then do the arithmetic: bytes per day divided by the target file size gives files per partition, and days retained gives the folder count. I want each partition to hold at least around 1 GB, so a 50 MB-a-day table is not partitioned by hour and may not be partitioned at all. High-cardinality keys like ids are out; clustering, Z-order or bucketing handle those inside files.
What is hidden partitioning in Iceberg?
The partition spec is stored in table metadata as transforms of source columns, such as day(order_ts) or bucket(16, customer_id). Writers compute the partition values and record them in manifests, and readers filter on the source column, which Iceberg converts to partition filters, so users never write the partition column themselves. The spec can evolve: new data uses the new spec while old files keep theirs, with no rewrite.