Sub topic 13
Controlling file and row group sizes
This chapter assumes you can write and read a partitioned dataset with ds.write_dataset and ds.dataset. It also assumes you know that a Parquet file holds row groups, and that each row group holds one column chunk per column. Here you will learn which write_dataset options set the size of files and row groups, how to check what was written, and how to repair a dataset that has too many small files.
Why sizes matter
A Parquet file is split into row groups, and each row group stores one column chunk per column. Two sizes affect read performance.
- File size. Every file costs a directory listing entry, an open call, and a footer read. On local disks this is cheap. On object stores such as S3, each file adds network round trips. Thousands of tiny files make planning and scanning slow, even when the total data is small.
- Row group size. A row group is the unit of parallel reading and of min/max statistics. Small row groups give finer skipping but add metadata and compress worse. Very large row groups need more memory to read and to write, because the writer buffers a whole group before flushing it.
The writer options
| Option | Default | Effect |
|---|---|---|
| `max_rows_per_file` | 0 (no limit) | Starts a new file in the same directory once this many rows are written. |
| `max_rows_per_group` | 1,048,576 | Splits large incoming batches into row groups of at most this many rows. |
| `min_rows_per_group` | 0 | Buffers small batches until at least this many rows are available, then writes a group. |
| `max_open_files` | 1024 | Caps how many output files are open at once across all partitions. |
| `basename_template` | `part-{i}.parquet` | Names files. `{i}` is a counter. |
Check the defaults against your installed PyArrow version, because they can change between releases.
Keep max_rows_per_group no larger than max_rows_per_file. A row group cannot span files, so a larger group limit has no effect. If you set max_rows_per_group, set min_rows_per_group too, so that many small input batches do not turn into many tiny row groups.
Seeing the effect on a small dataset
The numbers below are tiny so you can see the splitting. Real datasets use much larger limits.
import pyarrow as pa
import pyarrow.dataset as ds
import pyarrow.parquet as pq
n = 10_000
table = pa.table({
"id": pa.array(range(n), type=pa.int64()),
"value": pa.array([float(i) for i in range(n)], type=pa.float64()),
})
ds.write_dataset(
table,
"sizes_demo",
format="parquet",
max_rows_per_file=4_000,
min_rows_per_group=1_000,
max_rows_per_group=2_000,
existing_data_behavior="overwrite_or_ignore",
)
dataset = ds.dataset("sizes_demo", format="parquet")
for path in sorted(dataset.files):
meta = pq.ParquetFile(path).metadata
print(path, meta.num_rows, "rows,", meta.num_row_groups, "row groups")The writer fills a file up to 4,000 rows, cutting row groups at 2,000 rows. You should see three files with 4,000, 4,000 and 2,000 rows, holding 2, 2 and 1 row groups.
Checking what was written with file_visitor
Reopening files works, but write_dataset can report each file as it is finished. Pass a file_visitor callable. It receives a WrittenFile object with the path and, for Parquet, a metadata attribute.
import pyarrow as pa
import pyarrow.dataset as ds
table = pa.table({
"country": ["DE", "FR", "DE", "FR", "DE", "FR"] * 1_000,
"amount": [1.0, 2.0, 3.0, 4.0, 5.0, 6.0] * 1_000,
})
written = []
def visit(f):
written.append((f.path, f.metadata.num_rows, f.metadata.num_row_groups))
ds.write_dataset(
table,
"sizes_visitor",
format="parquet",
partitioning=ds.partitioning(
pa.schema([("country", pa.string())]), flavor="hive"
),
max_rows_per_file=1_500,
max_rows_per_group=1_500,
min_rows_per_group=500,
file_visitor=visit,
existing_data_behavior="overwrite_or_ignore",
)
for path, rows, groups in sorted(written):
print(path, rows, groups)Each country holds 3,000 rows, so each partition directory gets two files of 1,500 rows. Collecting this list in a pipeline is a cheap way to log file counts and sizes on every run.
How max_open_files fragments data
The writer keeps one open file per partition it is currently writing to. When the number of open files reaches max_open_files, it closes the least recently used one. If later rows arrive for that partition, the writer opens a new file in the same directory. The result is many small files.
This happens when the input is not grouped by partition key and there are many distinct keys. For example, a table sorted by timestamp but partitioned by customer_id touches every customer all the time.
You have three ways to avoid it:
- Sort or group the input by the partition columns before writing.
- Write in several passes, each handling a subset of the keys.
- Raise
max_open_files. The operating system's open-file limit and memory use (each open file holds buffers) set the ceiling.
Choosing target sizes
These are rules of thumb, not guarantees. Measure on your own data and storage.
- Files: aim for roughly 128 MB to 1 GB on disk. Below about 10 MB, per-file overhead usually dominates, especially on object storage.
- Row groups: aim for roughly 100,000 to 1,000,000 rows, or about 64 to 256 MB uncompressed. Wide tables with many columns may need fewer rows per group to stay in that byte range.
- Rows versus bytes: the options count rows, not bytes. Estimate bytes per row from a sample file (file size divided by
num_rows), then derive row limits from your byte target.
A rough sizing helper:
import os
import pyarrow.parquet as pq
def rows_for_target(sample_path, target_bytes):
rows = pq.ParquetFile(sample_path).metadata.num_rows
bytes_per_row = os.path.getsize(sample_path) / rows
return int(target_bytes / bytes_per_row)
# Example: rows needed for a 256 MB file, based on one existing sample file
# print(rows_for_target("sizes_demo/part-0.parquet", 256 * 1024 * 1024))The compressed on-disk size depends on the data, so a sample from one partition may not match the others.
Compacting a dataset with many small files
To fix an existing dataset, read it and write it to a new location with larger limits. Streaming through a scanner keeps memory use bounded. Do not write into the directory you are reading from.
import pyarrow.dataset as ds
source = ds.dataset("sizes_visitor", format="parquet", partitioning="hive")
ds.write_dataset(
source.scanner(batch_size=64_000),
"sizes_compacted",
format="parquet",
schema=source.schema,
partitioning=ds.partitioning(source.schema.field("country").type
and __import__("pyarrow").schema([source.schema.field("country")]),
flavor="hive"),
max_rows_per_file=1_000_000,
min_rows_per_group=100_000,
max_rows_per_group=1_000_000,
existing_data_behavior="overwrite_or_ignore",
)Writing from a scanner needs the schema argument. When the source has Hive partitioning, the country column comes from the path and is part of the dataset schema, so it is available to the new partitioning.
Common mistakes
- Setting
max_rows_per_groupabovemax_rows_per_fileand expecting bigger groups. - Setting only
max_rows_per_groupand getting many tiny groups from small input batches. Setmin_rows_per_groupas well. - Expecting
max_rows_per_fileto give equal-sized files. The last file in each directory holds the remainder. - Writing unsorted data with many partition keys and a low
max_open_files. - Rewriting a dataset into its own directory while reading it.
Exercise
You write a dataset partitioned by customer_id (50,000 distinct values) from a table sorted by timestamp, with the default max_open_files. You find about 400,000 small files. What caused it, and what are two ways to reduce the file count?
Show answer
Rows for every customer arrive throughout the input, so the writer needs about 50,000 files open at once. That is more than the 1024 limit. The writer closes the least recently used file, and later rows for that customer open a new file in the same directory. To fix this, sort or group the input by customer_id before writing, or write in several passes over subsets of customers. Raising max_open_files also works, but it is limited by the OS file descriptor limit and by the memory each open file uses. Partitioning by a column with fewer distinct values would remove the root cause.