Keeping tables fast

Part of the free LogicWiz Data Engineering course, Module 13: The lakehouse on Databricks. The SQL and Python run in the app, on real Postgres and real Python in the browser.

It is 10:30 on Thursday. Tess's click report used to load in 4 seconds. Today it takes 3 minutes. No job failed and the data barely grew, yet the storage bill keeps climbing. Nora asks one question: "How many files is that table?" You look: 8,640, each about 1 MB.

You'll learn to

  • Work out what small files cost and compact them with OPTIMIZE
  • Explain how file statistics let a query skip files
  • Choose between Z-order and liquid clustering
  • Say what VACUUM deletes and what that does to time travel

Learn

8,640 files of 1 MB each

The events table gets a 1 MB append every five minutes. That is 288 commits a day, and each commit adds at least one new file. A month of that is 8,640 files.

Every file has a fixed cost, however small it is: a storage request or two, a footer to read, a slot in a task. Think of moving house with 8,640 shoeboxes when 34 crates would do. The load weighs the same. The trips do not.

Spark even prices this in. When it plans a scan, it counts each file as its size plus an open cost of 4 MB:

  • data: 8,640 × 1 MB = 8,640 MB
  • planned work: 8,640 × (1 + 4) MB = 43,200 MB

Five times the data.

The same data, planned two ways

Two bars in megabytes: 8,640 files of 1 MB are planned as 43,200 MB of work, while the same data in 34 files of about 256 MB is planned as 8,776 MB.

Both bars hold the same 8,640 MB of data. The difference is the 4 MB that Spark adds for every file it has to open.

Pack the shoeboxes into crates

The fix is compaction: rewrite many small files into a few large ones. On Databricks the command is OPTIMIZE.

The rows do not change. Only how they are packed changes. So the commit marks its add and remove actions with dataChange: false, and a stream reading the table knows it can skip that commit.

The log has the same illness, by the way: 8,640 commits to replay since the last checkpoint.

In the next card, seven small daily writes stand in for the month of appends. Before you run it, answer one question.

Seven small appends, then OPTIMIZE

import minidelta

t = minidelta.DeltaTable('lake/orders')
for day in range(1, 8):                 # one small file per day
    t.write(f"SELECT * FROM 'data/orders.csv' WHERE CAST(order_ts AS DATE) = DATE '2025-06-0{day}'")
print('files before:', len(t.files()), ' rows:', t.count())

t.optimize()
print('files after: ', len(t.files()), ' rows:', t.count())
last = t.history()[0]
print(last['operation'], last['operationMetrics'])

Seven files became one and the row count did not move. Open the last commit with t.log(t.version()): its add and remove actions say "dataChange": false.

How OPTIMIZE fills its bins

OPTIMIZE packs crates the way you would, one partition at a time.

  1. It picks the small files: those under a minimum size.
  2. It walks them in order and fills a bin. A file goes into the current bin unless it would push the bin past the target size. Then a new bin starts.
  3. Each bin with two or more files becomes one task that writes one new file. A bin of one file is skipped: there is nothing to pack.
  4. One commit removes the old files and adds the new ones.

Run it again and it finds nothing small, so it does nothing. A job you can repeat safely like this is idempotent.

On Databricks the target is 256 MB for most tables and grows for very large ones.

Five files, a 256 MB target

Five files of 90, 120, 80, 400 and 60 megabytes: the four small ones are packed into two bins of 210 and 140 megabytes, each bin is written as one new file, and the 400 megabyte file is left alone.

  1. Pick the small files. Four files are under the minimum size (256 MB here). The 400 MB file is big enough already and is left alone.

  2. Fill bin 1. 90 + 120 = 210 MB. The next file, 80 MB, would make 290 MB, which is past the target. So bin 1 closes.

  3. Fill bin 2. The 80 MB file starts a new bin, and the 60 MB file fits beside it: 140 MB. No small files are left.

  4. Write and commit. Each bin is written as one new file. One commit removes the four small files and adds the two new ones. The table now reads 3 files, not 5.

Follow the amber files into the bins. The sizes are made up for the example. The four removed files are still in the folder: hold that thought until VACUUM.

Why the query still opened every file

Fewer files helped. But Tess's report asks for one customer, and it still reads the whole table. Why?

Each add action in the log carries small statistics about its file: the row count, and for each column the smallest and largest value. Before a query opens anything, it reads those stats. For WHERE customer_id = 7 it skips every file whose range from min to max cannot contain 7. This is called data skipping.

There is a condition. Skipping only works if similar values sit together. If every file holds customers 1 to 29, every range contains 7 and nothing is skipped.

Count the files a query must read

import minidelta

def files_to_read(t, column, value):
    """The files whose min/max range for column could hold value."""
    return [f for f, s in t.stats().items()
            if s['minValues'][column] <= value <= s['maxValues'][column]]

t = minidelta.DeltaTable('lake/orders')
for day in range(1, 8):                 # one small file per day
    t.write(f"SELECT * FROM 'data/orders.csv' WHERE CAST(order_ts AS DATE) = DATE '2025-06-0{day}'")
print('before:', len(files_to_read(t, 'customer_id', 7)), 'of', len(t.files()), 'files')

t.optimize(sort_by='customer_id', max_rows_per_file=6)
print('after: ', len(files_to_read(t, 'customer_id', 7)), 'of', len(t.files()), 'files')

optimize(sort_by=...) sorts the rows by customer as it rewrites them. Arranging rows so that similar values share a file is called clustering. Compare the two printed lines, then look at the ranges in the table below.

The customer_id range of each file

Before: files by daymin..maxAfter: sorted by customeridmin..max
part-00000 (1 June)10..28part-000071..6
part-00001 (2 June)7..23part-000086..8
part-00002 (3 June)3..28part-0000910..14
part-00003 (4 June)3..20part-0001014..19
part-00004 (5 June)3..25part-0001120..23
part-00005 (6 June)7..29part-0001223..28
part-00006 (7 June)1..29part-0001328..29

Before, 6 of 7 ranges contain 7, so the query opens 6 files. After sorting, only part-00008 does. Same rows, same number of files, one sixth of the reading.

Files a query for customer 7 opens

Two bars: six of seven files opened when the files are laid out by day, one of seven after clustering by customer_id.

Each bar counts files opened out of 7. The rows are the same in both; only their arrangement changed.

Remember: stats can only skip a file when similar values sit together. Compaction makes files bigger. Clustering makes them skippable.

Sort it every time, or keep it sorted

A real table gives you two ways to cluster.

Z-ordering runs inside OPTIMIZE: OPTIMIZE t ZORDER BY (customer_id, order_date). It weaves the bits of the columns' values together, so rows that are close in all of them land in the same files. Its weakness: every run sorts every file in the partition again. Picture re-sorting a whole bookshelf each time one book arrives.

Liquid clustering keeps the keys with the table: CLUSTER BY (customer_id). OPTIMIZE then shelves only the new books: it rewrites just the data that is not yet clustered. Databricks recommends it for all new tables.

Z-order against liquid clustering

Z-orderLiquid clustering
Asked for in each OPTIMIZE ... ZORDER BY (...)Declared once on the table: CLUSTER BY (...), up to four keys
Not idempotent: each run reclusters every file in the partition, a near-full rewriteIncremental: OPTIMIZE rewrites only data that is not yet clustered
Locality weakens with each extra columnALTER TABLE ... CLUSTER BY changes the keys without a rewrite; OPTIMIZE ... FULL reclusters everything
Works inside the partitions of a partitioned tableCannot be combined with partitioning or Z-order

Compact and cluster on Databricks

Runs on Databricks:

-- An existing partitioned table: compact one day and Z-order it
OPTIMIZE workspace.silver.events WHERE event_date = '2025-06-30' ZORDER BY (user_id);

-- A new table: liquid clustering, keys kept with the table
CREATE TABLE workspace.silver.orders_clustered
CLUSTER BY (customer_id)
AS SELECT * FROM workspace.silver.orders;

-- Queries now filter by date too: change the keys, then recluster old data once
ALTER TABLE workspace.silver.orders_clustered CLUSTER BY (customer_id, order_ts);
OPTIMIZE workspace.silver.orders_clustered FULL;
-- OPTIMIZE returns one row: the table's path and a metrics struct
path             metrics
.../events       {"numFilesAdded": 1, "numFilesRemoved": 288, ...}

Read the metrics: one day of 288 small files became 1. CLUSTER BY AUTO lets Databricks choose the keys from the queries it sees; it needs predictive optimization. Clustering keys must be columns with statistics collected.

The old files are still in the folder

One bill is still climbing: storage. OPTIMIZE, MERGE and DELETE never delete a file. They only mark it removed, so that time travel keeps working (Lesson 13.2).

VACUUM is the command that deletes. It removes data files that no version inside the retention window needs: by default, files removed more than 7 days ago. It also clears files Delta does not manage, such as leftovers of aborted writes. It never touches the log.

The price is time travel. A version needs its log entries (kept 30 days) and its data files (kept 7). After VACUUM the window is the shorter of the two: 7 days.

One day of appends: before, after OPTIMIZE, after VACUUM

Three bars on one scale: 288 files of 1 MB; after OPTIMIZE, a 256 MB file and a 32 MB file plus the 288 old files still kept for time travel, doubling what is stored; after VACUUM a week later, only the two new files.

Read the three bars top to bottom, with a 256 MB target. 288 files of 1 MB fill one 256 MB bin, and the 32 left over make a second. Look at the middle bar: until VACUUM, compaction doubles the storage it was meant to tidy.

How far back time travel reaches after a daily VACUUM

A timeline over 30 days: the JSON log is kept for all 30 days, removed data files only for the last 7, so time travel fails before day 23 and works from day 23 to today.

Read the bottom lane: it is green only where both lanes above it have a bar. To keep 30 days of time travel, raise delta.deletedFileRetentionDuration to 30 days and pay to store every rewritten file for a month. From Databricks Runtime 18.0, versions older than the file retention are refused even before VACUUM runs.

Try it: append, OPTIMIZE, then VACUUM

The Delta table simulator: append a few small files, run OPTIMIZE to compact them, then VACUUM, and see which old versions can still be opened.

Append three times, OPTIMIZE, then click an old version: it still opens. VACUUM deletes the removed small files, and the same old version is gone.

Compact, then clean up

import minidelta

t = minidelta.DeltaTable('lake/orders')
for day in range(1, 8):                 # one small file per day
    t.write(f"SELECT * FROM 'data/orders.csv' WHERE CAST(order_ts AS DATE) = DATE '2025-06-0{day}'")
t.optimize()
on_disk = [n for n in t.ls() if n.endswith('.parquet')]
print(len(on_disk), 'Parquet files in the folder, current version reads', len(t.files()))

gone = t.vacuum(keep_versions=1)
print('VACUUM deleted', len(gone), 'files; rows still', t.count())
try:
    t.count(version_as_of=0)
except minidelta.VersionGone as e:
    print('time travel to version 0:', e)

The rows survive, the old version does not. minidelta keeps versions by count (keep_versions); real VACUUM keeps them by age (RETAIN 168 HOURS is the default 7 days).

VACUUM on Databricks

Runs on Databricks:

VACUUM workspace.silver.events DRY RUN;      -- list what would be deleted
VACUUM workspace.silver.events;              -- delete, keeping 7 days
VACUUM workspace.silver.events RETAIN 0 HOURS;
-- the third command fails with an error that starts:
The specified VACUUM retention period is too low and may corrupt this Delta table
if any writes are in progress. ...

Delta refuses a retention that short, because a write that has not committed yet, or a long-running reader, may still need those files. It only goes through if someone sets spark.databricks.delta.retentionDurationCheck.enabled = false.

The trap: one folder per customer. Never partition by a column with many values. That manufactures the small files you are trying to get rid of. Partition only large tables, by a column with few values such as date, aiming at partitions of a gigabyte or more, or use liquid clustering. Two more habits: keep the 7-day retention in production, and remember that Z-order on a big table rewrites it on every run, so schedule it or move to liquid clustering.

Numbers to remember

Setting or commandDefaultWhat it is
spark.sql.files.openCostInBytes4 MBThe cost Spark adds for each file when it plans a scan
spark.sql.files.maxPartitionBytes128 MBThe most Spark packs into one input split
OPTIMIZE minimum file size1 GB in open-source DeltaFiles under it are the small ones OPTIMIZE picks
OPTIMIZE target file size1 GB in open-source DeltaDatabricks autotunes it by table size: 256 MB for tables under 2.56 TB, rising linearly to 1 GB at 10 TB, or whatever delta.targetFileSize says
Optimized writes, auto compaction128 MBThe file size they aim for when set to true
delta.dataSkippingNumIndexedCols32Stats are kept for the first 32 columns, or the ones you name in delta.dataSkippingStatsColumns. A column without stats cannot be skipped on, and clustering by it does nothing
Liquid clusteringUp to 4 keysGA from Databricks Runtime 15.4 LTS. Writes above a size threshold (64 MB for one key on a Unity Catalog managed table) cluster as they land
delta.deletedFileRetentionDuration7 daysHow long VACUUM keeps a removed data file
delta.logRetentionDuration30 daysJSON commits older than this are cleaned up after checkpoints, never by VACUUM
VACUUM ... LITERecent runtimesFinds candidates from the log instead of listing the folder: much cheaper on a table with millions of files
Folders starting with or .VACUUM ignores them

For Unity Catalog managed tables, Databricks does most of this for you. Predictive optimization runs OPTIMIZE, VACUUM and ANALYZE when it judges a table needs them (it never runs ZORDER), on serverless jobs compute billed to your account, and logs each run in system.storage.predictive_optimization_operations_history. Optimized writes and auto compaction, always on for MERGE, UPDATE and DELETE, stop files getting small in the first place. You still need the mechanism: someone has to explain the bill and the slow query.

What changed at SwiftKart

The events table now gets a nightly OPTIMIZE and is clustered on the column Tess's report filters by. Her report loads in seconds again.

silver.orders is clustered by order date, so the MERGE from Lesson 13.3 touches a few dozen files, not 4,000. VACUUM runs with the default 7 days, and Nora writes the consequence into the team notes: a mistake older than a week cannot be undone with RESTORE.

So far you have looked after one table at a time. Lesson 13.5 lines the tables up: raw files in at one end, numbers Tess can trust at the other.

In one line

OPTIMIZE packs small files into big ones, clustering puts similar values in the same files so their min/max stats can skip them, and VACUUM deletes removed files, which ends time travel past the shorter of the two retention windows.

Interview corner

What is the small files problem, and how do you fix it on Delta?

Every file costs requests, a footer read and an estimated 4 MB open cost in Spark planning, so 8,640 files of 1 MB are planned like 43 GB of work, and every commit lengthens the log replay. I compact with OPTIMIZE, which bin-packs small files into files near the target size, and prevent it with optimized writes and auto compaction. I also avoid partitioning by high-cardinality columns, which multiplies small files, and on Unity Catalog managed tables let predictive optimization schedule the compaction.

Z-order, partitioning or liquid clustering?

Partitioning splits data into folders by a column; it pays only for large tables and low-cardinality columns such as date, with partitions of a gigabyte or more. Z-order interleaves the bits of up to a few columns during OPTIMIZE so min/max skipping works on all of them, but it is not idempotent and rewrites the partition every run. Liquid clustering keeps up to four keys in table metadata, clusters incrementally and lets you change keys without a rewrite; Databricks recommends it for new tables, and it cannot be mixed with partitioning or Z-order.

What does VACUUM delete, and how does it interact with time travel?

It deletes data files that no version within delta.deletedFileRetentionDuration (7 days by default) still references, plus untracked files such as leftovers of failed writes; it never deletes log files, which expire after delta.logRetentionDuration (30 days) at checkpoint time. Time travel needs both, so the practical window is 7 days. A shorter retention can delete files a running query, stream or uncommitted write still needs, which is why RETAIN 0 HOURS is refused unless the check is disabled.

How would you size the target file size for a table?

Large enough that per-file overhead is negligible, small enough to keep parallelism and cheap rewrites. Databricks autotunes 256 MB for tables under 2.56 TB, rising to 1 GB at 10 TB; for tables rewritten often by MERGE I prefer smaller files, because a MERGE rewrites whole files, and delta.tuneFileSizesForRewrites does that automatically. I check the effect in OPTIMIZE metrics such as p50FileSize and in query profiles.