≈ The Lake

Part 8 · Data layout · Chapter 25

Partitioning

Hive-style partition directories, what Delta and Iceberg record instead, how a partitioned Spark write turns into files, static and dynamic partition pruning, choosing a partition column, and partitioning's effect on concurrent writes.

complete ~30 min

After this chapter you should be able to:
  • Explain why the directory path is not the source of truth in Delta or Iceberg.
  • Predict how many files a partitioned write produces, and fix the small-files problem at write time.
  • Say which filters prune partitions, and how dynamic partition pruning extends that to joins.
  • Choose (or reject) a partition column using cardinality, partition size and query patterns.

Partitioning is the oldest skipping technique in this book and the coarsest. Rows with the same value of the partition columns go into the same files, and a query that filters on those columns never touches the other files. Part 3 skipped data inside a file. This part, chapters 25 to 28, is about which rows end up in which file: partitioning, then Z-order and data skipping, then liquid clustering, then compaction.

The simulator in src/sim/layout/partition.ts ports Spark’s directory naming, its partitioned-write algorithm and its partition pruning. The tests pin each of them.

Hive-style directories

Hive stored a table as a directory and a partition as a subdirectory named column=value. Spark kept the convention for file-based tables: events/event_date=2026-03-01/country=DE/part-00007-….parquet. ExternalCatalogUtils.getPartitionPathString builds each segment from the escaped column name, =, and the escaped value.[Spark ExternalCatalogUtils] Two details come from Hive and stay surprising:

  • Escaping. escapePathName replaces control characters and " # % ' * / : = ? \ { [ ] ^ and DEL with %XX. That code is “mainly copied from Hive”. A value 12:30/A becomes 12%3A30%2FA, so the slash cannot create a directory. Spaces and non-ASCII characters are left alone, except that spaces and < > | are also escaped on Windows.[Spark escapePathName]
  • Null. Both null and the empty string become __HIVE_DEFAULT_PARTITION__, Hive’s default partition name. A table that knows only its directories cannot tell them apart.

With nothing but directories, the directory tree is the table. A reader lists the table directory recursively to find the partitions and files, and it parses the types of the partition values back out of strings. Chapter 3 covered what a recursive listing costs on S3, and why a list can miss a file that a concurrent writer is still adding.

Quiz Check: directoriesAnswers are scheduled for spaced review on the Review page.

Q1. Spark writes rows whose partition column country is NULL. Which directory do they go to?

How sure are you?

Q2. A partition value is 12:30/A. What directory segment does Spark write for column slot?

How sure are you?

What the table format records

Delta and Iceberg keep the convention but not the dependence on it. Delta’s spec says data files can live “in any non-hidden subdirectory”, and the partition directory format “is only used to follow existing conventions and is not required by the protocol”.[PROTOCOL.md: data files] What counts is the log:

  • metaData.partitionColumns lists the partition columns.
  • Each add action carries partitionValues, “a map from partition column to value for this logical file”.[PROTOCOL.md: add]
  • Values are strings in a fixed format: dates as {year}-{month}-{day}, numbers as their string form. Timestamps are written as local time, or, as the spec recommends, as ISO 8601 in UTC. A null is a JSON null, and “An empty string for any type translates to a null partition value”.[PROTOCOL.md: partition value serialization]

Partition columns are normally not stored in the Parquet files at all. A reader adds them to each row from partitionValues. Only the materializePartitionColumns writer feature and the IcebergCompat features require them in the files, and even then, readers “should continue to read partition values from AddFile metadata”. Delta Spark still writes Hive-style directories. Its DelayedCommitProtocol.parsePartitions even recovers partitionValues by parsing the directory string Spark generated, normalizing timestamps to UTC. [Delta DelayedCommitProtocol] Under column mapping, the map’s keys are physical names, and Delta Spark stops writing partition directories at all: TransactionalWrite.getCommitter says “We force the use of random prefixes in column mapping modes”, so files go under short random directory names.[Delta TransactionalWrite]

Iceberg goes further. Each manifest entry holds the data file’s partition tuple, computed by the spec’s transforms, and the file’s location is arbitrary. Chapter 18 covers that, including filters on a source column that prune through a transform.

Quiz Check: the log decidesAnswers are scheduled for spaced review on the Review page.

Q1. A Delta data file sits under country=US/ but its AddFile has partitionValues: {"country": "CA"}. What does a Delta reader return for that file's rows?

How sure are you?

How a partitioned write makes files

Partitioning sets a lower bound on the number of files: a file holds one partition. How far above that bound a write lands depends on how rows reach the write tasks.

FileFormatWriter requires each task’s rows to be sorted by the dynamic partition columns (“We should first sort by dynamic partition columns, then bucket id, and finally sorting columns”). It adds a sort when the plan does not already provide one.[Spark FileFormatWriter] DynamicPartitionDataSingleWriter then streams the sorted rows. It opens a new file whenever the partition values change, and starts a new file in the same partition when maxRecordsPerFile is reached:[Spark DynamicPartitionDataSingleWriter]

// FileFormatDataWriter.scala (trimmed)
if (currentPartitionValues != nextPartitionValues || currentBucketId != nextBucketId) {
  currentPartitionValues = Some(nextPartitionValues.get.copy())
  fileCounter = 0
  renewCurrentWriter(currentPartitionValues, currentBucketId, closeCurrentWriter = true)
} else if (description.maxRecordsPerFile > 0 && recordsInFile >= description.maxRecordsPerFile) {
  renewCurrentWriterIfTooManyRecords(currentPartitionValues, currentBucketId)
}
writeRecord(record)
Two tasks can write to the same partition
Task 0
  1. GB rows → GB file 0 The writer opens a file for the first key.
  2. US rows → US file 0 A new partition key opens a new writer.
Task 1
  1. GB rows → GB file 1 This task writes its own GB output.
  2. US rows → US file 1 This task writes its own US output.
Two partition values produce four files in this example. When the write distributes each partition value to one task, it can produce fewer files.[Spark writer]

So each task writes one file for each partition value it holds. Rows of 50 countries spread across 200 tasks give about 10,000 files, each holding a fiftieth of a two-hundredth of the data. The simulator reproduces this:

  • Partition by country, rows in arrival order. 36,000 events over 90 days in 20 skewed countries, written by 32 tasks, produce 672 files for 21 partitions (20 countries plus null).
  • Partition by event_date. The same rows produce 120 files for 90 dates. Rows arrive in time order, so each task’s slice covers only three or four days.
  • Repartition by country first. df.repartition($"country") hash-partitions the rows by the partition column, so each country lands in exactly one task. The write then produces 21 files, one per partition. The cost is one shuffle, and skew: the largest country’s task does the most work and writes the largest file.

spark.sql.files.maxRecordsPerFile (default 0, no limit) can only split files.[Spark SQLConf] Nothing in the write path merges small ones. Merging is compaction’s job (chapter 28). Delta’s optimized writes (delta.autoOptimize.optimizeWrite, off by default) do the repartitioning for you. DeltaOptimizedWriterExec shuffles the rows “hash partitioned on the table partition columns”, then bin-packs the shuffle blocks so that each write task gets about one target file’s worth.[Delta DeltaOptimizedWriterExec]

Quiz Check: writesAnswers are scheduled for spaced review on the Review page.

Q1. 200 write tasks each hold rows for all 50 countries, and the table is partitioned by country. Roughly how many files does one write produce?

How sure are you?

Q2. What does spark.sql.files.maxRecordsPerFile do in a partitioned write?

How sure are you?

Partition pruning

Spark’s optimizer rule PruneFileSourcePartitions works on catalog tables. It separates the deterministic filters into partition filters and data filters, and replaces the file index with one restricted to the matching partitions. It keeps the filters in the plan, “so that they are visible in physical planning”.[Spark PruneFileSourcePartitions] For path-based tables, PartitioningAwareFileIndex.prunePartitions does the evaluation:[Spark prunePartitions]

val partitionPruningPredicates = predicates.filter {
  _.references.map(_.name).toSet.subsetOf(partitionColumnNames)
}
val predicate = partitionPruningPredicates.reduce(expressions.And)
val selected = partitions.filter { case PartitionPath(values, _) => boundPredicate.eval(values) }

The test is whether all references are partition columns, not whether the filter has a particular shape. month(event_date) = 3 prunes a table partitioned by event_date, because it is evaluated on each partition’s value. event_ts >= '2026-03-01' does not, even if the writer derived event_date from event_ts: Spark does not know the relationship. Delta’s generated columns supply it. If event_date is declared GENERATED ALWAYS AS (CAST(event_ts AS DATE)), Delta’s GeneratedColumn.generatePartitionFilters adds event_date >= '2026-03-01' during scan preparation. It recognizes a fixed list of expressions: casts to date, year, month, dayofmonth, date_format, substring, date_trunc and trunc.[Delta GeneratedColumn] Iceberg’s partition transforms do the same thing in the spec itself.

Delta prunes against the log, not directories. rewritePartitionFilters replaces each partition column with CAST(partitionValues['<physical name>'] AS <type>) and filters the snapshot’s AddFile rows.[Delta rewritePartitionFilters] A comparison with NULL is never true, so the __HIVE_DEFAULT_PARTITION__ partition drops out of every comparison filter. You reach it only with IS NULL.

The data filters go on to the next layers: Delta’s per-file min/max statistics (chapter 26) and then the Parquet statistics of chapter 8.

Quiz Check: pruningAnswers are scheduled for spaced review on the Review page.

Q1. A table is partitioned by event_date (a date). Which filters prune partitions in Spark's file index? (Select all.) (select all that apply)

How sure are you?

Q2. How does Delta evaluate a partition filter like country = 'DE' against the log?

How sure are you?

Dynamic partition pruning

Static pruning needs a literal. In a star schema, the selective filter is usually on a dimension table, and the fact table gets only a join key:

SELECT ... FROM sales s JOIN dates d ON s.event_date = d.date WHERE d.is_holiday

Spark’s PartitionPruning rule handles this. When the join key is a partition column of a filterable scan, the join type allows it, and the other side has a selective predicate, it inserts a DynamicPruning predicate on the partitioned side. The predicate is an IN over the keys that survive the other side’s filter.[Spark PartitionPruning] At planning time:

  • If the join is a broadcast hash join, the subquery reuses the broadcast results.
  • Otherwise the subquery is kept only if its estimated benefit outweighs running the other side twice.
  • If neither holds, the predicate is dropped.

Two settings govern this. spark.sql.optimizer.dynamicPartitionPruning.enabled defaults to true. reuseBroadcastOnly also defaults to true, which keeps only the broadcast-reuse case.[Spark SQLConf] In the physical plan this appears as PartitionFilters: [..., dynamicpruningexpression(...)] on the fact scan.

Quiz Check: dynamic pruningAnswers are scheduled for spaced review on the Review page.

Q1. SELECT ... FROM sales s JOIN dates d ON s.event_date = d.date WHERE d.is_holiday. sales is partitioned by event_date. What does dynamic partition pruning add?

How sure are you?

Choosing a partition column

The write model and the pruning rule together give the criteria:

  1. Queries filter on it, by equality or range, as a literal or through a dimension join. Otherwise every query reads every partition, and partitioning only adds files.
  2. Low cardinality relative to data size. Every partition is at least one file per write. For full-size files, each partition needs at least one target file’s worth of data, and partitions grow only as fast as new data arrives in them. A date column with gigabytes a day qualifies. user_id never does: in the lab it gives 25,608 partitions of a few MB each, and no query on another column prunes anything.
  3. Stable. Changing the partition columns of a Delta table means rewriting it. Iceberg can evolve the partition spec without a rewrite (chapter 18).
  4. Not skewed into uselessness. A column where one value holds 80% of the rows prunes well only for the other 20%.

For skipping on high-cardinality columns, or on several columns at once, the tools are file-level statistics with clustering: Z-order (chapter 26) and liquid clustering (chapter 27). They keep files at their target size whatever the cardinality.

Quiz Check: choosingAnswers are scheduled for spaced review on the Review page.

Q1. Which make a column a poor partition column? (Select all.) (select all that apply)

How sure are you?

Partitioning and concurrency

Partitions are also the unit of conflict detection in Delta’s open-source checker. When a transaction loses the race, the concurrent-append check takes the files the winners added and keeps those whose partitionValues match the loser’s read predicates. Only partition columns take part in that match.[Delta ConflictChecker] Two UPDATEs whose WHERE clauses name different dates therefore both commit. On an unpartitioned table, the read predicate cannot be narrowed, and any concurrent non-blind add conflicts. Chapter 10 walks through the checks, including why a MERGE needs a literal partition filter on the target to benefit. Iceberg’s equivalent is the conflict detection filter in its validation step (chapter 17).

This gives some tables a partition column for concurrency alone, for example by date for a job that rewrites one day at a time while ingestion appends to today.

Quiz Check: concurrencyAnswers are scheduled for spaced review on the Review page.

Q1. Two Delta UPDATEs run at the same time on a table partitioned by event_date, one with WHERE event_date = '2026-03-01', the other on '2026-03-02'. What happens in the open-source conflict checker?

How sure are you?

Try it

The lab writes 36,000 simulated events with the writer algorithm above. The events cover 90 days in arrival order, with Zipf-skewed countries, a few null countries and 50,000 users. The table size you pick scales the bytes each simulated row stands for. Things to try:

  • Partition by event_date, country at 100 GB with rows in arrival order, then repartition by the partition columns. Watch the file count and the histogram.
  • The same layout at 1 TB: the files get bigger, and the partition count does not change.
  • Partition by user_id, then run any query.
  • The March, via month() query, with and without event_date among the partition columns.
1,888partitions
2,423files
22.2 MBmedian file
1,564files under 32 MB
< 1 MB0
1–8 MB302
8–32 MB1,262
32–128 MB698
128–512 MB161
512 MB–2 GB0
> 2 GB0

event_date=2026-01-01/country=__HIVE_DEFAULT_PARTITION__/part-00000-000.parquetevent_date=2026-01-01/country=AR/part-00000-001.parquetevent_date=2026-01-01/country=AU/part-00000-002.parquet… and 2,420 more

WHERE event_date = '2026-02-14' AND country = 'DE'
1 / 1,888partitions kept
1files to open
63.9 MBto scan (0.1%)

Partition filters: event_date = '2026-02-14', country = 'DE'. Data filters, left for file statistics and Parquet: none.

Summary

  • Hive-style directories are col=value segments, escaped with Hive’s rules. Null and empty strings both become __HIVE_DEFAULT_PARTITION__.
  • In Delta, partitionValues in each AddFile is the source of truth. The directory layout is a convention, and partition columns are normally not in the data files. Iceberg stores a partition tuple per manifest entry.
  • Each write task writes one file per partition value it holds, so files ≈ tasks × partitions unless the data is repartitioned by the partition columns first. maxRecordsPerFile only splits files.
  • Spark prunes with every filter whose references are all partition columns. Delta evaluates the filters against partitionValues in the log. Generated columns (Delta) and transforms (Iceberg) turn filters on source columns into partition filters.
  • Dynamic partition pruning builds a partition filter at runtime from the other side of a join, by default only when it can reuse a broadcast.
  • Partition only on low-cardinality columns that queries filter on, with enough data per partition for full-size files. Partitions also narrow Delta’s conflict detection.

Primary sources

Review this chapter

This chapter has 10 quiz questions.

Review this chapter's cards → Review all due cards