Sub topic 14
Keeping tables fast and tidy
This chapter assumes you have built the bronze, silver, and gold tables from the earlier chapters. You should be comfortable with Delta Lake basics (the transaction log, versions, and immutable data files) and with Unity Catalog names such as main.silver.orders. Here you learn how to keep those tables fast to read and cheap to store as they grow.
Why tables degrade
Delta tables never edit a data file in place. Every write adds new Parquet files and records them in the transaction log. Every MERGE, UPDATE, DELETE, or CREATE OR REPLACE TABLE marks old files as removed in the log but leaves them in storage. Two problems follow:
- Small files. Streaming runs that trigger often, or Auto Loader runs that see a few new files each time, write many tiny files. Queries then spend more time opening files than reading data.
- Dead files. Files that are no longer part of the current version still occupy storage until something deletes them. A gold table rebuilt every night with
CREATE OR REPLACE TABLEleaves a full copy of itself behind each time.
Two commands handle these problems. OPTIMIZE compacts small files into larger ones. VACUUM deletes files that no table version in the retention window needs.
Measure before you tune
Start by checking whether a table has a problem. DESCRIBE DETAIL reports the number of files and total size.
detail = spark.sql("DESCRIBE DETAIL main.silver.orders").select("numFiles", "sizeInBytes").first()
avg_mb = detail.sizeInBytes / max(detail.numFiles, 1) / 1024 / 1024
print(f"{detail.numFiles} files, average {avg_mb:.1f} MB per file")As a rough guide, files in the tens to hundreds of megabytes are healthy for large tables. An average of a few megabytes or less means compaction will help. Small tables (under about a gigabyte) are fine with a few files, so don't spend effort on them.
Compaction with OPTIMIZE
OPTIMIZE rewrites small files into larger ones. It does not change the table's contents, and readers can keep querying while it runs.
OPTIMIZE main.silver.orders;Compaction is itself a write, so it creates a new table version. Time travel still works across it.
You can also compact at write time instead of afterwards. These two table properties make writers produce bigger files and merge small ones right after a write:
ALTER TABLE main.bronze.orders SET TBLPROPERTIES (
'delta.autoOptimize.optimizeWrite' = 'true',
'delta.autoOptimize.autoCompact' = 'true'
);Optimized writes add some shuffle cost to each write. They pay off for streaming and MERGE workloads that otherwise leave many tiny files, and they matter less for large batch loads that already write big files.
Data layout: clustering instead of partitioning
Compaction fixes file size. Layout decides which files a query has to read. If most gold and silver queries filter on order_ts or customer_id, you want rows with similar values stored together, so Delta can skip files whose min/max statistics rule them out.
Databricks recommends liquid clustering for new tables. You name the clustering columns, and OPTIMIZE clusters the data incrementally:
ALTER TABLE main.silver.orders CLUSTER BY (order_ts, customer_id);
OPTIMIZE main.silver.orders;You can change the clustering columns later without rewriting the whole table. That is a main advantage over the older approaches, which are:
| Approach | Strength | Limitation |
|---|---|---|
| Hive-style partitioning | Simple, good for very large tables with one low-cardinality filter column such as date | Fixed at creation. Too many partitions create many small files. |
| `ZORDER BY` | Multi-column co-location | Rewrites data on each run and cannot be combined with partitioning on the same columns. |
| Liquid clustering | Changeable keys, incremental, works with streaming writes | Choose a few columns you really filter on, because more keys dilute the benefit. |
Clustering choices differ by layer. Bronze is read mostly by the silver job, which reads new data incrementally, so it rarely needs clustering keys. Silver benefits from keys that match MERGE join conditions and common filters, such as order_id or order_ts. Gold tables are small and aggregated, so compaction is usually enough, unless a mart is large and filtered by a known column.
Cleaning up with VACUUM
VACUUM physically deletes data files that are no longer referenced by the current version and are older than the retention threshold. The default threshold is 7 days.
-- List the files that would be deleted, without deleting anything
VACUUM main.silver.orders DRY RUN;
-- Delete them
VACUUM main.silver.orders;Retention is a trade-off between storage cost and how far back you can go. Once a file is vacuumed, time travel to any version that needed it fails. Two table properties control the windows:
ALTER TABLE main.silver.orders SET TBLPROPERTIES (
'delta.deletedFileRetentionDuration' = 'interval 7 days',
'delta.logRetentionDuration' = 'interval 30 days'
);deletedFileRetentionDuration is how long removed data files survive before VACUUM may delete them. logRetentionDuration is how long history entries are kept. Time travel needs both, so effective history is the shorter of the two.
Check history before choosing a value with DESCRIBE HISTORY main.silver.orders. It shows which operations produced each version, which also helps you spot a noisy writer.
Retention and your pipeline
The layers have different recovery needs, so retention should differ too.
- Bronze is your replay source. If silver logic has a bug, you rebuild from bronze. Keep bronze rows long term. File retention for the table can still be short, because replay uses the current rows, not old versions. If the raw files in the landing volume are also retained, bronze is doubly recoverable.
- Silver is where you may want time travel to undo a bad
MERGE. Keep a retention window longer than the time it takes you to notice a problem. - Gold tables rebuilt with
CREATE OR REPLACE TABLEproduce a full set of dead files each run. Vacuum them regularly, or storage grows by one copy of the table per run.
A streaming job reading bronze as a Delta source (for example, a downstream stream from main.bronze.orders) tracks its position in its checkpoint. If the stream is stopped for longer than the log retention, the versions it needs may be gone. Keep log retention well above your longest planned outage.
Let Databricks do it: predictive optimization
For Unity Catalog managed tables, predictive optimization runs OPTIMIZE, VACUUM, and statistics collection for you, based on observed table usage. It is enabled by default for newer accounts. Otherwise, you can turn it on at catalog or schema level:
ALTER SCHEMA main.silver ENABLE PREDICTIVE OPTIMIZATION;Predictive optimization covers managed tables only. External tables, and any tables in a workspace without it enabled, still need scheduled maintenance. When it is on, avoid also scheduling manual OPTIMIZE and VACUUM jobs against the same tables, since they duplicate work.
If you must run maintenance yourself, make it a separate scheduled task in your job, after the gold step. This keeps the pipeline's own tasks short:
OPTIMIZE main.silver.orders;
VACUUM main.silver.orders;
OPTIMIZE main.gold.daily_revenue;
VACUUM main.gold.daily_revenue;Run these weekly or daily for busy tables, not after every pipeline run.
Common mistakes
- Running
OPTIMIZEon tiny tables. It costs compute and gains nothing. - Partitioning a table by a high-cardinality column such as
customer_id. This produces thousands of small partitions. Use clustering instead. - Setting retention to zero hours to reclaim space. This breaks readers and removes your safety net.
- Picking five or more clustering columns "just in case". Choose the one to three columns used in filters and join keys.
- Assuming
DELETEfrees space. It writes new files and keeps the old ones untilVACUUMruns. This matters when you remove personal data for compliance, because the old files still hold it until vacuumed.
Exercise
Your gold table main.gold.daily_revenue is rebuilt every night with CREATE OR REPLACE TABLE. After three months its storage size is about 90 times the size of the current table, but queries are fast. What explains the growth, and what do you do about it?
Show answer
Each rebuild marks the previous files as removed in the transaction log but leaves them in storage. Fast queries are expected because readers only open files in the current version. The fix is to run VACUUM on the table, after checking with VACUUM main.gold.daily_revenue DRY RUN. Keep the retention at least as long as your time-travel needs, 7 days by default. Better still, enable predictive optimization on the schema so VACUUM runs automatically.