Sub topic 9
Choosing file formats and layouts
This chapter assumes you can write basic Polars lazy queries with scan_* functions, filter, select, and group_by. It also assumes you know what CSV and Parquet files are. The earlier chapters showed that the streaming engine reads data in chunks. Here the question is what those chunks are read from. The same query can run in seconds or crawl, depending on the format and layout of the files under it.
Why the file matters
A lazy query decides what to read from the file before it reads anything. Pushdown is only useful if the file can answer questions like "which columns exist?" and "can I skip this block of rows?" without scanning everything. Formats differ a lot in how well they support this.
Three properties matter for chunked processing:
- Column access. Can the reader fetch only
user_idandamountwithout touching the other columns? - Skipping. Can the reader rule out parts of the file from metadata, such as minimum and maximum values?
- Splittability. Can the reader start in the middle of the file or read several parts in parallel?
Comparing the common formats
| Format | Layout | Column pruning | Skipping by statistics | Typical use |
|---|---|---|---|---|
| CSV | Text, row by row | No. Every row is parsed in full. | No | Exchange, raw landing zone |
| NDJSON | One JSON object per line | No | No | Logs, API dumps |
| Parquet | Binary, columnar, split into row groups | Yes | Yes, per row group | Main analytical storage |
| Arrow IPC (Feather v2) | Binary, columnar | Yes | Limited | Fast local intermediate files |
CSV and NDJSON are text. To get the third column of a CSV row, the reader must scan past the first two. Projection pushdown on CSV can avoid building the unused columns in memory, but the bytes still have to be read and tokenized. Dates and numbers are also parsed from text, which costs CPU time.
Parquet stores each column separately. A file is divided into row groups, which are blocks of rows. Each column inside a row group has min and max statistics. A filter such as amount > 1000 can skip every row group whose maximum amount is at most 1000, without decoding that block.
Arrow IPC is the same in-memory layout Polars uses, written to disk. It reads quickly and needs little decoding. It is usually larger than compressed Parquet, so it fits temporary files better than long-term storage.
Convert once, query many times
If your source data is CSV, a common pattern is to convert it once to Parquet and run all later queries against the Parquet files. The conversion itself must not need the file in memory, so use a lazy scan and a sink:
import polars as pl
(
pl.scan_csv("events.csv", infer_schema_length=10_000)
.sink_parquet(
"events.parquet",
compression="zstd",
row_group_size=100_000,
)
)This reads the CSV in chunks and writes Parquet as it goes. Two parameters deserve attention:
compression="zstd"gives a good size-to-speed balance. Smaller files mean less disk and network I/O, which often outweighs the decompression cost.row_group_sizecontrols how many rows go into each row group. It sets how fine-grained skipping can be.
infer_schema_length is a gotcha for CSV. Polars guesses column types from the first rows only. If row 500,000 contains text in a column that looked numeric before, the scan fails mid-run, possibly after a long time. For large files, pass an explicit schema or schema_overrides for columns you care about, or raise infer_schema_length. Fixing the types during conversion means the Parquet files carry a stable schema from then on.
Row group size
Row group size is a trade-off.
- Small row groups give precise skipping, because each group covers a narrow range of values. But there are more groups, more metadata, and smaller column chunks that compress worse.
- Large row groups compress well and reduce overhead. But one group may span the whole value range of a column, so statistics rule out nothing.
Row group size also affects memory use. A reader generally has to decode at least one row group of each needed column at a time. If a row group holds tens of millions of rows, a single decode step can use a lot of memory.
Statistics only help when the data is somewhat ordered by the filter column. If event_date is random across the file, every row group contains a wide range of dates and none can be skipped. If you sort or write the data in date order, a filter on one week touches few row groups.
Many files and file size
Streaming works well on many Parquet files read through a glob pattern, as in pl.scan_parquet("events/*.parquet"). Files give the engine natural units of parallel work and let it skip a whole file when its metadata rules the file out.
Avoid both extremes:
- Thousands of tiny files (a few KB or MB each) add per-file overhead: opening, reading the footer, and listing. On object storage such as S3, each request adds latency.
- One huge file limits parallelism if it has few row groups, and a failed job has to start over.
A reasonable target is files from roughly 100 MB to 1 GB each, with row groups of about 100,000 to a few million rows depending on row width. These are starting points, not rules. Measure with your own data.
Partitioned layouts
A partitioned layout puts files into directories named after column values. The common version is Hive-style partitioning:
events/
year=2026/month=11/part-0.parquet
year=2026/month=12/part-0.parquetThe directory names carry the values of year and month. When you filter on those columns, Polars can skip entire directories without opening a file. Enable the feature when scanning:
import polars as pl
lf = (
pl.scan_parquet("events/**/*.parquet", hive_partitioning=True)
.filter((pl.col("year") == 2026) & (pl.col("month") == 12))
.select("user_id", "amount")
)
print(lf.explain())In the plan, check that the filter is applied at the scan and that the number of files to read is smaller than the full set. If it is not, the filter probably uses an expression the optimizer cannot push down, or hive_partitioning is off.
Recent Polars releases can also write partitioned output from a sink, for example with pl.PartitionByKey. The API is newer and has changed between versions, so check the documentation for the version you run before relying on it.
Choose partition columns with care:
- Pick columns you filter on often, with a modest number of distinct values, such as date parts or region.
- Avoid high-cardinality columns like
user_id. They create huge numbers of tiny directories and files. - Do not partition so finely that each partition is smaller than about 100 MB.
Deciding what to use
The diagram summarizes the choices in this chapter.
A short checklist follows from it:
- Keep raw CSV only as an input. Convert it once to Parquet with an explicit schema.
- Use zstd compression unless you have measured a reason not to.
- Write files of a sensible size, not thousands of tiny ones.
- Partition by a coarse column that your queries filter on.
- Order the data by the column you filter on most, so row group statistics can skip blocks.
- Run
explain()on a real query and confirm that filters and column selections reach the scan.
Common errors
- Scanning compressed CSV and expecting streaming. A gzip file cannot be read from the middle, so the reader generally has to decompress it from the start. Memory use and speed can be much worse than with plain CSV or Parquet. Convert it to Parquet instead.
- A schema failure late in a long CSV scan. The cause is type inference on too few rows. Set the schema explicitly.
- Expecting skipping on unsorted data. Statistics exist but every row group overlaps the filter range. Sort the data on write.
- Wide, small row groups with large string columns. These can use more memory per decode than you expect. Lower
row_group_sizeif memory spikes during the scan. - Mixed schemas across files. If files in one glob have different column types, the scan can fail or need extra casts. Keep the writing process consistent.
The next chapters build on this by looking at which operations use the most memory once the data is flowing in chunks.
Exercise
Your team receives a 60 GB CSV of web events every month. Analysts mostly run queries that filter on one calendar month and sum a few numeric columns. Describe the storage setup you would build, and name one reason for each choice.
Show answer
Convert each CSV once with scan_csv (explicit schema or schema_overrides) and sink_parquet, so the conversion does not need the file in memory and later queries avoid parsing text. Use zstd compression to reduce I/O. Write files in the 100 MB to 1 GB range with row groups of about 100,000 rows or more, so there are neither thousands of tiny files nor one file with no parallelism. Partition by year and month in Hive-style directories, because analysts filter on month and whole directories can be skipped. Scan with hive_partitioning=True and confirm with explain() that the month filter and the column selection are pushed down to the scan.