Sub topic 8
Delta file layout and OPTIMIZE
This chapter covers how a Delta table is stored as files, why many small files slow queries down, and how OPTIMIZE fixes that. It assumes you know basic SQL, can run commands in a Databricks notebook or SQL editor, and know what a Spark task is. Later chapters cover data skipping and clustering in more detail. Here the focus is on the file layout those features build on.
How a Delta table is stored
A Delta table is a directory in cloud storage. It holds two kinds of content:
- Data files, usually Parquet. Parquet is a columnar file format, so each file stores values column by column.
- A transaction log in the
_delta_logfolder. The log is a series of JSON commit files, with periodic checkpoints. It records which data files belong to the current version of the table.
A query does not list the directory to find its data. It reads the log, gets the list of active files, and then plans its scan over those files. Files that were removed by an update or delete can still exist in storage, but the log no longer lists them as part of the current version.
Delta never edits a data file in place. An UPDATE, DELETE or MERGE writes new files and marks the old ones as removed in the log. An INSERT or append writes new files. This design gives you atomic commits and time travel. It also means that the number and size of files change with every write.
Why file count and size matter
Spark reads a table by splitting the list of files into tasks. Every file has a fixed cost: opening it, reading its footer metadata, and scheduling work for it. If the table has thousands of tiny files, this cost can exceed the cost of reading the data.
| Layout | Typical effect |
|---|---|
| Very many small files (KB to a few MB each) | Slow listing and planning, many short tasks, scheduler overhead, poor compression, little benefit from vectorized reads |
| Moderately sized files (hundreds of MB to about 1 GB) | Fewer tasks, long sequential reads, good compression, good fit for Photon's batch processing |
| A few very large files | Less parallelism, because one file can limit how many tasks can run |
Photon and other vectorized engines process data in batches of column values. Small files produce small batches and frequent restarts, so the engine spends more time on setup than on computation. A good layout is a precondition for getting value from Photon.
How small files accumulate
Small files are a normal result of common write patterns:
- Streaming jobs that commit every few seconds, each time writing a small file per partition.
- Frequent small batch appends, for example one load every few minutes.
MERGEorUPDATEoperations that touch a few rows in many files and rewrite them.- Writes with a high shuffle partition count, where each task writes its own small file.
- Over-partitioned tables, where each partition value gets only a little data per write.
Compacting files with OPTIMIZE
OPTIMIZE reads the small files in a table, combines their rows, and writes larger files. It commits the result as a new table version.
OPTIMIZE orders;Key properties of the command:
- Compaction does not change query results. It only changes how rows are grouped into files.
- It is safe to run while readers and writers use the table. Readers see either the old version or the new one. Delta uses optimistic concurrency, so a write that conflicts with the compaction can fail and need a retry. Compaction of files that a concurrent writer did not touch usually succeeds.
- It is idempotent in practice. If you run it again with no new writes, it finds little or nothing to do. Files that are already large enough are left alone.
- It targets a file size of around 1 GB by default. The actual size can vary, and Databricks may choose a smaller target for tables it judges to be small or write-heavy.
- It is not free. It uses compute to read and rewrite data, so you pay for the job and should schedule it deliberately.
You can limit the work to part of a table with a WHERE clause on partition columns:
OPTIMIZE orders WHERE order_date >= '2024-01-01';This is useful for large tables where only recent partitions receive new small files. Older partitions that were already compacted do not need another pass.
The output of OPTIMIZE includes metrics such as the number of files added and removed, and the minimum, maximum and median size of the new files. Check these after the first run to confirm that compaction did what you expected.
Ordering data with ZORDER
OPTIMIZE can also sort the data as it rewrites it:
OPTIMIZE orders ZORDER BY (customer_id);ZORDER BY co-locates rows with similar values of the chosen column in the same files. Each file then covers a narrow range of customer_id values, so queries that filter on that column can skip more files. Data skipping and the comparison with liquid clustering are covered in the next chapters. For now, remember that ZORDER BY makes OPTIMIZE more expensive, because it rewrites data in sorted order instead of only merging files. It also rewrites files again on later runs when new data arrives, so use it on columns that queries filter on often.
Preventing small files at write time
Compaction after the fact works, but it is cheaper to write larger files in the first place. Databricks offers table properties for this:
ALTER TABLE orders SET TBLPROPERTIES (
'delta.autoOptimize.optimizeWrite' = 'true',
'delta.autoOptimize.autoCompact' = 'true'
);- Optimized writes shuffle data before writing so each task writes fewer, larger files. This adds a shuffle to the write, so write latency can rise slightly.
- Auto compaction runs a small compaction after a write if the table has many small files. It makes the table healthier without a separate scheduled job, but it does not replace
OPTIMIZEfor large rewrites orZORDER BY.
The defaults for these features depend on your runtime version and table type. Check the documentation for your environment, and confirm what is set with SHOW TBLPROPERTIES orders.
Inspecting the layout
Before you optimize, measure the current state. DESCRIBE DETAIL shows the file count and total size:
DESCRIBE DETAIL orders;Look at numFiles and sizeInBytes. Dividing the size by the file count gives the average file size. An average of a few MB on a table of hundreds of GB is a clear sign of a small files problem. DESCRIBE HISTORY orders lists past operations, so you can see how often writes happen and when OPTIMIZE last ran.
Cleaning up with VACUUM
OPTIMIZE does not delete the old small files. The log marks them as removed, but they stay in storage so that time travel and in-flight readers still work. VACUUM deletes files that are no longer referenced and are older than the retention threshold, which is 7 days by default:
VACUUM orders;Be careful with the retention period. If you shorten it, you lose the ability to time travel past that point, and a long-running query that started before the cleanup can fail because its files disappeared. Do not set it lower than the longest query or stream that reads the table.
Common errors and gotchas
- Running
OPTIMIZEonce and assuming the problem is solved. New writes create new small files, so compaction must recur or be automated. - Expecting
OPTIMIZEto reduce storage cost at once. Old files remain untilVACUUMruns, so storage can briefly grow. - Using
ZORDER BYon a column that no query filters on, or on too many columns. The benefit of Z-ordering falls as you add columns. - Z-ordering by a partition column. It has no effect, because each partition already holds only one value of it.
- Over-partitioning by a high-cardinality column, such as a user ID. This produces many tiny partitions, each with tiny files, which
OPTIMIZEcannot merge across partition boundaries. - Optimizing a small table. If a table totals less than a few hundred MB, one file or a handful of files is already fine.
Putting it together
A practical routine for a table that receives frequent appends looks like this:
- Run
DESCRIBE DETAILto find the average file size. - Enable optimized writes and auto compaction if the table is written often.
- Schedule
OPTIMIZE(with aWHEREfilter for recent partitions, if partitioned) at a rate that fits your write volume. - Add
ZORDER BYonly for columns that queries filter on. - Run
VACUUMon a schedule that respects your time-travel needs. - Compare query times and the amount of data scanned before and after.
Exercise
A table has 40,000 files and 80 GB of data. Queries on it are slow, and the Spark UI shows a very large number of tiny tasks. What is the average file size, and what is the first command you would run to improve the layout? Why will the storage size not drop immediately afterwards?
Show answer
The average file size is about 2 MB (80 GB divided by 40,000). Run OPTIMIZE <table> to compact the small files into larger ones, optionally limited with a WHERE clause on partition columns. Storage does not drop at once because OPTIMIZE only marks the old files as removed in the transaction log. The files remain in storage until VACUUM deletes them after the retention period, which is 7 days by default.
Exercise
You run OPTIMIZE events ZORDER BY (event_date) on a table partitioned by event_date. Why is this not useful?
Show answer
Each partition holds rows with a single event_date value, so there is nothing to order within a partition by that column. Z-ordering only helps on non-partition columns that queries filter on.