Sub topic 12
Unsupported operations and fallback behavior
The streaming engine does not implement every Polars operation. When a query contains an operation it cannot stream, Polars does not stop with an error. It runs that part of the query on the regular in-memory engine instead. Your code still returns the right answer, but the memory profile you expected may no longer hold.
This chapter assumes you know how to build lazy queries with scan_parquet, how collect(engine="streaming") runs them, and how to read the output of explain(). It also assumes you know that group_by, join, and sort can need a lot of memory even when streaming.
What fallback means
A query plan is a tree of operations. Each node (a scan, a filter, a group_by, a join) takes input from the node below it and passes output upward. When you ask for the streaming engine, Polars tries to run each node as a streaming operator that handles one chunk at a time.
If a node has no streaming implementation, Polars hands that part of the plan to the in-memory engine. The in-memory engine needs its whole input at once, so the streaming engine collects everything that feeds that node into a full DataFrame first. Nodes above the fallback can then stream again.
The consequences:
- Correctness is preserved. Fallback changes how the work is done, not what the result is.
- Memory is not preserved. Everything that flows into the fallback node must fit in RAM at the same moment.
- The failure is silent by default. The first sign is usually an out-of-memory error or a slow query on a large input.
Which operations are affected
The set of supported operations grows with each Polars release, so any fixed list goes out of date. Treat the categories below as a guide to where fallback tends to happen, and confirm against your installed version.
| Category | Examples | Why it is hard to stream |
|---|---|---|
| Python callbacks | `map_batches`, `map_elements` | Polars cannot know what the function needs, so it cannot safely feed it chunks |
| Some window and ordered operations | certain `over(...)` forms, rolling and dynamic windows | The result for a row can depend on rows in other chunks |
| Operations that need all rows | some pivots, some reshaping, some set-like operations | The output shape depends on the full input |
| Newer or less common expressions | recently added expression types | Streaming support is often added after the in-memory version |
Do not read this table as "never use these." A window expression over a small, already-filtered table falls back harmlessly. The problem appears only when the data reaching the fallback node is large.
Detecting fallback
Fallback is not an error, so you have to look for it. There are three practical methods.
Turn on verbose logging
Setting the POLARS_VERBOSE environment variable makes Polars print diagnostic messages to standard error while it runs the query. Depending on your version, these messages tell you when part of a query is executed by the in-memory engine.
import os
# Set this before running the query. Messages go to stderr.
os.environ["POLARS_VERBOSE"] = "1"
import polars as pl
df = pl.DataFrame(
{
"user_id": [1, 1, 2, 2, 3],
"amount": [10.0, 20.0, 5.0, 15.0, 7.0],
}
)
df.write_parquet("small_events.parquet")
lf = (
pl.scan_parquet("small_events.parquet")
.with_columns(
(pl.col("amount") - pl.col("amount").mean().over("user_id")).alias("centered")
)
.select("user_id", "centered")
)
result = lf.collect(engine="streaming")
print(result)Read the stderr output for lines that mention the in-memory engine or a fallback. The exact wording changes between versions, so search for the words "fallback" and "in-memory" rather than matching an exact string.
Inspect the plan
explain() prints the optimized logical plan, which shows which nodes exist. It does not by itself tell you which engine runs each node. Recent Polars versions let you pass the engine, for example lf.explain(engine="streaming"), so the printed plan reflects how the streaming engine will actually execute the query. If your version does not accept that argument, use the verbose method instead.
Compare the two engines on a sample
Run the same query on a small sample with both engines and confirm they agree. This does not detect fallback, but it confirms that your sample result is trustworthy before you scale up.
import polars as pl
from polars.testing import assert_frame_equal
lf = (
pl.scan_parquet("small_events.parquet")
.group_by("user_id")
.agg(pl.col("amount").sum().alias("total_amount"))
)
in_memory = lf.collect().sort("user_id")
streaming = lf.collect(engine="streaming").sort("user_id")
assert_frame_equal(in_memory, streaming)
print("Both engines agree")Sort both results before comparing. Streaming does not guarantee row order unless the query orders its output.
Working around fallback
You cannot add streaming support to an operation yourself, but you can control how much data reaches it. Apply these in order.
- Shrink the input first. Put filters and column selection before the unsupported operation. Pushdown already moves filters toward the scan, but a filter that depends on the result of the fallback node cannot move below it.
- Replace the operation with an equivalent supported one. For example, a per-group mean subtracted with
overcan sometimes be written as agroup_byaggregation followed by a join. Test this on a sample, because a join has its own memory cost. - Replace Python callbacks with native expressions.
pl.col("x") * 100streams. A lambda that does the same thing throughmap_elementsusually does not, and it is also much slower. - Split the query at the fallback. Stream the first half into an intermediate file with
sink_parquet, then start a second lazy query from that file. The intermediate file sits on disk, so memory holds only what the second query needs.
Here is the split approach:
import polars as pl
# Stage 1: reduce the data with operations that stream well.
(
pl.scan_parquet("events/*.parquet")
.filter(pl.col("status") == "ok")
.select("user_id", "amount")
.sink_parquet("stage1.parquet")
)
# Stage 2: the remaining work reads the smaller intermediate file.
result = (
pl.scan_parquet("stage1.parquet")
.with_columns(
(pl.col("amount") - pl.col("amount").mean().over("user_id")).alias("centered")
)
.collect(engine="streaming")
)If stage 2 still falls back, its input is now only the filtered, two-column data, which is far smaller than the raw files.
Sinks and fallback
A sink runs the query with the streaming engine and writes chunks as they are produced. A fallback node inside a sinking query behaves the same way as in collect: its input is materialized in memory first. Sinking solves the problem of a large final result. It does not solve the problem of a large input to a fallback node. These are two separate memory costs, and you need to check both.
Some combinations of sink and operation may also be rejected outright in a given version, for example when a sink needs an ordering the plan cannot provide. If a sink raises an error about an unsupported operation, the usual fix is the split approach above, with the unsupported step done on the collected smaller result.
Common mistakes
- Assuming
engine="streaming"guarantees bounded memory. It requests streaming. It does not promise that every node streams. - Testing only on small data. Fallback works well on small inputs, so the problem hides until production size.
- Trusting a result of the same shape. A correct answer says nothing about how it was computed. Check memory use as well as output.
- Using an old fallback list. Operations that fell back last year may stream now, and the reverse is not true. Read the release notes for your version.
- Comparing outputs without sorting. Row order from streaming is not fixed.
Summary of the decision
When a query uses an operation you are unsure about, ask these questions in order:
- Does verbose output show that the operation ran on the in-memory engine?
- If so, how large is the data that reaches it after all filtering and column selection?
- If it fits comfortably in RAM, leave it alone.
- If it does not, rewrite it with a supported operation or split the query at that point with a sink.
Exercise
A query scans 200 GB of Parquet files, filters to the rows where status is "ok" (about 5% of the data), then applies map_batches with a Python function, and finally runs group_by and sink_parquet. It is run with the streaming engine and the machine has 32 GB of RAM. Will fallback cause an out-of-memory error? What would you check and change?
Show answer
It probably will not, but you need to measure. map_batches is a Python callback and is likely to fall back to the in-memory engine, so everything reaching it must fit in RAM. The filter keeps about 5% of 200 GB, roughly 10 GB, and the filter and column selection run before the callback, so the data reaching it is about 10 GB or less after projection. That fits in 32 GB, but only if the filter really runs before the callback and few columns are kept. Check with POLARS_VERBOSE=1 that the fallback happens where you expect, and check the plan to confirm the filter is applied at the scan. To be safer, select only the columns the function needs, replace the callback with native expressions if possible, or sink the filtered data to an intermediate Parquet file and run the callback in a second query.
Exercise
You run the same query with collect() and with collect(engine="streaming") on a small sample. The two DataFrames have the same rows but assert_frame_equal fails. What is the most likely cause and the fix?
Show answer
Row order differs. The streaming engine does not guarantee row order unless the query sorts its output. Sort both results by a key column, or by all columns, before comparing, as in the earlier example.