Sub topic 3
Optimized Writes, Compaction, and Maintenance
Assume you know basic SQL, Delta tables, Parquet files, and Spark partitions. This chapter focuses on maintenance after a table has been written.
Optimized writes and auto compaction
Optimized writes reduce the number of small files during a write. Auto compaction combines remaining small files after the write finishes. Both reduce file-opening overhead and improve scan performance.
ALTER TABLE events SET TBLPROPERTIES (
'delta.autoOptimize.optimizeWrite' = 'true',
'delta.autoOptimize.autoCompact' = 'true'
);These settings help, but they do not replace periodic OPTIMIZE for heavily updated tables. They also add work to writes, so measure both write and read performance.
Checking layout and pruning
Use DESCRIBE DETAIL to inspect file counts and total size. A high numFiles compared with sizeInBytes suggests small files.
DESCRIBE DETAIL events;
DESCRIBE HISTORY events;History shows when maintenance operations ran. To check whether a filter can skip files, inspect the query plan and compare runtime before and after maintenance. A useful filter usually matches partition columns, Z-order columns, or liquid-clustering columns.
EXPLAIN SELECT *
FROM events
WHERE user_id = 42;Cleaning up with VACUUM
OPTIMIZE rewrites files but leaves old files temporarily because readers may still need them. VACUUM deletes unreferenced files older than the retention period.
VACUUM events RETAIN 168 HOURS;The seven-day period is a safety default. Do not reduce retention below the time required by long-running readers, delayed jobs, or time-travel requirements.
Predictive optimization
For eligible Unity Catalog managed tables, predictive optimization can automate maintenance such as OPTIMIZE and VACUUM. It reduces scheduling work, but you should still monitor file counts, query performance, and storage usage.
Choosing and migrating layouts
Use partitioning for a low-cardinality column, such as event date, when queries commonly filter by it. Use Z-ordering for additional selective filters on a traditionally partitioned table. Use liquid clustering when access patterns change or several columns need flexible organization.
To move an existing compatible table to liquid clustering, declare clustering columns and then optimize:
ALTER TABLE events CLUSTER BY (event_date, user_id);
OPTIMIZE events;Change or remove the keys with another ALTER TABLE statement, then run OPTIMIZE again.
Exercise
Which maintenance operation reclaims storage from obsolete files after OPTIMIZE?
Show answer
VACUUM, after the configured retention period has passed.