Sub topic 4
Compacting files with OPTIMIZE
This chapter assumes you know basic SQL, can run commands in a Databricks notebook or SQL warehouse, and understand that a Delta table is Parquet data files plus a transaction log. It also assumes you have seen the small-files problem described in the earlier chapter. Here you will learn what OPTIMIZE does to a table, how to run it safely, and how to read its output.
What OPTIMIZE does
OPTIMIZE reads small data files in a Delta table and rewrites their rows into fewer, larger files. This is called compaction. Compaction reduces the per-file cost of listing, opening, and reading files. Every file a query touches costs a metadata lookup and a read request against cloud storage. Fewer files mean fewer of those.
The strategy is bin-packing. OPTIMIZE groups small files into bins that approach a target size, then writes one new file per bin. The target is up to about 1 GB per file by default. Databricks can pick a smaller target for small tables or for tables with heavy rewrite activity, so do not expect every file to be exactly 1 GB.
OPTIMIZE changes how the data is laid out, not what the data is. The new log entry marks the file changes as not changing data. Queries return the same rows before and after.
Check the table before you compact
Start by measuring. DESCRIBE DETAIL returns table metadata, including numFiles and sizeInBytes.
DESCRIBE DETAIL events;Divide sizeInBytes by numFiles to get the average file size. As a rough guide, an average of a few MB on a table of tens of GB points to a small-files problem. An average in the hundreds of MB suggests compaction will not help much.
| Observation | Likely meaning |
|---|---|
| 40,000 files, 20 GB total | Average of about 0.5 MB. Strong candidate for OPTIMIZE. |
| 200 files, 20 GB total | Average of about 100 MB. Layout is already reasonable. |
| 1 file, 50 MB total | Nothing to compact. |
DESCRIBE HISTORY events shows recent writes. Many small WRITE, MERGE, or STREAMING UPDATE commits in a short period explain why files are small.
Running OPTIMIZE
The simplest form compacts the whole table.
OPTIMIZE events;The command returns one row with the table path and a metrics struct. The fields you will use most are:
numFilesAddedandnumFilesRemoved: how many files were written and replaced.filesAddedandfilesRemoved: structs withmin,max,avg, andtotalSize. Compare theavgvalues to see the change in file size.numBatches: how many batches of work the command ran.totalConsideredFilesandtotalFilesSkipped: how many filesOPTIMIZElooked at and how many it left alone.
A healthy result has numFilesRemoved much larger than numFilesAdded, and a filesAdded.avg near the target size.
OPTIMIZE is idempotent
OPTIMIZE leaves alone files that are already large enough. If you run it twice with no new writes in between, the second run does little or no work and may report zero files added. Only new small files, produced by later writes, get compacted next time. This is why a scheduled OPTIMIZE gets cheaper once the old data has been compacted, as long as the new data per run is small compared with the whole table.
A caution: files that are compacted are rewritten, not edited. Rewriting costs compute and storage writes, and it creates a new copy of the data. For large tables, compaction is real work, so choose when to run it.
Restricting OPTIMIZE with WHERE
On a table partitioned with PARTITIONED BY, you can compact only some partitions. Put a filter on partition columns in the WHERE clause.
CREATE TABLE events_partitioned (
event_id BIGINT,
user_id BIGINT,
event_date DATE,
payload STRING
)
PARTITIONED BY (event_date);
OPTIMIZE events_partitioned
WHERE event_date >= '2024-01-01';This is the standard way to keep cost down for a table that receives new data every day. Old partitions are already compacted and rarely change, so you only compact the recent ones.
Two points to remember:
- The
WHEREpredicate on a partitioned (non-clustered) table may reference only partition columns. A filter onuser_idin this table fails with an error, becauseOPTIMIZEworks by whole partitions here. - Compaction happens within each partition.
OPTIMIZEnever merges files across partitions, because each partition's files live in their own directory and share partition values.
That second point matters. A table partitioned on a high-cardinality column, such as one with millions of distinct values, has many tiny partitions, and OPTIMIZE cannot make files larger than the data in a partition. The next chapter covers when partitioning helps and when it hurts.
Using the Python API
The Delta Lake Python API exposes the same operation. This is useful when compaction is part of a job that already runs in Python.
from delta.tables import DeltaTable
dt = DeltaTable.forName(spark, "events")
result = dt.optimize().executeCompaction()
result.show(truncate=False)executeCompaction() returns a DataFrame with the same metrics as the SQL command. To restrict it to partitions, add where:
from delta.tables import DeltaTable
dt = DeltaTable.forName(spark, "events_partitioned")
dt.optimize().where("event_date >= '2024-01-01'").executeCompaction()The Python API also offers executeZOrderBy, which a later chapter covers.
How OPTIMIZE interacts with other work
OPTIMIZE is a normal Delta transaction. It writes new files, then commits one log entry that removes the old files and adds the new ones. This gives it several properties.
- Readers are not blocked. A query that started before the commit keeps reading the old files. A query that starts after the commit reads the new ones.
- Appends can run alongside it. New files written while
OPTIMIZEruns are not part of the compaction, and the commit succeeds. ConcurrentINSERTand streaming appends normally do not conflict. - Updates, deletes, and merges can conflict. If another job rewrites a file that
OPTIMIZEis also rewriting, one transaction fails with a concurrent modification error. Partition theOPTIMIZEaway from theMERGEtarget range with aWHEREclause, or schedule them apart. - Time travel still works. Old versions of the table still point to the old files, so queries on earlier versions keep working.
The old files stay on storage
After OPTIMIZE, the replaced small files are no longer part of the current table version. They are still in cloud storage. Storage use can therefore go up right after compaction, because the table now holds both copies.
VACUUM deletes files that the table no longer references and that are older than the retention period.
VACUUM events RETAIN 168 HOURS;The 168 hours here is 7 days, the default retention. Do not shorten it without a reason. Readers and time-travel queries on older versions need those files, and a shorter retention can break long-running queries.
A later chapter covers VACUUM in more detail.
Common mistakes
- Compacting a table that does not need it. Check
DESCRIBE DETAILfirst. A table whose average file size is already near the target gains little. - Running OPTIMIZE after every small write. Each run has fixed overhead and rewrites data. Run it on a schedule that matches ingestion, for example once per day after a batch load, or use the write-time features covered later.
- Compacting the whole table every time. On a large partitioned table, use
WHEREto limit the work to recent partitions. - Expecting OPTIMIZE to fix a bad partitioning scheme. Compaction cannot merge across partitions, so over-partitioned tables stay fragmented.
- Forgetting VACUUM. The table is faster to read but storage cost stays high until old files are removed.
- Using a cluster that is too small.
OPTIMIZEis a Spark job. Its speed depends on the cluster size, so a large first-time compaction on a tiny cluster can run for hours.
Summary of the workflow
- Run
DESCRIBE DETAILand compute the average file size. - Run
OPTIMIZE, adding aWHEREon partition columns if the table is partitioned and large. - Compare
filesAdded.avgtofilesRemoved.avgin the output. - Run
DESCRIBE DETAILagain to confirmnumFilesdropped. - Plan a
VACUUMto reclaim storage.
Exercise
A table partitioned by eventdate has 30,000 files totalling 15 GB. You run OPTIMIZE eventspartitioned WHERE user_id = 42 and get an error. Why does it fail, how would you restrict the job to the last 7 days, and why can storage use rise after the job finishes?
Show answer
On a partitioned table that is not liquid clustered, the WHERE clause of OPTIMIZE may reference only partition columns, and userid is not one. To restrict the job, filter on eventdate, for example OPTIMIZE eventspartitioned WHERE eventdate >= current_date() - INTERVAL 7 DAYS. Storage can rise because OPTIMIZE writes the new large files but leaves the old small files on storage, since earlier table versions still reference them. They are deleted only when VACUUM runs after the retention period.