Data Architecture & Reliability
Why Your Data Lake Is Getting Expensive (And How to Fix It)
The S3 Bill Doesn’t Lie — But It Doesn’t Explain Itself Either
The pipeline ran every hour. Every run wrote a new set of files. After six months, the table had 4.2 million files.
Every query took 12 minutes. Not because the data was large. Because the query planner had to list 4.2 million files before reading a single byte.
Storage cost: $1,800/month. Query infrastructure to compensate: $6,400/month.
The root cause was a partition strategy designed at 10 GB, still running unchanged at 50 TB.
Data lake costs grow in two ways. The first is obvious: more data, more storage. The second is invisible: more files, more metadata, more read overhead, more compute needed to compensate for a lake that was never designed for its current scale.
Most teams are paying for the second problem while assuming they have the first.
TL;DR
- Small files are the single most common cause of data lake cost explosion — and they accumulate silently
- Partition explosion turns a reasonable design into a metastore bottleneck at scale
- Read amplification means you pay to scan bytes that have nothing to do with your query
- Storage cost and query cost are coupled — optimizing one without the other makes both worse
- Most data lakes are expensive because of how data was written, not how much data exists
A data lake that nobody can afford to query is not an asset. It is a liability with an S3 invoice attached.

The S3 Bill Has a Root Cause
Object storage pricing looks simple: you pay per GB stored, per request, and per byte transferred. But the real cost is not in those line items. It is in the compute required to query a lake that is structurally expensive to read.
A well-structured data lake at 10 TB can be queried for less than $50/month in compute. The same data, poorly structured — wrong file sizes, wrong partitioning, no statistics — can require $2,000–5,000/month in compute to serve the same queries.
The storage bill is a symptom. The architecture is the disease.
The Small Files Problem
This is the most common and most damaging structural failure in production data lakes.
A file in object storage is not free to open. Every file requires:
- A metadata lookup in the catalog or metastore
- An S3 LIST or HEAD request to verify existence and size
- A connection to read the file content
- A task on a Spark executor assigned specifically to that file
When your table has 10 files, this overhead is negligible. When it has 4 million files, this overhead dominates your query time — often completely eclipsing actual data processing.
How Small Files Happen
Streaming pipelines are the primary source. A pipeline processing 1,000 events/second writing to hourly partitions will produce:
1,000 events/sec × 3,600 sec = 3.6M events/hour
If each micro-batch writes a new file every 30 seconds:
3,600 / 30 = 120 files per partition per hour
120 files × 24 hours × 365 days = 1,051,200 files/year
per partition.After one year with modest cardinality, you have tens of millions of files.
Append-heavy batch pipelines create the same problem. Every incremental load adds files. Every backfill run adds more. Nobody deletes the old ones because the pipeline never needed to.
What Small Files Actually Cost You
The cost appears in three places:
Query planning time scales linearly with file count. Spark must enumerate every file in a partition before it can plan the query. At 100,000 files, planning takes seconds. At 4 million files, planning takes minutes — before a single byte of actual data is read.
Task scheduling overhead multiplies with file count. Each file typically becomes at least one task. A query against a table with 500,000 files can generate 500,000 tasks on your cluster. The scheduler overhead alone saturates your driver.
S3 request costs are real and overlooked. Every LIST, HEAD, and GET request has a price. At 4 million files queried hourly: the S3 request bill alone can exceed the storage cost.
# Diagnose your small files problem before it becomes a crisis
def audit_file_distribution(table_path: str, spark):
files = spark.read.format("delta").load(table_path).inputFiles()
import boto3
s3 = boto3.client("s3")
sizes = []
for f in files[:10000]: # sample first 10k
bucket, key = f.replace("s3://", "").split("/", 1)
meta = s3.head_object(Bucket=bucket, Key=key)
sizes.append(meta["ContentLength"] / (1024 * 1024)) # MB
avg_mb = sum(sizes) / len(sizes)
small_count = sum(1 for s in sizes if s < 32)
print(f"Total files sampled: {len(sizes)}")
print(f"Average file size: {avg_mb:.1f} MB")
print(f"Files under 32 MB: {small_count} ({100*small_count/len(sizes):.1f}%)")
if avg_mb < 64:
print("WARNING: Severe small files problem. Compaction required.")
elif avg_mb < 128:
print("CAUTION: File sizes below optimal. Consider compaction.")
else:
print("OK: File sizes are within acceptable range.")☁️ Object Storage Was Never Designed Like a Filesystem
One of the most important architectural misunderstandings in modern data engineering is treating S3 like HDFS.
They are not equivalent systems.
HDFS was designed as a distributed filesystem:
- low-latency metadata operations
- atomic renames
- filesystem semantics
- compute and storage co-located
S3 is an object store.
That distinction changes everything.
Why This Matters
Operations that are cheap in HDFS become expensive in object storage:
- directory listing
- recursive partition discovery
- file renames
- metadata enumeration
A Spark job writing 500,000 files to S3 is not just writing data.
It is generating:
- object metadata operations
- LIST requests
- HEAD requests
- eventual consistency coordination
- transaction management overhead
At scale, object store semantics become part of the architecture itself.
Rename Operations Are Extremely Expensive
In HDFS:
rename(fileA → fileB)is a metadata operation.
In S3:
renameis actually:
copy object
→ delete originalFor large datasets, this becomes a hidden write amplification cost.
This is one reason modern table formats avoid heavy rename-based commit protocols.
Why Commit Protocols Became a Systems Problem
Traditional Hive commit patterns relied on atomic filesystem behavior.
Object stores do not provide those guarantees naturally.
This forced modern lakehouse systems to introduce:
- transaction logs
- snapshot isolation
- manifest-based metadata layers
- optimistic concurrency control
The lakehouse architecture exists partly because object storage semantics forced it to exist.
The Important Shift
At PB scale, you are no longer designing:
Spark jobs over files.
You are designing:
distributed metadata systems over object storage primitives.
That is a fundamentally different engineering problem.
Partition Explosion
Partitioning is the second major structural failure mode. It starts as a reasonable design decision and becomes a catastrophe at scale.
How Partitions Multiply
Consider a table partitioned by event_date, region, and product_category:
365 days × 50 regions × 200 categories = 3,650,000 partitionsEach partition is a directory in S3. Each directory entry is a record in the metastore. Three years of this table: ~10 million metastore records — for one table.
Every query that touches this table requires the metastore to enumerate relevant partitions, filter them against the query predicates, and return the matching set. At 10 million partitions, that enumeration is the bottleneck. Not compute. Not network. The catalog.
The Metastore Bottleneck
Hive Metastore and AWS Glue Catalog are sequential systems. Partition listing is not parallelized in the same way query execution is. Adding more executors does not make the catalog faster.
# Measure partition count before it becomes unmanageable
def check_partition_health(database: str, table: str, spark):
partitions = spark.sql(
f"SHOW PARTITIONS {database}.{table}"
).count()
print(f"Partition count: {partitions:,}")
if partitions > 100_000:
print("CRITICAL: Partition count exceeds 100k. Query planning degraded.")
elif partitions > 10_000:
print("WARNING: Partition count approaching problematic range.")
else:
print("OK: Partition count is healthy.")
return partitionsThe rule of thumb: tables with more than 100,000 partitions will exhibit query planning degradation. Tables with more than 1 million partitions are operationally dangerous.
🧊 Why Modern Table Formats Exist
Traditional Hive-style lakes were designed around directory listing and partition discovery.
At small scale, that model works.
At large scale, it collapses under metadata pressure.
A query against a Hive table often requires:
- recursively listing partition directories
- discovering files dynamically
- querying the metastore for partition mappings
- planning execution from millions of physical objects
This is why modern lakehouse table formats exist.
Delta Lake, Iceberg, and Hudi are not just storage formats.
They are metadata scaling systems.
Their real innovation is not ACID transactions.
It is replacing expensive directory discovery with structured metadata layers optimized for large-scale planning.
Delta Lake
Delta stores transaction state in an append-only transaction log (_delta_log).
Every write operation records:
- added files
- removed files
- schema changes
- statistics
This allows Spark to determine table state without recursively scanning object storage.
The trade-off:
large Delta tables can accumulate massive transaction logs, requiring periodic checkpointing to compact metadata state.
JSON commit logs
→ periodic Parquet checkpoints
→ reconstructed table stateApache Iceberg
Iceberg pushes metadata scaling further.
Instead of relying primarily on directory structure, Iceberg uses:
- manifest files
- manifest lists
- snapshot metadata trees
Queries resolve table state through metadata indirection layers rather than partition enumeration.
This makes Iceberg particularly strong for:
- very large partition counts
- multi-engine interoperability
- hidden partitioning
- large-scale metadata pruning
Iceberg was designed explicitly to solve metadata scalability limitations in Hive-style lakes.
Apache Hudi
Hudi focuses heavily on incremental processing and upsert-heavy workloads.
Its indexing layer enables:
- record-level updates
- incremental pull queries
- near-real-time ingestion patterns
This makes Hudi attractive for CDC-heavy architectures and continuously mutating datasets.
The trade-off is operational complexity:
index maintenance and compaction become significant concerns at large scale.
The Important Insight
These systems are fundamentally solving:
metadata scalability,
not just transactional guarantees.
The storage layer stopped being “files in S3” years ago.
Modern lakehouses are metadata systems that happen to store data in object storage.
Read Amplification
Even with healthy file sizes and reasonable partition counts, a lake can be expensive to query if the data within files is organized poorly.
Predicate Pushdown Only Works When Files Are Sized Right
Parquet stores min/max statistics per row group. When Spark reads a Parquet file, it can skip entire row groups based on filter predicates — without reading the data. This is called predicate pushdown.
But predicate pushdown only works at the row group level within a file. If your files are 10 MB with one row group each, Spark must open 1,000 files to scan 10 GB — and predicate pushdown skips nothing, because each file contains exactly one row group.
If those same 10 GB are stored in 10 files of 1 GB each, each with many row groups — Spark opens 10 files, and predicate pushdown skips the majority of row groups that don’t match the filter. Read amplification drops dramatically.
Column Pruning Doesn’t Help Row-Oriented Files
Column pruning — reading only the columns a query needs — is one of Parquet’s most powerful cost reduction features. A query selecting 3 columns from a 50-column table reads roughly 6% of the total bytes.
This does not work on CSV, JSON, or any row-oriented format. Spark must read the entire row to extract the columns it needs. At scale, that difference is not a performance concern. It is the primary cost driver.
# Verify column pruning is working via the query plan
df = spark.read.parquet("s3://bucket/events/") \
.select("user_id", "event_type", "timestamp") \
.filter("event_date = '2026-05-01'")
df.explain(mode="formatted")
# Look for: PushedFilters, ReadSchema (should list only selected columns)
# If ReadSchema lists all 50 columns: column pruning is not workingFix #1: Enforce File Size at Write Time
The cheapest compaction is the kind you never need to run. Write correctly-sized files from the start.
For Delta Lake, optimizeWrite automatically coalesces small files during the write operation:
spark.conf.set("spark.databricks.delta.optimizeWrite.enabled", "true")
spark.conf.set("spark.databricks.delta.optimizeWrite.binSize", "512") # MB
df.write \
.format("delta") \
.option("optimizeWrite", "true") \
.partitionBy("event_date", "region") \
.mode("append") \
.save("s3://bucket/events/")For non-Delta Parquet, control file size via repartitioning before write:
target_file_size_bytes = 512 * 1024 * 1024 # 512 MB
estimated_data_size = df.rdd.rawSize()
num_files = max(1, estimated_data_size // target_file_size_bytes)
df.repartition(num_files) \
.write \
.option("compression", "snappy") \
.parquet("s3://bucket/events/")Fix #2: Run Compaction Pipelines
For tables that already have a small files problem, compaction is the remediation.
Delta Lake’s OPTIMIZE command compacts small files into larger ones with bin-packing:
from delta.tables import DeltaTable
def compact_table(table_path: str, partition_filter: str = None):
dt = DeltaTable.forPath(spark, table_path)
optimize = dt.optimize()
if partition_filter:
optimize = optimize.where(partition_filter)
result = optimize.executeCompaction()
metrics = result.select(
"metrics.numFilesAdded",
"metrics.numFilesRemoved",
"metrics.filesAdded.avg",
"metrics.filesRemoved.avg"
).collect()[0]
print(f"Files removed: {metrics.numFilesRemoved}")
print(f"Files added: {metrics.numFilesAdded}")
print(f"Avg size before: {metrics['filesRemoved.avg'] / 1e6:.1f} MB")
print(f"Avg size after: {metrics['filesAdded.avg'] / 1e6:.1f} MB")
# Remove obsolete files (default: 7-day retention)
dt.vacuum(retentionHours=168)For Z-ordering on high-selectivity columns — which collocates related data within files to maximize predicate pushdown effectiveness:
dt.optimize() \
.where("event_date >= '2026-01-01'") \
.executeZOrderBy("user_id", "event_type")Z-ordering is not free. It requires a full rewrite of the affected files. Run it on columns that appear in WHERE clauses and JOIN conditions — not on every column.
Fix #3: Rethink Your Partition Strategy
The correct partition strategy depends on your dominant query pattern — not on what seemed logical when you designed the table.
Design rule: partition on the column your queries filter on most frequently, at a granularity that produces partitions of at least 1 GB each.
If daily partitioning produces partitions smaller than 1 GB, move to weekly or monthly. The cost of over-partitioning — in metastore overhead and small files — exceeds the benefit of partition pruning for small datasets.
# Before: daily + region + category → 3.6M partitions at modest scale
df.write.partitionBy("event_date", "region", "product_category")
# After: monthly + region only → manageable partition count
# Use Z-ordering to handle category selectivity within files
df.withColumn("event_month", F.date_format("event_date", "yyyy-MM")) \
.write \
.partitionBy("event_month", "region") \
.format("delta") \
.save(table_path)
# Then Z-order within partitions on the high-selectivity columns
dt.optimize().executeZOrderBy("product_category", "user_id")This pattern — coarse partitioning for partition pruning, Z-ordering for within-partition selectivity — is the mature approach that balances metastore cost against query performance.
Fix #4: Implement Storage Tiering
Not all data in a data lake is accessed equally. Most access patterns follow a steep recency curve: recent data is queried frequently, historical data is queried rarely.
Paying hot storage prices for cold data is pure waste.

S3 Intelligent-Tiering automates this for objects over 128 KB — it monitors access patterns and moves objects between tiers automatically, with no retrieval fees for Frequent and Infrequent Access tiers:
# Apply lifecycle policy via boto3 (or IaC)
import boto3
s3 = boto3.client("s3")
s3.put_bucket_lifecycle_configuration(
Bucket="your-data-lake-bucket",
LifecycleConfiguration={
"Rules": [
{
"ID": "intelligent-tiering-raw",
"Filter": {"Prefix": "raw/"},
"Status": "Enabled",
"Transitions": [
{"Days": 30, "StorageClass": "INTELLIGENT_TIERING"}
]
},
{
"ID": "archive-cold-data",
"Filter": {"Prefix": "archive/"},
"Status": "Enabled",
"Transitions": [
{"Days": 365, "StorageClass": "DEEP_ARCHIVE"}
]
}
]
}
)For a lake with 500 TB total where 80% is older than 90 days, tiering alone can reduce the storage bill by 50–60%.
Fix #5: Vacuum Dead Files Aggressively
Delta Lake and Iceberg maintain old file versions for time travel. Every MERGE, UPDATE, or DELETE creates new files without deleting the old ones immediately. Those obsolete files accumulate silently.
from delta.tables import DeltaTable
def vacuum_table(table_path: str, retention_hours: int = 168):
dt = DeltaTable.forPath(spark, table_path)
# Check how many files would be removed
spark.conf.set("spark.databricks.delta.vacuum.logging.enabled", "true")
spark.conf.set("spark.databricks.delta.retentionDurationCheck.enabled", "false")
# Dry run first
dt.vacuum(retentionHours=retention_hours)
# Run VACUUM on a schedule — weekly minimum for high-churn tables
# Daily for tables with frequent MERGE/UPDATE operationsThe default retention is 7 days (168 hours). Reducing it below 7 days risks breaking concurrent readers — do not go below 24 hours in production without fully understanding your access patterns.
For high-churn tables (frequent MERGE operations), vacuum weekly. Left unrun, obsolete files from Delta operations can double or triple your storage cost within months.
Fix #6: Use Table Statistics
Without statistics, Spark’s query planner makes worst-case assumptions. It over-allocates resources, chooses sort-merge joins when broadcast joins would work, and misestimates partition sizes.
Collecting and maintaining statistics costs a small amount of compute upfront and saves significant query cost continuously:
# Collect table-level and column-level statistics
spark.sql("""
ANALYZE TABLE events
COMPUTE STATISTICS FOR COLUMNS
user_id, event_type, event_date, region
""")
# For Delta tables, enable automatic statistics collection
spark.conf.set(
"spark.databricks.delta.autoOptimize.autoCompact", "true"
)
spark.conf.set(
"spark.databricks.delta.properties.defaults.autoOptimize.optimizeWrite",
"true"
)With accurate statistics, AQE can make better runtime decisions — converting sort-merge joins to broadcast joins when one side is smaller than the planner estimated, and coalescing partitions more aggressively when actual data sizes are known.
The Compound Cost Model
Data lake costs are not linear. They compound in both directions.
Small files increase query time. Longer queries require larger clusters. Larger clusters cost more per hour. The cost of one poorly-designed partition strategy is not the storage cost of that partition. It is the compute cost of every query that has ever touched that table, multiplied by how long the problem went undetected.
The reverse is also true. Compaction reduces file count, which reduces query planning time, which reduces cluster-hours required, which reduces cost faster than the storage savings alone would suggest.
Before optimization (50 TB table, 2M files):
Storage: $1,150/month
Query compute: $5,800/month (clusters fighting the metadata overhead)
Total: $6,950/month
After optimization (same 50 TB, 48K files, tiered storage):
Storage (tiered): $520/month
Query compute: $780/month
Total: $1,300/month
Net reduction: ~81%The storage savings were $630/month. The compute savings were $5,020/month. The root cause of the compute cost was always the storage structure.
Trade-offs
Aggressive compaction vs write freshness. Compaction rewrites files. While compaction is running on a partition, concurrent reads may see partially-compacted state. For tables with strict read-while-write requirements, schedule compaction during low-traffic windows.
Fine-grained partitioning vs metastore cost. Finer partitions give better query pruning but create more metastore records. The crossover point — where partition overhead exceeds pruning benefit — depends on data volume per partition. The heuristic: if a partition is smaller than 500 MB, it is probably too fine-grained.
Z-ordering vs write throughput. Z-ordering is a full rewrite of the affected files. It improves selective read performance significantly but adds write latency. Run it on a separate schedule from your ingestion pipeline — not inline.
Storage tiering vs retrieval cost. Glacier and Deep Archive have retrieval fees and retrieval latency. Do not tier data that has a non-trivial chance of being queried within the retention window. Intelligent-Tiering is the right default for uncertain access patterns — it handles the decision automatically.
Operational Lessons
Audit file count and partition count before symptoms appear. A table crossing 100,000 partitions or 1 million files is a warning sign — not a crisis yet, but heading toward one. Set alerts on these thresholds.
Treat compaction as infrastructure, not maintenance. Compaction is not a one-time cleanup. It is a continuous operational responsibility for any table that receives regular writes. Schedule it. Monitor it. Alert when it falls behind.
The partition strategy you design at 10 GB will not survive at 10 TB. Build a partition review into your table design process — explicitly ask: what does this partition structure look like at 100× current volume?
Storage cost and query cost are a system. Optimizing one in isolation makes the other worse. The goal is minimizing total cost of ownership — storage plus compute — not minimizing either metric independently.
🧠 Why Teams Keep Recreating These Problems
Most expensive data lakes are not caused by bad engineers.
They are caused by organizational incentives that optimize for shipping pipelines — not maintaining storage architecture over time.
The ingestion team optimizes for delivery speed.
The analytics team optimizes for query flexibility.
The platform team optimizes for infrastructure stability.
Nobody is explicitly responsible for:
- file count growth
- partition health
- compaction SLAs
- lifecycle policies
- metadata scalability
So the problems compound silently.
The Common Failure Pattern
A pipeline launches at small scale.
The partition strategy is reasonable for current volume.
Compaction is deferred “until later.”
Lifecycle policies are never added because the data may still be useful someday.
The system works.
Then:
- ingestion volume grows
- query frequency increases
- new teams begin consuming the data
- backfills create millions of additional files
- operational ownership becomes fragmented
The lake slowly becomes expensive to operate — not because any single decision was catastrophic, but because no team owned the long-term structure.
Why This Happens Repeatedly
Storage architecture problems grow sublinearly at first.
At 100 GB:
poor partitioning is invisible.
At 10 TB:
it becomes annoying.
At 100 TB:
it becomes operationally expensive.
At 1 PB:
it becomes architectural debt that can require a full platform migration.
The dangerous part is that the feedback loop is delayed by months or years.
Teams inherit the consequences long after the original design decisions were made.
Mature Platforms Treat Structure as Infrastructure
The strongest data platforms operationalize:
- compaction schedules
- partition reviews
- metadata monitoring
- file count budgets
- lifecycle enforcement
- ownership boundaries
Because data lakes do not remain healthy accidentally.
Their structure either evolves intentionally —
or degrades continuously.
🚀 Final Takeaway
A data lake gets expensive not because data is large, but because data is unstructured.
Millions of small files. Millions of unnecessary partitions. Cold data stored at hot prices. Statistics that were never collected. Files that were never compacted. Obsolete versions that were never vacuumed.
None of these failures announce themselves. The bill just grows. Queries just get slower. Engineers add more compute to compensate — and the underlying structure gets more expensive to maintain.
📌 Core Principle
You are not paying for storage.
You are paying for every design decision that made your data expensive to read.
Fix the structure. The bill follows.
🔥 Next in Series
🔍 Designing a Real-Time Fraud Detection System (End-to-End)
The data lake is optimized. The pipelines are cost-efficient.
Now the business wants decisions in 50 milliseconds.
Next, we design a fraud detection system from ingestion to inference — end-to-end:
- event ingestion at 40,000 transactions per second
- real-time feature computation under strict latency budgets
- online feature store design and consistency guarantees
- model serving within the authorization window
- failure modes that cost money in both directions
Because fraud detection is the sharpest edge case in data engineering: wrong in one direction, fraudulent transactions pass. Wrong in the other direction, legitimate transactions are blocked. And you have under 100 milliseconds to be right.
🔔 Follow for More
Follow TheDataForge for high-signal deep dives on Spark, Kafka, Streaming, Lakehouse, and real-world data engineering — no fluff, only engineering truth.
⚡️Let’s connect — I post daily Big Data & Spark insights at DataForgeX on X.
💬 Comment Below
What’s the most expensive structural mistake you’ve found in a data lake?
Millions of small files from a streaming pipeline nobody audited? A partition strategy designed at 10 GB still running unchanged at 50 TB? Cold data paying hot storage prices because nobody set a lifecycle policy?
Or have you done a lake optimization pass and found the compute savings dwarfed the storage savings?
👇 Real numbers from engineers who’ve opened the cloud bill and traced it back to a partition column.
🏷️ Tags
#data-engineering #data-lake #apache-spark #cost-optimization #delta-lake #cloud-infrastructure #big-data #storage-architecture #production-engineering #system-design