Lakehouse engines achieve warehouse-grade scan speeds on S3/GCS by compacting tiny streaming files into 256–512 MB Parquet files and co-locating multi-column query predicates via Z-ordering so min/max stats prune irrelevant files.
TL;DR30-second simplified summary▾
Streaming ingestion into Apache Iceberg or Delta Lake writes thousands of small 100 KB–2 MB Parquet files per hour. Because object stores like Amazon S3 incur 10–50 ms per GET/HEAD request and Spark/Trino planners must inspect file metadata before scanning, small-file fragmentation turns simple queries into minutes-long metadata storms.
Bin-Pack Compaction merges many tiny Parquet files within a partition into target-sized files (typically 256–512 MB) without changing row order. It eliminates S3 request overhead and improves Parquet dictionary/RLE compression, but does not tighten min/max column ranges if rows arrive in random order.
Z-Order Clustering (and modern Hilbert-curve Liquid Clustering) solves multi-dimensional filtering: it interleaves the bits of 2–4 commonly filtered columns (e.g., tenant_id, event_time) to map multi-dimensional points onto a 1D sort key. When written to 256 MB Parquet files, each file's min/max statistics in the Iceberg manifest or Delta transaction log cover a tight, non-overlapping region—letting query planners skip 95–99% of files via Data Skipping.
Key trade-offs involve compute cost and write amplification: Z-ordering requires an expensive global shuffle/sort (often 3–5x more CPU than bin-packing), diminishes in effectiveness beyond 3–4 clustering columns, and requires optimistic concurrency control (OCC) so background compactions never conflict with live streaming writers.
From patterns to decisions.
Explain how bin-pack compaction, Z-order/Hilbert space-filling curves, and snapshot manifest stats accelerate lakehouse queries.
The Small-File Tax on Object Storage (S3/GCS).
Unlike local NVMe SSDs, object stores (S3, GCS, ADLS) have high per-object open latency (~20–40 ms) and strict per-prefix request limits (5,500 GETs/sec per prefix in S3):
- Metadata Bloat: Each Parquet file carries a footer and an Iceberg/Delta manifest entry. Planning 200,000 files takes 30–60 seconds on the driver before a single task runs.
- Broken Compression: Parquet row groups need ~128 MB to build effective dictionary and run-length encodings; 200 KB files compress poorly.
200K Tiny Files vs 400 Compacted 256MB Files
1.:
2.:
Caption: Compacting 200,000 tiny Parquet files into 400 target-sized 256 MB files cuts S3 metadata round-trips by 500x and eliminates coordinator planning stalls.
How Manifest Min/Max Column Stats Enable Data Skipping.
Iceberg manifests and Delta _delta_log checkpoints store lower_bounds and upper_bounds for columns in every Parquet file.
When a query asks WHERE tenant_id = 'acme' AND amount > 500, the planner checks each file's [min, max] range:
- If
'acme' < file.min_tenantor'acme' > file.max_tenant, the entire 256 MB file is pruned in memory with zero S3 I/O. - Why Unsorted Files Fail: If every streaming micro-batch contains rows from all tenants (
min='aaa', max='zzz'), every file overlaps the query and 0% of files are skipped.
Manifest Min/Max Bounds -> File Pruning
1.:
2.:
Caption: Manifest min/max column bounds let engines prune non-overlapping Parquet files in memory, skipping >95% of S3 reads when rows are clustered.
Bin-Pack vs. Sort vs. Z-Order & Hilbert Curves.
Choosing the right compaction strategy depends on your query predicates:
- Bin-Pack: Fast linear merge of small files with zero global sort. Best for append-only logs queried strictly by partition.
- Lexicographical Sort (
SORT BY (A, B)): Great for queries filtering onA, but useless for queries filtering only onB. - Z-Order / Hilbert Curve (
ZORDER BY (tenant_id, event_time)): Interleaves the binary bits ofAandBso nearby points in 2D space stay close in 1D file order—giving strong data skipping for queries onA,B, or(A, B).
Bin-Pack vs Lexicographical Sort vs Z-Order
1.:
2.:
Caption: Bin-packing fixes file size cheaply, whereas Z-order and Hilbert curves interleave bits across 2–4 columns to tighten min/max bounds for multi-dimensional queries.
Optimistic Concurrency (OCC) & Merge-on-Read Delete Files.
Because Iceberg and Delta use Optimistic Concurrency Control (OCC) on immutable snapshots:
- A background
rewrite_data_filesjob reads snapshotS1, writes compacted Parquet files, and commits areplacesnapshotS2. - If a streaming writer commits new appended files (
S1 -> S1b) while compaction is running, Iceberg/Delta checks that the files being replaced were not modified byS1b, rebases cleanly, and commitsS2with zero writer lock stalls. - Compaction also materializes Merge-on-Read (MoR) positional/equality delete files into clean base Parquet files, restoring fast scan speeds.
Snapshot Isolation & OCC Rebase
1.:
2.:
Caption: Snapshot-based Optimistic Concurrency Control lets background compaction jobs rewrite old files and commit atomically without blocking concurrent streaming appends.
Automated Iceberg Compaction & Snapshot Expiry Job (PySpark).
Never compact partitions that only have 1–2 files—use min-input-files to avoid pointless rewrites, and run with bounded retry on transient OCC commit conflicts:
import random, time
def run_iceberg_maintenance(spark, table: str, max_retries: int = 3) -> None:
if not table or '.' not in table:
raise ValueError('Table must be qualified as catalog.db.table')
compact_sql = f'''
CALL iceberg.system.rewrite_data_files(
table => '{table}',
strategy => 'sort',
sort_order => 'zorder(tenant_id, event_time)',
options => map(
'target-file-size-bytes', '268435456',
'min-input-files', '5',
'max-concurrent-file-group-rewrites', '4'
)
)
'''
for attempt in range(max_retries):
try:
spark.sql(compact_sql)
spark.sql(f"CALL iceberg.system.rewrite_manifests('{table}')")
spark.sql(f"CALL iceberg.system.expire_snapshots(table => '{table}', retain_last => 5)")
return
except Exception as exc:
if attempt == max_retries - 1:
raise RuntimeError(f'Maintenance failed for {table}: {exc}') from exc
time.sleep((2.0 * (2 ** attempt)) + random.uniform(0, 1.0))Z-Order Rewrite -> Manifest Rewrite -> Snapshot Expiry
1.:
2.:
Caption: Chaining rewrite_data_files (Z-order, 256 MB target), rewrite_manifests, and expire_snapshots with bounded retry keeps data and metadata compact.
Incremental Liquid Clustering vs. Static Partitioning.
Static partitioning (PARTITIONED BY (day, region)) breaks when a high-cardinality key like tenant_id creates 10,000 tiny partitions or when query patterns shift.
- Over-Partitioning Hazard: Partitioning by
(day, tenant_id)guarantees small files because each partition cannot merge across boundaries. - Incremental / Liquid Clustering: Replaces rigid sub-partitions with coarse time partitioning (or unpartitioned tables) plus incremental Hilbert-curve clustering on
(tenant_id, event_time)—adapting cluster keys without rewriting historical data.
Over-Partitioned Directories vs Hilbert Clustering
1.:
2.:
Caption: Replacing fine-grained physical partitions with coarse partitions plus Z-order/Hilbert clustering prevents small-file explosion while keeping queries fast.
Time-Travel Retention, Orphan Files, and Compaction Cost Guardrails.
Watch for three FinOps and safety traps:
- Unexpired Snapshots:
rewrite_data_fileswrites new 256 MB files and keeps old small files referenced by older snapshots. Untilexpire_snapshotsruns, storage doubles! - Orphan File Leaks: Failed Spark tasks leave unreferenced
.parquetfiles on S3; scheduleremove_orphan_files(older_than => 3 days)weekly (never< 24hto avoid deleting in-flight writes). - Z-Order Write Amplification: Run fast
binpackhourly on hot streaming partitions and schedule expensivezordernightly on settled partitions.
Hourly Bin-Pack + Nightly Z-Order + Weekly Orphan GC
1.:
2.:
Caption: Pairing hourly low-cost bin-packing with nightly Z-ordering, snapshot expiry, and 3-day-safe orphan cleanup optimizes both query speed and S3 cost.
Practice: Make the trade-off yourself.
After running `rewrite_data_files` on a 10 TB Iceberg table, your S3 bucket usage temporarily jumps to 18 TB instead of shrinking. Why?