Sub topic 14
When streaming is not the right tool
This chapter assumes you can write lazy Polars queries, run them with collect(engine="streaming"), and read the output of explain(). It covers the cases where streaming does not solve your problem, and what to do instead.
What streaming can and cannot fix
The streaming engine reduces memory use by processing data in chunks. It works when each chunk can be filtered, transformed, or folded into a small running state, and then discarded. It does not make a large result small, and it does not make a memory-heavy operation cheap.
Streaming is a poor fit in these situations:
- The result is large.
collect()still builds a full DataFrame. If the output is bigger than memory, usesink_parquetinstead, or reduce the result. - The query needs the whole dataset at once. A sort over all rows, a join where both sides are huge, or a
group_bywith billions of distinct keys must hold a lot of state. - An operation is unsupported. The engine can fall back to in-memory execution for that part of the query, and the memory savings disappear.
- The data is small. If it fits in memory comfortably, chunking adds scheduling overhead and gives no benefit.
- You reuse the same data repeatedly. Each streaming
collect()rereads the files. Interactive exploration is often faster with a filtered subset held in memory.
A decision path
Work around the limit by splitting the job
When one streaming query is still too heavy, split the data into partitions and combine small partial results. This works for aggregations that can be merged, such as sum, count, min, and max. It does not work for a median or a distinct count, because partial results cannot be combined correctly.
from pathlib import Path
import polars as pl
partials = []
for path in sorted(Path("events").glob("*.parquet")):
partial = (
pl.scan_parquet(path)
.filter(pl.col("status") == "ok")
.group_by("user_id")
.agg(pl.col("amount").sum().alias("total_amount"))
.collect(engine="streaming")
)
partials.append(partial)
result = (
pl.concat(partials)
.group_by("user_id")
.agg(pl.col("total_amount").sum())
)
print(result.head())Each file produces a small table of per-user totals. The final step sums those totals. Peak memory depends on one file and the number of users, not on the whole dataset.
Signs you have reached the limit
Look for these symptoms before changing tools:
- Memory still grows with input size after you add filters and a column selection. Check with
explain()that pushdown happens. - The plan contains operations you know are memory-heavy, such as a full
sortor a largejoin. - The query runs but is slower than the eager version on a small sample. The data may simply be small.
- The final
collect()fails after the scan completes. The result is too big, not the input.
Alternatives
| Situation | Option |
|---|---|
| Result too large for memory | `sink_parquet` or another sink |
| Heavy join or sort | Pre-sort or partition the files, or use a database engine such as DuckDB |
| Merge-friendly aggregation | Process partitions and combine partial results |
| Data far beyond one machine | A distributed engine, or a larger machine |
| Repeated interactive work | Filter once, save a smaller Parquet file, and work eagerly on it |
Streaming is one tool for reducing memory use. Often the best fix is also upstream: store the data in partitioned Parquet, select only the columns you need, and aggregate early.
Exercise
A query joins two 200 GB Parquet datasets on a high-cardinality key and then calls collect(engine="streaming"). Memory still runs out. Give two reasons streaming might not help, and one alternative.
Show answer
The join must hold state for one side (or many keys at once), which can be as large as the data itself. The joined result may also be larger than memory, and collect() builds all of it. Alternatives include writing the result with sink_parquet, partitioning both datasets by the join key and joining one partition pair at a time, or using a database or distributed engine built for large joins.
Exercise
Why can you combine per-file results for a sum but not for a median?
Show answer
Sums of partial sums equal the total sum, so partial results merge exactly. Medians of partial medians generally do not equal the overall median, because the median depends on the full ordering of all values.