Skip to main content
← CONCEPTS / DATA ENGINEERING & PIPELINES
An end-to-end domain learning journey

Lakehouse File Compaction, Z-Ordering
& Data Skipping.

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.
Start the journey7 sections· Last modified Nov 23, 2026
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

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.

Full walkthrough · 7 stages
01
Stage 1 • Foundationfoundation

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.
Storage Layout

200K Tiny Files vs 400 Compacted 256MB Files

200K x 200 KB Files400 x 256 MB FilesStateStore

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.

02
Stage 2 • Data Skippingfoundation

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_tenant or '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.
Query Pruning

Manifest Min/Max Bounds -> File Pruning

WHERE tenant='acme'Manifest StatsRead 2 / 400 FilesStorePrune non-overlapping files

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.

03
Stage 3 • Clustering Strategiesintermediate

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 on A, but useless for queries filtering only on B.
  • Z-Order / Hilbert Curve (ZORDER BY (tenant_id, event_time)): Interleaves the binary bits of A and B so nearby points in 2D space stay close in 1D file order—giving strong data skipping for queries on A, B, or (A, B).
Compaction Modes

Bin-Pack vs Lexicographical Sort vs Z-Order

Bin-PackZ-Order / HilbertStateStore

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.

04
Stage 4 • Concurrency & Deletesintermediate

Optimistic Concurrency (OCC) & Merge-on-Read Delete Files.

Because Iceberg and Delta use Optimistic Concurrency Control (OCC) on immutable snapshots:

  • A background rewrite_data_files job reads snapshot S1, writes compacted Parquet files, and commits a replace snapshot S2.
  • 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 by S1b, rebases cleanly, and commits S2 with zero writer lock stalls.
  • Compaction also materializes Merge-on-Read (MoR) positional/equality delete files into clean base Parquet files, restoring fast scan speeds.
Atomic Compaction

Snapshot Isolation & OCC Rebase

Snapshot S1ProducerConcurrent Stream Atomic Commit SStore

1.:

2.:

Caption: Snapshot-based Optimistic Concurrency Control lets background compaction jobs rewrite old files and commit atomically without blocking concurrent streaming appends.

05
Stage 5 • Implementationintermediate

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))
Maintenance Pipeline

Z-Order Rewrite -> Manifest Rewrite -> Snapshot Expiry

rewrite_data_filesrewrite_manifestsexpire_snapshotsStoreGC unreferenced files

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.

06
Stage 6 • Modern Evolutionadvanced

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.
Partitioning Evolution

Over-Partitioned Directories vs Hilbert Clustering

PARTITION BY (day,tenant)Coarse Partition +Z/HilbertStateStore

1.:

2.:

Caption: Replacing fine-grained physical partitions with coarse partitions plus Z-order/Hilbert clustering prevents small-file explosion while keeping queries fast.

07
Stage 7 • Operations & FinOpsadvanced

Time-Travel Retention, Orphan Files, and Compaction Cost Guardrails.

Watch for three FinOps and safety traps:

  • Unexpired Snapshots: rewrite_data_files writes new 256 MB files and keeps old small files referenced by older snapshots. Until expire_snapshots runs, storage doubles!
  • Orphan File Leaks: Failed Spark tasks leave unreferenced .parquet files on S3; schedule remove_orphan_files(older_than => 3 days) weekly (never < 24h to avoid deleting in-flight writes).
  • Z-Order Write Amplification: Run fast binpack hourly on hot streaming partitions and schedule expensive zorder nightly on settled partitions.
Tiered Maintenance

Hourly Bin-Pack + Nightly Z-Order + Weekly Orphan GC

Hourly Bin-PackNightly Z-Order +ExpireStateStore

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 · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

After running `rewrite_data_files` on a 10 TB Iceberg table, your S3 bucket usage temporarily jumps to 18 TB instead of shrinking. Why?

Recommended Learning Flow