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.
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,200tiny 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.
30s Commits x 40 Partitions -> 45s Planning Stall
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.
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
30sto5m(10x fewer commits/snapshots). - Iceberg Fanout / Hash Distribution: Set
write.distribution-mode = hashon the partition key so each partition is written by 1–2 tasks rather than all 40 executors writing 40 tiny files per partition.
30s Fanout Writes vs 5m Hash-Distributed Writes
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.
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:
rewrite_data_files(Partition-Scoped): FilterWHERE event_date = '...'day-by-day withpartial-progress.enabled = trueso partial progress commits safely even if a job restarts.rewrite_manifests: Collapses 50,000 small manifest files into ~15–20 ~8 MB manifests.expire_snapshots: Drops snapshots older than 7 days (retain_last => 10), shrinkingmetadata.jsonand deleting old 200 KB files from S3.
Partial-Progress Data -> Manifests -> Snapshot Expiry
1.:
2.:
Caption: Running partial-progress data compaction per partition, followed by rewrite_manifests and expire_snapshots, safely clears the 200K-file backlog.
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 = 4andmax-file-group-size-bytes = 10737418240(10 GB). - Adaptive S3 Retry: Configure
fs.s3a.retry.limit = 10andfs.s3a.connection.maximum = 200with 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.
Unbounded Parallelism vs Throttled Hash-Prefixed S3
1.:
2.:
Caption: Bounding concurrent file-group rewrites and enabling Iceberg object-storage hash prefixes eliminates S3 503 throttling during backlog compaction.
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)")Partition Loop -> Partial Progress -> Manifest & Expiry
1.:
2.:
Caption: Iterating date partitions with partial-progress commits and bounded retry drains massive small-file backlogs without OOMing coordinators.
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 = trueandwrite.metadata.previous-versions-max = 20: Automatically deletes oldmetadata.jsonfiles 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.
Default Unbounded Metadata vs Self-Cleaning Table Props
1.:
2.:
Caption: Configuring Iceberg metadata auto-deletion and manifest merge thresholds keeps snapshot and manifest counts bounded indefinitely.
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 below64 MBor total file count exceeds10,000.SELECT count(*) FROM table.manifests: Keep under50manifests.- Trino/Spark Planning Latency: Track
query_planning_msp99 (target< 500 msvs45,000 msprior).
45s Planning + S3 503s vs 400ms Healthy Steady State
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: Make the trade-off yourself.
What does setting `write.distribution-mode = hash` on the Iceberg table accomplish for the streaming sink?