Sub topic 6
How the Streaming Engine Processes Data in Chunks
This chapter assumes you know basic Python, can read Polars expressions such as pl.col, filter, with_columns, and group_by, and have met lazy queries and scan_* functions. You will learn the working model behind the streaming engine: how it splits data into chunks, how those chunks move through a query, and where the model breaks down.
The core idea: process a piece at a time
An eager query loads the whole input, then runs each step over the full data. A streaming query reads a small piece of the input, runs every step on that piece, passes the result onward, and then reads the next piece. Memory use depends on the size of a piece and on any state the query must keep, not on the size of the file.
Polars calls these pieces morsels. A morsel is a small batch of rows from a source, a few thousand to a few hundred thousand rows depending on the data and the engine's settings. The exact size is an internal detail that can change between versions, so do not write code that depends on it.
A pipeline of nodes
Internally, the streaming engine turns the optimized logical plan into a graph of nodes. Each node does one job, such as reading a file, filtering rows, computing expressions, or aggregating. Morsels travel along the edges between nodes.
Nodes run concurrently. While one thread filters morsel 3, another can already be reading morsel 4. This overlap keeps CPU cores busy and hides disk latency, so streaming is often faster than eager execution even when memory is not a concern.
Two kinds of nodes
The memory behavior of a query depends on which kinds of nodes it contains.
| Node kind | Behavior | Memory held | Examples |
|---|---|---|---|
| Streaming (per-morsel) | Transforms each morsel independently and passes it on | One or a few morsels per thread | `filter`, `select`, `with_columns` with row-wise expressions |
| Stateful (accumulating) | Combines morsels into state across the whole input | Grows with the state, not the input | `group_by`, `join`, `sort`, `unique` |
A per-morsel node forgets a morsel once it has passed it on. A stateful node must remember something. A sum per group remembers one number per group. A sort must remember every row it will emit, because the first output row could be the last input row.
Seeing it work
The query below filters and aggregates many Parquet files. The filter and the column selection run per morsel. Only the aggregation state, one running total per user_id, persists.
import polars as pl
lf = (
pl.scan_parquet("events/*.parquet")
.filter(pl.col("status") == "ok")
.group_by("user_id")
.agg(pl.col("amount").sum().alias("total_amount"))
)
result = lf.collect(engine="streaming")If there are ten million distinct users, the state holds ten million sums, which is small. If the grouping key is nearly unique per row, the state approaches the size of the input, and the memory advantage disappears. The next sections cover this in more detail.
How aggregation keeps state small
For a decomposable aggregation such as sum, min, max, count, or mean, each morsel is reduced to partial results per group. The engine then merges partial results into the running state. It never needs the original rows again.
Here is the idea in plain Python. This is a model of the technique, not Polars internals:
from collections import defaultdict
def streaming_group_sum(morsels):
state = defaultdict(float)
for morsel in morsels: # morsel: list of (user_id, amount)
for user_id, amount in morsel:
state[user_id] += amount
return dict(state)
morsels = [
[("a", 1.0), ("b", 2.0)],
[("a", 3.0), ("c", 4.0)],
[("b", 5.0)],
]
print(streaming_group_sum(morsels))This prints {'a': 4.0, 'b': 7.0, 'c': 4.0}. At any moment the function holds one morsel plus one entry per group. The same shape applies in Polars, with parallel threads each keeping partial state that is merged later.
Some aggregations need more than a small number per group. A median or a list aggregation must keep the values themselves, so memory grows with the data in each group.
Parallelism and ordering
Several threads process morsels at once, so morsels can finish out of order. Polars tracks a sequence number on each morsel so that operations that depend on order can restore it. Two consequences follow.
- Order-preserving work costs something. If your query depends on row order, the engine may need to buffer morsels until earlier ones arrive.
- Without an explicit
sort, do not rely on output order from agroup_byorjoin. Treat it as unspecified, in streaming and in eager mode alike.
Backpressure: why a fast reader does not flood memory
A reader can produce morsels faster than later nodes consume them. If the engine let the reader run ahead without limit, the buffered morsels would fill memory. Instead, edges between nodes behave like bounded queues. When a queue is full, the upstream node waits. This is backpressure.
The practical effect is that peak memory scales roughly with the number of threads times the morsel size times the number of nodes in flight, plus any state held by stateful nodes. Reducing the thread count lowers the first term but also lowers throughput.
You can limit threads before importing Polars by setting the POLARS_MAX_THREADS environment variable:
import os
os.environ["POLARS_MAX_THREADS"] = "4"
import polars as pl
print(pl.thread_pool_size())The variable is read when Polars is imported, so setting it after import polars has no effect.
Where streaming helps and where it does not
The engine's model gives a simple way to predict memory use. Walk the plan from the scan to the output and ask, at each node, what it must remember.
- Scan, filter, and projection nodes remember almost nothing. Pushdown also means fewer rows and columns ever enter the pipeline.
- A
group_bywith few groups remembers little. Agroup_bywith many groups remembers a lot. - A
joinmust hold one side, usually the build side, in memory so it can look up matches while the other side streams past. - A
sortof the full input must hold the input, although the engine can use techniques that reduce this. - The final result is collected into a DataFrame, so it must fit in memory unless you write it with a sink.
Common mistakes
- Assuming streaming means constant memory. Memory is bounded for per-morsel nodes only. Stateful nodes can still grow with the data.
- Collecting a huge result.
collect(engine="streaming")still builds a DataFrame at the end. If the output is large, use a sink instead. - Reading the file eagerly first. Calling
pl.read_csvbefore building the query loads everything, so the streaming engine never sees the data. Usescan_csvorscan_parquet. - Relying on output order. Parallel morsel processing does not promise a stable order without
sort. - Setting
POLARS_MAX_THREADStoo late. It must be set before Polars is imported.
Checking the plan
Before running a large query, print the plan and confirm that the filter and projection sit at the scan:
import polars as pl
lf = (
pl.scan_parquet("events/*.parquet")
.filter(pl.col("status") == "ok")
.select("user_id", "amount")
)
print(lf.explain())If the filter appears above the scan instead of inside it, or the scan lists every column, the pushdown did not apply and more data flows through the pipeline than needed. Later chapters show how to inspect the streaming plan itself and how to handle operations the engine does not support.
Exercise
A query scans a 200 GB Parquet dataset, filters to status == "ok", and then runs groupby("sessionid") with sum on amount. session_id is unique for almost every row. The result is collected with collect(engine="streaming"). Why might memory still run out, and what are two changes that could help?
Show answer
The groupby node is stateful, and with a nearly unique key it holds about one entry per surviving row, so its state is close to the size of the filtered input. The collected result is also nearly that large. Two options: reduce the state by filtering or selecting fewer rows before the groupby, or write the result with sink_parquet so the output is not materialized as a DataFrame. If the state itself is too large, also consider splitting the work by partition, for example processing one group of files at a time, or choosing a different grouping key.
Exercise
You set os.environ["POLARSMAXTHREADS"] = "2" on the line after import polars as pl, and thread usage does not change. Why?
Show answer
Polars reads POLARSMAXTHREADS when it is imported and starts its thread pool then. The variable must be set before the import, either in the shell or in Python before import polars.