Sub topic 3
Choosing File Formats and Layouts
This chapter assumes basic Python, DataFrames, and Polars expressions such as filter, with_columns, and group_by. The goal is to keep each processing step within available memory.
Choosing File Formats and Layouts
Parquet is usually a better source for streaming than CSV. It stores columns separately, keeps schema information, and supports compression. Polars can read only the columns and row groups needed by a query.
Partition large datasets into directories when queries often filter by the same field:
events/
date=2026-01-01/part-000.parquet
date=2026-01-02/part-000.parquetPartitioning by date can prevent unrelated files from being read. Avoid creating thousands of tiny files, because file and metadata overhead can outweigh the benefit.
Where Memory Still Goes
Streaming limits the amount of input held at once, but some operations need state across many chunks:
group_bystores groups and their aggregate state.joinusually keeps one side or its key structure in memory.sortmay need to compare and retain much of the input.
A query can therefore stream its scan and filter while still using substantial memory during an aggregation or join. Reduce the input first with filters and selected columns.
Keeping the Final Result Small Enough
Select only required columns, filter early, and aggregate before collecting. If the result is still large, write it directly:
import polars as pl
(
pl.scan_parquet("events/*.parquet")
.filter(pl.col("status") == "ok")
.select(["user_id", "amount"])
.sink_parquet("ok_events.parquet")
)sink_parquet avoids materializing the complete result as a DataFrame.
Unsupported Operations and Fallback Behavior
Streaming support depends on the Polars version and the operation. An unsupported plan node may run with a non-streaming strategy or may produce an error. Do not assume that engine="streaming" makes every operation out-of-core. Check the plan and test with realistic data.
Tuning and Debugging Memory Use
Use explain() to inspect the optimized plan. Confirm that filters and column selection appear near the file scan. If memory remains high, reduce columns, filter earlier, use narrower data types, repartition files, or split a large join into stages. Test peak memory with production-like data, not only a small sample.
> callout note > Streaming reduces input memory, but it does not remove the memory cost of large groups, joins, sorts, or a large final result.
When Streaming Is Not the Right Tool
Use another approach when the workload requires repeated random access, a global sort dominates execution, the result itself is too large to store locally, or the query contains unsupported operations. A database, distributed engine, or purpose-built external sort may fit better.
Exercise
Why can a streaming query still run out of memory during a group_by?
Show answer
The scan can process chunks, but the group_by must retain state for all groups until it can produce the final aggregates.