Object Storage, Partitioning and the Small-Files Problem
Model why a rename on object storage is a copy and a delete per object, land a streaming job as 1,344 small Parquet files in a Hive-style layout, prove partition pruning with DuckDB, measure the small-files overhead, and fix it with a sorted compaction.
Contentsand lesson path
On this page
- The problem
- Step 1: Object storage is not a file system
- Step 2: Land the events the way the streaming job does
- Step 3: Measure what the layout costs
- Step 4: Prove what partition pruning skips
- Step 5: Compact each partition into one sorted file
- Step 6: Let sorting and statistics skip row groups
- Common mistakes
- Check your understanding
- Apply it
- Review prompt
Lessons of File & Table Formats
- Row vs Columnar: Inside Avro and Parquet Concept · 25 min
- Lab: The Same Data as CSV, Avro and Parquet Lab · 25 min
- Object Storage, Partitioning and the Small-Files Problem Worked example · 30 min
- Table Formats: Snapshots, Manifests and Atomic Commits Concept · 25 min
- Lab: Evolve, Time-Travel and Compact an Iceberg Table Lab · 30 min
- Check: Review a Storage Layout Knowledge check · 6 questions
What you will learn
- Explain how object storage differs from a distributed file system such as HDFS, lay out data with partitioning, sorting and target file sizes so engines can prune it, and fix a small-files problem with compaction.
01. The problem
A streaming job writes click events to a data lake on object storage every 15 minutes, one Parquet file per day folder per run. After two weeks the table has 1,344 files, a query for one user on one day is slow, and the bill shows far more requests than expected. Your task: explain where the time and requests go, and change the layout so that engines can skip most of the data.
You will see how object storage differs from a file system, build the slow layout, measure it, prove what partition pruning fixes, compact the files, and sort them so that statistics can skip data inside each file. Everything runs locally with Python 3.12, PyArrow 26.0.1 and DuckDB 1.5.6. A local folder stands in for the bucket, and step 1 is a clearly labelled simulation.
mkdir lake-layout && cd lake-layout
python3.12 -m venv .venv && source .venv/bin/activate
python -m pip install pyarrow==26.0.1 duckdb==1.5.602. Step 1: Object storage is not a file system
HDFS, the Hadoop Distributed File System, is a real file system spread over many machines. One server, the NameNode, keeps the whole directory tree, while DataNodes store file contents in large blocks (128 MB is typical). Renaming a directory is one change to the NameNode's tree, however many files it holds, and other clients see either the old name or the new one. Classic Hadoop and Hive jobs used this as their commit: write to a temporary directory, then rename it into place.
An object store such as Amazon S3, Google Cloud Storage or Azure Blob Storage is a flat map from a key (a string such as lake/events/event_date=2026-03-05/batch-007.parquet) to an immutable object. The "folders" in a console are only shared key prefixes, and a list request returns at most 1,000 keys. A general-purpose S3 bucket has no rename call, so tools copy each object to its new key and delete the old one. The Hadoop S3A documentation states the result: directory renames take time proportional to the number and size of the files, and they are not atomic. The model below counts the requests. It is a simulation, not a client for a real service.
"""A toy model of an object store and of a file system namespace.
This is a simulation for counting requests, not a client for a real service.
"""
class ObjectStore:
"""Flat keys -> bytes. Folders are only shared key prefixes."""
def __init__(self):
self.objects = {}
self.requests = {"LIST": 0, "COPY": 0, "DELETE": 0}
def put(self, key, data):
self.objects[key] = data
def list(self, prefix):
keys = sorted(k for k in self.objects if k.startswith(prefix))
self.requests["LIST"] += max(1, -(-len(keys) // 1000)) # pages
return keys
def rename_prefix(self, old, new, fail_after=None):
"""There is no rename: copy every object, then delete the old ones."""
for i, key in enumerate(self.list(old)):
if i == fail_after:
raise RuntimeError(f"client crashed after {i} copies")
self.requests["COPY"] += 1
self.objects[new + key[len(old):]] = self.objects[key]
for key in self.list(old):
self.requests["DELETE"] += 1
del self.objects[key]
class Namespace:
"""A directory tree like the one the HDFS NameNode keeps."""
def __init__(self):
self.tree = {}
self.operations = 0
def rename_dir(self, old, new):
self.operations += 1
self.tree[new] = self.tree.pop(old)
def staged_store(run):
store = ObjectStore()
for i in range(2_500):
store.put(f"lake/tmp/{run}/part-{i:05d}.parquet", b"x")
return store
store = staged_store("run-7")
store.rename_prefix("lake/tmp/run-7/", "lake/events/")
print("object store, rename 2,500 objects:", store.requests)
fs = Namespace()
fs.tree["/lake/tmp/run-7"] = [f"part-{i:05d}.parquet" for i in range(2_500)]
fs.rename_dir("/lake/tmp/run-7", "/lake/events")
print("namespace, rename a 2,500-file directory:", fs.operations, "operation")
crash = staged_store("run-8")
try:
crash.rename_prefix("lake/tmp/run-8/", "lake/events/", fail_after=1_200)
except RuntimeError as err:
print("crash:", err)
print("keys under the new prefix:", len(crash.list("lake/events/")),
"| still under the old prefix:", len(crash.list("lake/tmp/run-8/")))python objstore_sim.pyobject store, rename 2,500 objects: {'LIST': 6, 'COPY': 2500, 'DELETE': 2500}
namespace, rename a 2,500-file directory: 1 operation
crash: client crashed after 1200 copies
keys under the new prefix: 1200 | still under the old prefix: 2500The "rename" cost 2,500 copies, 2,500 deletes and six list pages (three before copying, three before deleting). A batch delete of up to 1,000 keys per request cuts the deletes, but every copy remains. The crash is worse: a reader that lists lake/events/ now sees 1,200 files of a half-finished job. Some newer services add narrow exceptions, such as RenameObject for single objects in S3 Express One Zone directory buckets, but an atomic directory rename is not something you can rely on.
Two more properties shape lake design. S3 gives strong read-after-write consistency: a new object is visible to the next read and list. And you pay per request as well as per byte, so one request per tiny file costs money even when the bytes are few. In the infrequent-access classes of S3, an object under 128 KB is billed as 128 KB.
03. Step 2: Land the events the way the streaming job does
The script simulates 14 days of the streaming job: 96 runs per day, each writing 150 events as one Parquet file. It uses Hive-style partitioning: the folder name event_date=2026-03-05 carries the value of the partition column, so the column does not need to be stored inside the files and engines can read it from the path.
"""Simulate a streaming job: every 15 minutes it writes one small file."""
import random
from datetime import date, timedelta
from pathlib import Path
import pyarrow as pa
import pyarrow.parquet as pq
rng = random.Random(7)
root = Path("lake/events")
EVENTS = ["view", "click", "add_to_cart", "purchase"]
N = 150 # events per run
for d in range(14):
day = date(2026, 3, 1) + timedelta(days=d)
folder = root / f"event_date={day.isoformat()}" # Hive-style key=value
folder.mkdir(parents=True, exist_ok=True)
for run in range(96): # 24 hours x 4 runs per hour
first = (d * 96 + run) * N
table = pa.table({
"event_id": pa.array(range(first, first + N), pa.int64()),
"minute": pa.array([run * 15 + rng.randrange(15)
for _ in range(N)], pa.int16()),
"user_id": pa.array([rng.randrange(1, 50_001) for _ in range(N)],
pa.int64()),
"event": pa.array([rng.choice(EVENTS) for _ in range(N)]),
"value_cents": pa.array([rng.randrange(20_000) for _ in range(N)],
pa.int32()),
})
pq.write_table(table, folder / f"batch-{run:03d}.parquet")
files = sorted(root.rglob("*.parquet"))
print("partitions:", len(list(root.iterdir())), "| files:", len(files))
for f in files[:2]:
print(" ", f.as_posix())python land_small_files.pypartitions: 14 | files: 1344
lake/events/event_date=2026-03-01/batch-000.parquet
lake/events/event_date=2026-03-01/batch-001.parquet04. Step 3: Measure what the layout costs
Measure before you change anything. The script counts files, rows and bytes, adds up every footer plus its 8 trailing bytes (footer length and PAR1), and prints a simple request model for a full scan on object storage: list pages, plus at least two reads per file, one for the footer and one for the data.
"""Measure a layout: files, sizes, footer overhead, modelled requests."""
import sys
from pathlib import Path
import pyarrow.parquet as pq
root = Path(sys.argv[1])
files = sorted(root.rglob("*.parquet"))
meta = [pq.ParquetFile(f).metadata for f in files]
total = sum(f.stat().st_size for f in files)
rows = sum(m.num_rows for m in meta)
footers = sum(m.serialized_size + 8 for m in meta)
lists = -(-len(files) // 1000)
print(f"{root}: {len(files):,} files, {rows:,} rows, {total:,} bytes")
print(f" average file: {total // len(files):,} bytes, "
f"{rows // len(files):,} rows")
print(f" footers: {footers:,} bytes ({footers / total:.0%} of all bytes)")
print(f" full scan on object storage: >= {lists} LIST + "
f"{2 * len(files):,} GET requests")python inspect_layout.py lake/eventslake/events: 1,344 files, 201,600 rows, 5,640,584 bytes
average file: 4,196 bytes, 150 rows
footers: 1,564,416 bytes (28% of all bytes)
full scan on object storage: >= 2 LIST + 2,688 GET requestsEach file holds 150 rows, about 4 KB, and 28% of all bytes are footers, metadata that every file carries whatever its size. A full scan needs at least 2,688 read requests to fetch 5.6 MB. On object storage every request is a network round trip, so the time goes into waiting, not reading. Short column chunks also encode and compress worse. This is the small-files problem: per-file costs (listing, opening, reading footers, planning tasks) outweigh per-byte costs. Fix it at the source where you can, by writing larger batches less often, and compact what remains.
05. Step 4: Prove what partition pruning skips
Partition pruning means skipping whole folders whose partition value cannot match the filter, using only their paths. DuckDB does this when you pass hive_partitioning = true. To prove which files were read rather than guess, the script turns on DuckDB's JSON profiler and prints what the Parquet scan reports about its files.
"""Run one query with DuckDB and report what the Parquet scan touched."""
import json
import sys
import duckdb
layout = sys.argv[1]
sql = f"""
SELECT count(*) AS events, sum(value_cents) AS cents
FROM read_parquet('{layout}/*/*.parquet', hive_partitioning = true)
WHERE event_date = DATE '2026-03-05' AND user_id = 1337
"""
con = duckdb.connect()
con.execute("SET enable_profiling = 'json'")
con.execute("SET profiling_output = 'profile.json'")
print("result:", con.execute(sql).fetchall())
def find_scan(node):
if node.get("operator_name") in ("READ_PARQUET", "TABLE_SCAN"):
return node
for child in node.get("children", []):
if (hit := find_scan(child)) is not None:
return hit
return None
with open("profile.json") as f:
info = find_scan(json.load(f))["extra_info"]
for key in ["File Filters", "Filters", "Scanning Files", "Total Files Read"]:
print(f" {key}: {info.get(key)}")python query.py lake/eventsresult: [(4, 33662)]
File Filters: (event_date = '2026-03-05'::DATE)
Filters: user_id=1337
Scanning Files: 96/1344
Total Files Read: 96The File Filters line shows the date filter applied to paths: DuckDB scanned 96 of 1,344 files, those in event_date=2026-03-05. Pruning cannot help with user_id, an ordinary filter inside the files, and it cannot shrink the 96 files of the chosen day. It reduces how many partitions you touch, not how many files each one holds.
06. Step 5: Compact each partition into one sorted file
Compaction rewrites many small files into fewer large ones holding the same rows. The script reads each partition, sorts it by user_id, and writes one file per partition into a new prefix, with row groups of 2,000 rows so that step 6 can show statistics at work. In production, aim for files of a few hundred megabytes: the Parquet documentation recommends row groups of 512 MB to 1 GB, and Iceberg's default target file size is 512 MB. Here a day is only 14,400 rows, so one file per day is right. The script then checks that nothing was lost or duplicated.
"""Compact each partition into one file sorted by user_id, then verify."""
from pathlib import Path
import duckdb
import pyarrow.parquet as pq
src, dst = Path("lake/events"), Path("lake/events_compacted")
for part in sorted(src.iterdir()):
table = pq.read_table(part) # every small file of this partition
table = table.sort_by([("user_id", "ascending"), ("event_id", "ascending")])
(dst / part.name).mkdir(parents=True, exist_ok=True)
pq.write_table(table, dst / part.name / "part-0.parquet",
row_group_size=2_000)
check = """
SELECT count(*), sum(value_cents), count(DISTINCT event_id)
FROM read_parquet('{}/*/*.parquet', hive_partitioning = true)
"""
before = duckdb.sql(check.format(src)).fetchall()
after = duckdb.sql(check.format(dst)).fetchall()
print("before:", before)
print("after: ", after)
print("same rows:", before == after)python compact.py
python inspect_layout.py lake/events_compacted
python query.py lake/events_compactedbefore: [(201600, 2014583922, 201600)]
after: [(201600, 2014583922, 201600)]
same rows: True
lake/events_compacted: 14 files, 201,600 rows, 4,011,996 bytes
average file: 286,571 bytes, 14,400 rows
footers: 69,076 bytes (2% of all bytes)
full scan on object storage: >= 1 LIST + 28 GET requests
result: [(4, 33662)]
File Filters: (event_date = '2026-03-05'::DATE)
Filters: user_id=1337
Scanning Files: 1/14
Total Files Read: 1The same 201,600 rows now sit in 14 files. Footers fell from 28% to 2% of the bytes, the table shrank by about 29% because longer chunks encode better, and the modelled full scan fell from 2,688 to 28 reads. The one-day query reads one file instead of 96, with the same result.
What compaction did not solve: the new files sit under a new prefix. Making readers use them means "renaming" events_compacted/ to events/, which step 1 showed is thousands of copies and deletes, with a window in which readers see both versions or neither. Compacting in place has the same problem: between writing the new file and deleting the old ones, a query can count every event twice. Plain folders cannot swap many files at once. Table formats such as Iceberg and Delta Lake can, which is the subject of the next lesson.
07. Step 6: Let sorting and statistics skip row groups
Partitioning on user_id would be a mistake: 50,000 users would mean 50,000 folders per day of a few rows each. A good partition column has a modest number of values that most queries filter on, here the date. A column with many values is handled by sorting (or clustering) inside each partition, so that each row group's min/max range is narrow. Count the row groups a reader could not rule out for user 1337 on 5 March, before and after compaction.
"""Count the row groups whose user_id min/max range could hold user 1337."""
import sys
from pathlib import Path
import pyarrow.parquet as pq
USER = 1337
for layout in sys.argv[1:]:
files = sorted(Path(layout, "event_date=2026-03-05").glob("*.parquet"))
total = candidates = 0
for f in files:
md = pq.ParquetFile(f).metadata
col = md.schema.names.index("user_id")
for i in range(md.num_row_groups):
stats = md.row_group(i).column(col).statistics
total += 1
candidates += stats.min <= USER <= stats.max
print(f"{layout}: {candidates} of {total} row groups may hold user {USER}")python row_groups.py lake/events lake/events_compactedlake/events: 95 of 96 row groups may hold user 1337
lake/events_compacted: 1 of 8 row groups may hold user 1337In the small files, each file holds a random sample of users, so 95 of 96 row groups span a range that includes 1337. In the sorted file, each row group covers about an eighth of the user ids, so only 1 of 8 can match. The date partition plus statistics on a sorted column took the query from 1,344 files to one row group. For filters on several columns, engines offer multi-column orderings such as Z-order.
08. Common mistakes
09. Check your understanding
10. Apply it
Apply this to your practice dataset once it is in Parquet:
- Write it partitioned by day with
pyarrow.dataset.write_dataset(..., partitioning=["day"], partitioning_flavor="hive")and runinspect_layout.pyon it. If the average file is well under 100 MB, decide between monthly partitions and daily partitions plus compaction. - Sort each partition by the column of your second most common filter, and adapt
row_groups.pyto show how many row groups a typical value can skip. - Run one practice query with an adapted
query.pyon both layouts and recordScanning FilesandTotal Files Read.
11. Review prompt
Without looking back:
- Why is a directory rename one cheap atomic operation on HDFS but thousands of requests on a general-purpose S3 bucket?
- What did partition pruning skip in step 4, and what could it not skip?
- Name three costs that grow with the number of files rather than with the number of bytes.
- Why did sorting by
user_idhelp the query, while partitioning byuser_idwould hurt it? - Why is swapping compacted files into place unsafe without a table format?
References
- Amazon S3 User Guide: What is Amazon S3? (data consistency model)
- Amazon S3 User Guide: Naming objects (flat key structure)
- Amazon S3 API Reference: ListObjectsV2
- Amazon S3 API Reference: RenameObject
- Amazon S3 pricing
- Apache Hadoop: HDFS Architecture
- Apache Hadoop: Hadoop-AWS module (S3A) and rename semantics
- Apache Parquet: Configurations (row group size)
- DuckDB: Hive partitioning
- Apache Iceberg: Configuration (write.target-file-size-bytes)
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.