Skip to main content
← PROBLEMS / ARCHITECTURE
An end-to-end domain learning journey

Apache Iceberg Small-Files &
Manifest Bloat Remediation.

Stop small-file creation at the source via 5-minute write buffering and hash-repartitioning, then clear the 200K-file backlog with batched rewrite_data_files, rewrite_manifests, and expire_snapshots.
Start the journey7 stages· Last modified Nov 23, 2026
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

Your Kafka-to-Iceberg streaming pipeline commits micro-batches every 30 seconds across 40 partitions on Amazon S3. After 3 weeks, the table holds 200,000 tiny (~200 KB) Parquet files and 50,000 uncompacted manifest files across 60,000 snapshots. Trino and Spark query planning now stalls for 45 seconds before reading a single byte, S3 throws intermittent `503 Slow Down` errors, and coordinator memory spikes dangerously. Design a zero-downtime remediation and ongoing write/maintenance architecture.

From patterns to decisions.

Stop small-file creation at the source via 5-minute write buffering and hash-repartitioning, then clear the 200K-file backlog with batched rewrite_data_files, rewrite_manifests, and expire_snapshots.

Full walkthrough · 7 stages
01
Stage 1 • Triagefoundation

The Math Behind 200K Files and 50K Manifests in 3 Weeks.

At 1 commit every 30 seconds (2,880 commits/day) across 40 partitions:

  • Data File Explosion: Even 1 file per partition per commit = 115,200 tiny 200 KB files/day.
  • Manifest Explosion: Every commit writes a new manifest file + manifest list + metadata.json. At 60,000 snapshots, query planners spend 45s just fetching metadata JSON/Avro files from S3.
Bloat Cascade

30s Commits x 40 Partitions -> 45s Planning Stall

30s Kafka CommProducer50K Manifests45s Query PlannStore

1.:

2.:

Caption: 30-second commits across 40 partitions generate thousands of daily snapshots and manifests, causing 45-second query planning stalls and S3 503 throttling.

02
Stage 2 • Write-Path Fixfoundation

Stopping New Small Files: Buffering & Pre-Write Distribution.

Compacting the backlog fails if the streaming job keeps creating 4,800 tiny files every hour:

  • Increase Micro-Batch Interval: Move trigger from 30s to 5m (10x fewer commits/snapshots).
  • Iceberg Fanout / Hash Distribution: Set write.distribution-mode = hash on the partition key so each partition is written by 1–2 tasks rather than all 40 executors writing 40 tiny files per partition.
Write-Side Fix

30s Fanout Writes vs 5m Hash-Distributed Writes

30s + No Shuffle5m + HashDistributionStateStore

1.:

2.:

Caption: Extending micro-batches to 5 minutes and enabling hash write distribution cuts incoming Parquet file and snapshot creation by up to 40x.

03
Stage 3 • Backlog Drainintermediate

Safe 3-Step Backlog Drain: Data -> Manifests -> Snapshots.

Rewriting 200,000 files in a single Spark job can OOM the driver. Drain the backlog in three ordered steps:

  1. rewrite_data_files (Partition-Scoped): Filter WHERE event_date = '...' day-by-day with partial-progress.enabled = true so partial progress commits safely even if a job restarts.
  2. rewrite_manifests: Collapses 50,000 small manifest files into ~15–20 ~8 MB manifests.
  3. expire_snapshots: Drops snapshots older than 7 days (retain_last => 10), shrinking metadata.json and deleting old 200 KB files from S3.
Ordered Cleanup

Partial-Progress Data -> Manifests -> Snapshot Expiry

1.rewrite_data_files2. rewrite_manifests3. expire_snapshotsStorePrune metadata & S3

1.:

2.:

Caption: Running partial-progress data compaction per partition, followed by rewrite_manifests and expire_snapshots, safely clears the 200K-file backlog.

04
Stage 4 • S3 Resilienceintermediate

Preventing S3 `503 Slow Down` During Heavy Compaction.

Reading 200,000 small files in parallel from one S3 bucket prefix can trigger 503 Slow Down for live Trino/Spark queries:

  • Cap Concurrent Groups: Set max-concurrent-file-group-rewrites = 4 and max-file-group-size-bytes = 10737418240 (10 GB).
  • Adaptive S3 Retry: Configure fs.s3a.retry.limit = 10 and fs.s3a.connection.maximum = 200 with exponential backoff.
  • Iceberg Object-Store Layout (write.object-storage.enabled = true): Prepends a deterministic hash prefix to Parquet paths so S3 distributes IOPS across thousands of virtual shards.
S3 IOPS Protection

Unbounded Parallelism vs Throttled Hash-Prefixed S3

refill R tokens/sUnbounded CompBurst req/sToken Bucket (cap B)200 OKStore429 DropBucket empty

1.:

2.:

Caption: Bounding concurrent file-group rewrites and enabling Iceberg object-storage hash prefixes eliminates S3 503 throttling during backlog compaction.

05
Stage 5 • Implementationintermediate

Safe Partition-by-Partition Backlog Drainer (Python / PySpark).

Below is a resumable Python driver that drains partitions incrementally with partial-progress.enabled = true and bounded exponential backoff:

import random, time

def drain_iceberg_backlog(spark, table: str, partition_dates: list[str], max_retries: int = 3) -> None:
    for dt in partition_dates:
        sql = f'''
            CALL iceberg.system.rewrite_data_files(
                table => '{table}',
                where => "event_date = DATE '{dt}'",
                options => map(
                    'target-file-size-bytes', '536870912',
                    'min-input-files', '5',
                    'partial-progress.enabled', 'true',
                    'partial-progress.max-commits', '10',
                    'max-concurrent-file-group-rewrites', '4'
                )
            )
        '''
        for attempt in range(max_retries):
            try:
                spark.sql(sql)
                break
            except Exception as exc:
                if attempt == max_retries - 1:
                    raise RuntimeError(f'Backlog drain stalled on {dt}: {exc}') from exc
                time.sleep((5.0 * (2 ** attempt)) + random.uniform(0, 2.0))

    spark.sql(f"CALL iceberg.system.rewrite_manifests('{table}')")
    spark.sql(f"CALL iceberg.system.expire_snapshots(table => '{table}', retain_last => 10)")
Resumable Drainer

Partition Loop -> Partial Progress -> Manifest & Expiry

Date Partition Looppartial-progress=tr…Manifests + ExpiryStoreFinalize table health

1.:

2.:

Caption: Iterating date partitions with partial-progress commits and bounded retry drains massive small-file backlogs without OOMing coordinators.

06
Stage 6 • Metadata Propertiesadvanced

Tuning Iceberg Table Properties for Long-Term Stability.

Prevent metadata bloat from ever returning by setting table-level governance properties:

  • write.metadata.delete-after-commit.enabled = true and write.metadata.previous-versions-max = 20: Automatically deletes old metadata.json files after commits.
  • history.expire.max-snapshot-age-ms = 604800000 (7 days): Bounds snapshot history.
  • commit.manifest.min-count-to-merge = 20: Auto-merges small manifests during regular commits.
Table Governance

Default Unbounded Metadata vs Self-Cleaning Table Props

Default IcebergAuto-Pruned PropsStateStore

1.:

2.:

Caption: Configuring Iceberg metadata auto-deletion and manifest merge thresholds keeps snapshot and manifest counts bounded indefinitely.

07
Stage 7 • Verificationadvanced

Monitoring File Size Distributions & Planning Latency SLOs.

Add automated Iceberg metadata health checks to your observability dashboard:

  • SELECT count(*), avg(file_size_in_bytes)/1e6 FROM table.files: Alert if average file size drops below 64 MB or total file count exceeds 10,000.
  • SELECT count(*) FROM table.manifests: Keep under 50 manifests.
  • Trino/Spark Planning Latency: Track query_planning_ms p99 (target < 500 ms vs 45,000 ms prior).
Post-Fix Telemetry

45s Planning + S3 503s vs 400ms Healthy Steady State

BeforeAfterStateStore

1.:

2.:

Caption: Tracking Iceberg $files and $manifests system tables verifies that average file sizes stay >64 MB and query planning remains under 500 ms.

Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

What does setting `write.distribution-mode = hash` on the Iceberg table accomplish for the streaming sink?

Recommended Learning Flow