Sub topic 7
Running a query with the streaming engine
This chapter assumes you know basic Python and Polars expressions (pl.col, filter, group_by). It also assumes you can build a lazy query with scan_parquet or scan_csv, as covered in earlier chapters. Here you run that query so Polars processes it in chunks instead of loading all the input at once.
What `collect` does
A lazy query is only a description of work. Nothing is read or computed until you ask for a result. LazyFrame.collect() is the call that starts execution and returns an ordinary in-memory DataFrame.
collect takes an engine argument that selects the executor:
| Value | Behavior |
|---|---|
| `"auto"` (default) | Polars picks an engine. For `collect`, this is the in-memory engine. |
| `"in-memory"` | Materializes each intermediate result in full. |
| `"streaming"` | Processes the data in chunks and keeps only what each operator needs. |
| `"gpu"` | Runs on a GPU. It needs extra packages and is not covered here. |
The query and its optimizations are the same for all engines. Only the executor changes. That is why moving to streaming usually means changing one argument.
Older tutorials use collect(streaming=True). That older flag belongs to a previous streaming implementation and is deprecated. Use engine="streaming" on a current Polars release.
A first streaming query
The example below creates three small Parquet files, scans them as one dataset, and runs an aggregation with the streaming engine. The data is tiny so you can run it anywhere. The code is the same for files far larger than memory.
import tempfile
from pathlib import Path
import polars as pl
data_dir = Path(tempfile.mkdtemp())
for i in range(3):
pl.DataFrame(
{
"user_id": [1, 2, 3, 1, 2, 3],
"status": ["ok", "ok", "error", "ok", "error", "ok"],
"amount": [10.0, 5.5, 3.0, 7.25, 1.0, 2.0],
}
).write_parquet(data_dir / f"part-{i}.parquet")
lf = (
pl.scan_parquet(str(data_dir / "*.parquet"))
.filter(pl.col("status") == "ok")
.group_by("user_id")
.agg(pl.col("amount").sum().alias("total_amount"))
)
result = lf.collect(engine="streaming")
print(result.sort("user_id"))The result has one row per user_id. The sort at the end is only for stable printing. A group_by does not promise any row order unless you pass maintain_order=True, and the streaming engine in particular may return groups in a different order from run to run.
What happens during execution
The streaming engine splits the input into batches of rows, often called morsels. Each batch moves through the operators of the plan. A filter or a with_columns handles one batch and passes it on. Operators that must see more than one batch, such as group_by, keep a running state and combine the batches as they arrive.
Two consequences follow:
- Peak memory depends on the size of a batch plus the size of any operator state. It does not depend directly on the size of the input.
- Operators whose state grows with the data are the real memory risk. Examples are a
group_bywith many distinct keys, a largejoin, and a fullsort. A later chapter covers these.
The result still has to fit
collect(engine="streaming") returns a DataFrame, so the final result must fit in memory. Streaming lowers the cost of getting there. It does not change what you get at the end.
This works well when the query reduces the data:
- Filters that discard most rows.
- Aggregations that produce one row per group.
- Selecting a few columns from a wide file.
It fails when the query keeps almost everything. For example, pl.scan_csv("big.csv").with_columns(...).collect(engine="streaming") still builds the full output as one DataFrame. If the output is larger than memory, you hit the same out-of-memory error you started with. In that case, write the result to disk with a sink (next chapter) instead of collecting it.
Reducing the result before you collect
You can often shrink the output inside the query. Apply the reduction before collect, so the streaming engine does the work in chunks:
import tempfile
from pathlib import Path
import polars as pl
path = Path(tempfile.mkdtemp()) / "events.parquet"
pl.DataFrame(
{
"user_id": [1, 2, 3, 4, 5, 6],
"status": ["ok", "ok", "error", "ok", "ok", "ok"],
"amount": [10.0, 5.5, 3.0, 7.25, 1.0, 2.0],
}
).write_parquet(path)
top = (
pl.scan_parquet(str(path))
.filter(pl.col("status") == "ok")
.select("user_id", "amount")
.sort("amount", descending=True)
.head(3)
.collect(engine="streaming")
)
print(top)Here head(3) bounds the final size to three rows regardless of the input. Polars can combine sort and head into a top-k operation, so it does not have to hold a fully sorted copy of the data. The sort and head order matters. Putting head before sort would return the first three rows of the file and then sort only those.
Checking which engine runs the query
The streaming engine does not support every operation. When a part of the query is not supported, Polars may run that part with the in-memory engine instead of raising an error. The query still returns correct results, but memory behavior changes for that step.
You can inspect this in two ways:
- Print the plan with
lf.explain(engine="streaming"). Recent Polars versions accept theengineargument here and show the plan the streaming engine will execute. The plan shows where a scan applies a filter or reads only selected columns. - Set the environment variable
POLARS_VERBOSE=1before running. Polars then prints diagnostic messages to stderr, including notes about fallbacks.
import os
import tempfile
from pathlib import Path
import polars as pl
os.environ["POLARS_VERBOSE"] = "1"
path = Path(tempfile.mkdtemp()) / "events.parquet"
pl.DataFrame({"status": ["ok", "error"], "amount": [1.0, 2.0]}).write_parquet(path)
lf = pl.scan_parquet(str(path)).filter(pl.col("status") == "ok").select("amount")
print(lf.explain(engine="streaming"))
print(lf.collect(engine="streaming"))Diagnostic output varies between Polars versions, so treat it as a debugging aid and not a stable interface. A later chapter covers fallback behavior in more detail.
Making streaming the default
If most of your queries should use the streaming engine, you do not have to pass the argument every time. Polars has a global setting for this:
import polars as pl
pl.Config.set_engine_affinity("streaming")After this call, collect() prefers the streaming engine. Passing engine= explicitly overrides the setting for one call. This setting is global to the process, so avoid it in library code that other people import.
Common errors
- Using
read_csvand then.lazy().pl.read_csv("big.csv").lazy()has already loaded the whole file. Usepl.scan_csvso the file is read during execution. - Calling
collect()on a huge unfiltered query. The default engine and the streaming engine both return aDataFrame. Add filters, aggregations, or ahead, or switch to a sink. - Expecting a fixed row order. Streaming processes batches in parallel. Sort explicitly, or use
maintain_order=Truewhere an operation offers it, if order matters. - Passing
streaming=Trueon a new release. It is deprecated. Useengine="streaming". - Assuming a fast first run means low memory. A small test file will not reveal a
group_bywith millions of distinct keys. Measure peak memory on realistic data.
Exercise
A teammate writes pl.scancsv("logs.csv").withcolumns((pl.col("bytes") / 1024).alias("kb")).collect(engine="streaming") on a file twice the size of RAM and gets an out-of-memory error. Why does streaming not help, and what would you change?
Show answer
collect returns a DataFrame, and this query keeps every row, so the full output must be built in memory. Streaming only processes the input in chunks. It cannot make a result that is larger than RAM fit. Either reduce the result inside the query (filter rows, aggregate, select fewer columns, or use head), or replace collect with a sink such as sink_parquet so the output is written to disk as it is produced.
Exercise
What are two ways to find out whether part of a streaming query ran on the in-memory engine instead?
Show answer
Print the plan with lf.explain(engine="streaming") and look at how the query is executed. Or set POLARS_VERBOSE=1 and read the diagnostic messages Polars writes to stderr during collect.