Sub topic 9
Optimized writes and auto compaction
This chapter covers two write-time features that reduce small files without a separate maintenance job. It assumes you can run SQL in a Databricks notebook or SQL warehouse, and that you know what a Spark partition and a Parquet file are. It also assumes you have read the earlier chapters on the small-files problem and on OPTIMIZE.
Why fix small files at write time
OPTIMIZE repairs a table after the damage is done. A scheduled OPTIMIZE job works, but it has costs:
- It needs compute that someone has to schedule and pay for.
- Between runs, readers still see many small files.
- Every write that produces small files adds work for the next
OPTIMIZErun.
Delta Lake offers two features that attack the problem earlier. Optimized writes change how data is shuffled before files are written, so each write produces fewer, larger files. Auto compaction runs a small compaction step after a write commits, so files that are still too small get merged.
They solve different problems and are often used together.
| Feature | When it acts | What it does | Main cost |
|---|---|---|---|
| Optimized writes | Before files are written | Rebalances data across tasks so each task writes larger files | An extra shuffle in the write job |
| Auto compaction | After a write commits | Merges small files in the table | Extra time at the end of the write job |
| `OPTIMIZE` | On demand | Rewrites many files into larger ones, optionally with clustering | A separate job |
The problem optimized writes solve
Spark writes data in parallel. Each task writes its own files. For a partitioned table, a single task can hold rows for many partition values, so it may write one file per partition value it sees.
Suppose a job runs 200 tasks and writes to a table partitioned by event_date. If each task holds rows for 30 different dates, the write can create up to 6,000 files. Most of them will be tiny, because each file holds only a few rows from one task.
The same effect appears without partitioning. If a job has 200 shuffle partitions but only 50 MB of data, it can write 200 files of 250 KB each.
Optimized writes add a step before the write. Spark rebalances the data so that rows for the same partition value are gathered into fewer tasks, and each task writes bigger files. The target file size is around 128 MB by default for optimized writes.
The price is the shuffle. The write job moves data across the network before writing, so an individual write can take longer. In return, later reads and later OPTIMIZE runs have less work to do.
Enabling optimized writes
You can set optimized writes on a table with a table property:
ALTER TABLE events SET TBLPROPERTIES (
'delta.autoOptimize.optimizeWrite' = 'true'
);You can also enable it for a Spark session, which applies to writes made in that session:
SET spark.databricks.delta.optimizeWrite.enabled = true;A table property travels with the table, so every job that writes to it benefits, whichever cluster or warehouse runs the job. A session setting only affects the current session. For shared tables, the table property is usually the safer choice.
On recent Databricks runtimes and for some operations, optimized writes may already be on by default. For example, certain SQL warehouse writes and some statements such as MERGE, UPDATE, and DELETE can use it without any setting. Check the documentation for your runtime version before relying on the default. An explicit table property removes the doubt.
Auto compaction
Optimized writes reduce the number of small files a single write creates. They cannot do anything about files that earlier writes left behind. Streaming jobs and frequent small batches are the usual cause: each micro-batch adds a few small files, and over a day there are thousands.
Auto compaction handles this. After a write commits successfully, Delta checks whether the table (or the affected partitions) has enough small files. If it does, it runs a compaction step synchronously on the same cluster that did the write. The step behaves like a small OPTIMIZE that merges small files into larger ones.
Some details to keep in mind:
- It runs after the write commits, so the write itself is already durable and visible. A failure in compaction does not roll back your data.
- It triggers only when a threshold of small files is reached. By default the minimum number of files is 50.
- It compacts files below a size threshold, and its output files are smaller than those produced by a full
OPTIMIZE. The default target is about 128 MB. - It does not apply Z-ordering or clustering. It only merges files.
Enable it with a table property:
ALTER TABLE events SET TBLPROPERTIES (
'delta.autoOptimize.autoCompact' = 'true'
);Newer runtimes also accept values such as 'auto' and 'legacy' for this property, which select the current default behavior or the older one. The value 'true' is accepted on all runtimes that support the feature.
Enabling both together
Most tables that receive frequent small writes benefit from both settings:
ALTER TABLE events SET TBLPROPERTIES (
'delta.autoOptimize.optimizeWrite' = 'true',
'delta.autoOptimize.autoCompact' = 'true'
);You can also set the properties when you create the table, so they apply from the first write:
CREATE TABLE events_stream (
event_id BIGINT,
user_id BIGINT,
event_date DATE,
payload STRING
)
TBLPROPERTIES (
'delta.autoOptimize.optimizeWrite' = 'true',
'delta.autoOptimize.autoCompact' = 'true'
);To confirm what a table has set, run:
SHOW TBLPROPERTIES events;The output lists each property and its value. If a property is missing, the table uses the runtime or session default.
Precedence of settings
Both features can be controlled at the table level and at the session level. When both are set, the session setting generally takes precedence over the table property, because it is applied to the specific write. If a table property is true but a session turns the feature off, that session's writes will not use it.
This matters when you debug. If a table has the property set but still produces small files, check whether the writing job overrides it with a session configuration.
When these features help and when they do not
Good fits:
- Streaming ingestion with short trigger intervals.
- Frequent small batch appends, such as hourly loads of a few megabytes.
- Partitioned tables written by wide jobs, where each task sees many partition values.
MERGE,UPDATE, andDELETEworkloads that rewrite parts of files and tend to leave small ones.
Weaker fits:
- Large, infrequent batch writes that already produce well-sized files. The shuffle in optimized writes adds cost with little gain.
- Jobs where write latency is critical. Auto compaction adds time at the end of the job, and optimized writes add a shuffle.
- Tables that need clustering or Z-ordering. Neither feature reorders data by column values, so you still need
OPTIMIZEor liquid clustering for data skipping.
Common errors and gotchas
- Expecting clustering from auto compaction. Auto compaction merges files only. If your queries filter on
user_id, the layout is unchanged by it. - Compaction target size differs. Files from auto compaction are usually smaller than files from a full
OPTIMIZE. A table can look healthy but still benefit from an occasionalOPTIMIZE. - Session setting overrides the property. A job that explicitly disables the feature will ignore the table property.
- Streaming checkpoints and concurrency. Auto compaction runs on the writer cluster. In a streaming job, that cluster does the compaction work between or after micro-batches, so size it with that in mind.
- Old files remain. Compaction rewrites data into new files and marks old ones as removed in the transaction log. The old files still sit in storage until
VACUUMremoves them, as covered in the VACUUM chapter. - Assuming it fixes existing damage. Turning on both properties only affects future writes. A table that already has 100,000 small files still needs a one-time
OPTIMIZE.
Measuring the effect
Use DESCRIBE DETAIL before and after enabling the properties, and compare the average file size over time:
DESCRIBE DETAIL events;Divide sizeInBytes by numFiles to get the average file size. Then use DESCRIBE HISTORY to see what happened on each write:
DESCRIBE HISTORY events;The history shows WRITE, STREAMING UPDATE, and OPTIMIZE operations. When auto compaction runs, it appears as an OPTIMIZE entry. The operationParameters and operationMetrics columns report details such as the number of files added and removed. If you see regular OPTIMIZE entries after your writes, auto compaction is active.
A healthy pattern is an average file size close to the target of 128 MB or higher, with numFiles growing slowly as data grows. If the file count rises quickly while the average file size stays in the kilobytes, writes are still fragmenting.
Worked example
You ingest clickstream data every five minutes into a table partitioned by event_date. After a month, DESCRIBE DETAIL shows 90,000 files and a size of 45 GB, an average of about 0.5 MB per file.
- Run a one-time
OPTIMIZE events;to compact existing files. The table now has roughly 400 files of ~110 MB each. - Set both table properties so new writes stay healthy.
- After a week, run
DESCRIBE DETAILagain and comparenumFiles. CheckDESCRIBE HISTORYfor theOPTIMIZEentries that auto compaction created. - If average file size falls again, review whether a job overrides the properties, or whether the write pattern is so frequent that you also need a scheduled
OPTIMIZE.
Exercise
A table receives a streaming write every minute. You set 'delta.autoOptimize.autoCompact' = 'true' and find that queries filtering on user_id still scan many files, even though the number of files is now small. Why, and what should you do?
Show answer
Auto compaction only merges small files. It does not arrange rows by column values, so min/max statistics on userid stay wide and data skipping cannot prune files. Use OPTIMIZE with ZORDER BY (userid), or convert the table to liquid clustering with CLUSTER BY (userid), so rows with similar userid values are stored together.
Exercise
Which feature adds a shuffle before files are written, and which feature runs a merge step after the write commits?
Show answer
Optimized writes add the shuffle before files are written, so each task writes larger files. Auto compaction runs after the commit and merges small files that are already in the table.