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 write them out with sink_parquet. It also assumes you know the memory-heavy operations from earlier chapters (group_by, join, sort). The goal is to help you recognize when the streaming engine will not solve your problem, and to choose a better approach.
What streaming does and does not do
The streaming engine lowers the memory needed to read, filter, and transform data. It processes the input in chunks, so the full input never has to fit in RAM. It does not make every query small.
Memory use is set by the largest piece of state the query must hold at one time. Three things can make that state large:
- The final result. If the answer has billions of rows, collecting it into a DataFrame needs memory for all of them.
- Intermediate state. A
group_bywith many distinct keys, ajoinwhose build side is huge, or a globalsorthas to keep a lot of data around. - Operations without a streaming implementation. These can fall back to the in-memory engine for part of the query, which gives up the memory benefit for that part.
Streaming helps most when the query reduces the data early (filters, column selection, aggregation to a modest number of groups) or when the output goes straight to disk through a sink. When none of that applies, streaming gives you little.
Situations where streaming is the wrong choice
The data already fits comfortably in memory
If the dataset takes a fraction of your RAM, you gain little from streaming. Lazy evaluation still helps, because pushdown and plan optimization apply either way. The in-memory engine is a fine default for small and medium data, and some queries run faster on it. Measure both engines on a representative query before you switch. Do not assume streaming is faster or slower.
The result is itself larger than memory
A query like "all events, with one extra column" produces as many rows as it reads. Collecting that result defeats streaming. The fix is to avoid collecting it. Use sink_parquet or another sink. If a downstream step needs the whole result in memory, the problem is in the downstream step, not in Polars.
Many distinct groups or a huge join
Aggregating by a key with hundreds of millions of distinct values produces hundreds of millions of output rows, and the engine must track all of them while it runs. Joining two very large tables has the same problem, because one side or its hash table must be held. If you hit memory limits here, chunking the input does not remove the cost. You have to shrink the problem, for example by:
- partitioning both inputs by the join key and processing one partition at a time;
- filtering or pre-aggregating one side before the join;
- selecting only the columns you need before the join.
The query needs many passes over the same data
Streaming is built around a single pass over the input. Exploratory work, where you run many different queries on the same data, repeats the scan, decompression, and parsing each time. If the working set fits in memory after you filter and select columns, collect it once and explore the DataFrame. If it does not fit, write a reduced, cleaned Parquet file once with a sink, then query that file.
The work is iterative or needs random access
Machine-learning training loops, graph algorithms, and anything that revisits rows in arbitrary order do not map onto a chunked, one-pass pipeline. Lazy queries can prepare the data (feature selection, filtering, type casting), but the iterative part belongs to a different tool or to a data loader built for that purpose.
Your input format fights chunking
A single large gzip-compressed CSV is a poor streaming source. It cannot be split cheaply across workers, and parsing text costs more CPU than reading Parquet. Converting once to Parquet, ideally split into many files of moderate size, pays for itself if you query the data more than a few times.
The operation is not supported in streaming
Some expressions or plan nodes have no streaming implementation. The engine then runs that part in memory, so peak memory can look nothing like what you expected. Check the plan and the release notes for your Polars version, because support changes between releases.
A decision flow
Worked alternative: process partitions yourself
When a single streaming query holds too much state, you can split the work by file and combine small partial results. This works for aggregations that can be merged, such as sums and counts. An average needs a sum and a count kept separately. A median cannot be merged this way.
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())Peak memory here is bounded by one file's aggregation plus the accumulated partial results. The trade-off is that you now own the orchestration. If the partial results are still too big, the combination step has the same problem as the original query, and you need to partition by key instead of by file.
Partitioning by key means that every row for a given user_id lands in the same partition. You can then process each partition independently and write each result to its own output file. No combination step is needed, and no single step holds all the groups.
Choosing something other than Polars
Sometimes the right answer is another tool or more hardware. Consider these options when the decision flow leads you out of Polars.
| Situation | Reasonable option |
|---|---|
| The data is slightly too big for RAM | A machine with more memory, or reduce columns and use smaller dtypes |
| Data is already in a database or warehouse | Push the filtering and aggregation into SQL |
| You need joins or sorts on data far beyond one machine's disk and RAM | A distributed engine such as Spark or Dask |
| Data is read from many small objects in cloud storage | Compact it into fewer, larger Parquet files first |
| You need ad hoc SQL over local files | A SQL engine that reads Parquet directly, such as DuckDB |
None of these is always better than Polars. The point is to match the tool to where the memory goes. Cheap fixes come first. Select fewer columns, use narrower types such as Int32 or Categorical where the data allows, and filter early. These often move a query from "does not fit" to "fits" without a different engine.
A quick check before you give up on streaming
Work through these in order:
- Print the plan with
lf.explain()and confirm that the filter and column selection are applied at the scan. - Run the query on a small slice, such as one file, and watch peak memory. Scale up the input and see how memory grows. Flat growth suggests streaming works. Growth proportional to input size points at a stateful operation or a fallback.
- Replace
collectwith a sink if the output is large. - Remove or simplify one suspect operation at a time (a
sort, a widejoin, a high-cardinalitygroup_by) and see which one drives memory. - If one operation is the cause and you cannot avoid it, partition the work around it.
Summary of decision criteria
- Use the in-memory engine when the data fits and you want the simplest behavior.
- Use streaming when the input is large but the query reduces it, or when the output goes to a sink.
- Partition the work yourself when stateful operations exceed memory and the work splits by key or file.
- Change tools or hardware when the problem is large, stateful, and cannot be split.
Exercise
A query reads 400 GB of Parquet on a machine with 64 GB of RAM. It joins two tables on user_id, then sorts the full joined result by timestamp and calls collect(engine="streaming"). The job runs out of memory. Give two reasons streaming alone may not fix this, and describe one change to the approach.
Show answer
First, the joined and sorted result is as large as the data it comes from, and collecting it needs memory for every row. Second, a global sort and a large join both need to hold a lot of state, so chunked reading does not bound their memory. A change that helps is to partition both tables by user_id (for example into hashed buckets), join and sort one bucket at a time, and write each output with sink_parquet. Selecting only the needed columns and filtering before the join also reduces the state. If the sorted output must be a single ordered file, consider a database or distributed engine instead.
Exercise
You have a 2 GB CSV file on a laptop with 32 GB of RAM, and you will run about 50 different exploratory queries on it. Is streaming the right tool? What would you do?
Show answer
Probably not. The data fits easily in memory, and streaming runs a fresh pass over the input each time you collect. Convert the CSV to Parquet once (for example with scan_csv and sink_parquet), then read it with pl.read_parquet or scan_parquet and use the in-memory engine. This avoids re-parsing text on every query.