Sub topic 17
Larger-than-memory queries: streaming and sink_parquet
This chapter assumes you can write Polars expressions and build a LazyFrame with scan_csv or scan_parquet. It also assumes you have read explain() output. The code uses a recent Polars 1.x release, because the streaming API changed across versions. If a call below is rejected, check your installed version.
Why a lazy plan helps with big data
An eager DataFrame holds all its data in memory, and so does every intermediate result. A file larger than RAM cannot be read this way. A lazy query is a plan, so Polars can choose how to run it. Two choices matter for large inputs:
- Pushdown reads less data. Projection pushdown and predicate pushdown shrink what leaves the scan.
- Streaming processes the data in batches, so the full input never has to sit in memory at once.
Pushdown is always on. Streaming is an execution mode you request.
How batch processing works
In the streaming engine, the scan reads a chunk of rows. The chunk passes through operators such as filter and select. The result either feeds a running aggregation or goes to a sink, and then the next chunk is read.
Memory use is roughly the chunk size, plus any state an operator must keep. A filter keeps no state. A group_by keeps one entry per group. A sort or a join may need to hold a lot of data, which is why those operations can still be expensive.
Setting up sample data
The examples below use a generated file so you can run them as written.
import random
import polars as pl
random.seed(0)
n = 200_000
pl.DataFrame(
{
"region": random.choices(["EU", "US", "APAC"], k=n),
"product": random.choices(["a", "b", "c", "d"], k=n),
"amount": [random.uniform(-10, 100) for _ in range(n)],
}
).write_csv("big.csv")
print("wrote big.csv")This file is small, and the behaviour is the same for files that do not fit in memory. Only the scale changes.
Writing results with sink_parquet
sink_parquet runs the query in streaming fashion and writes the output directly to a file. No full DataFrame is ever built in memory.
import polars as pl
lf = pl.scan_csv("big.csv").filter(pl.col("amount") > 0)
lf.sink_parquet("positive.parquet")
check = pl.scan_parquet("positive.parquet").select(pl.len()).collect()
print(check)sink_parquet returns None, not a LazyFrame. It is an action, like collect(), so it runs the query immediately. The last two lines reopen the output lazily and count rows. That count scans the file, but only one value reaches memory.
Polars has sibling methods for other formats: sink_csv, sink_ipc and sink_ndjson. Choose Parquet when a later step will read the data again. It is compressed, typed and columnar, so a later scan_parquet can use projection and predicate pushdown.
Streaming into a normal result with collect
Sinks suit large outputs. Some queries have a small output but a large input, such as an aggregation over a huge file. For these, ask collect to use the streaming engine.
import polars as pl
summary = (
pl.scan_csv("big.csv")
.filter(pl.col("amount") > 0)
.group_by("region")
.agg(
pl.col("amount").sum().alias("total"),
pl.len().alias("rows"),
)
.sort("region")
.collect(engine="streaming")
)
print(summary)Only the group state and the three-row result are kept in memory.
Older code uses collect(streaming=True). That flag belongs to the earlier streaming implementation and is deprecated in recent releases. In new code, use engine="streaming".
Several outputs from one scan
Suppose you want two output files from the same filtered data. Calling sink_parquet twice runs two separate queries and scans the CSV twice. Recent releases let you build the sinks lazily with lazy=True and run them together with collect_all.
import polars as pl
base = pl.scan_csv("big.csv").filter(pl.col("amount") > 0)
eu = base.filter(pl.col("region") == "EU").sink_parquet("eu.parquet", lazy=True)
us = base.filter(pl.col("region") == "US").sink_parquet("us.parquet", lazy=True)
pl.collect_all([eu, us])With lazy=True, sink_parquet returns a LazyFrame that represents the write. Nothing is written until collect_all runs. This lets the optimiser share the common scan and filter between the two sinks, using the same mechanism as in the chapter on common subexpression elimination. The lazy argument is missing from older releases, so check your version if you get an unexpected-argument error.
What streaming does not cover
The streaming engine does not support every operation. When a query contains an unsupported step, Polars normally falls back to the in-memory engine for that part. The query still gives correct results, but memory use can jump without any error. Two cases need care:
- Sinks and unsupported operations. A sink must be able to stream the whole plan. If something in the plan cannot stream, Polars may raise an error or collect part of the data first. The behaviour depends on the version.
- Python UDFs.
map_elementsand similar calls are opaque, as the earlier chapter on optimisation barriers showed. They run row by row in Python and can also hinder streaming. Replace them with native expressions where you can.
Operations that need all the data in one place are the usual cause of high memory use. These include a global sort, a join on two large inputs, unique over many distinct values and pivot. Reduce the data before such a step. Filter early, select only the needed columns, or aggregate first.
Checking what will run
Use the tools from the earlier chapters to inspect a streaming query before you run it on big data:
- Call
explain()and confirm that the filter and the column list appear inside the scan node. If they do not, an optimisation barrier is in the way. - Call
collect_schema()to confirm the output column names and types without reading any data. - Run the query on a slice first, for example
pl.scan_csv("big.csv").head(100_000), then compare its output with the in-memory engine on the same slice.
import polars as pl
lf = (
pl.scan_csv("big.csv")
.filter(pl.col("amount") > 0)
.group_by("product")
.agg(pl.col("amount").mean())
)
print(lf.explain())
print(lf.collect_schema())
in_memory = lf.collect().sort("product")
streamed = lf.collect(engine="streaming").sort("product")
print(in_memory.equals(streamed))Both engines should give the same rows. Row order from a group_by is not guaranteed, so the code sorts before comparing. The comparison guards against a surprise when you switch engines.
Choosing between the options
| Situation | Use |
|---|---|
| Result fits in memory, input is small | `collect()` |
| Small result from a large input | `collect(engine="streaming")` |
| Result is large, or later steps read it again | `sink_parquet` |
| Several results from one scan | `sink_parquet(..., lazy=True)` plus `collect_all` |
Exercises
Exercise
A CSV file is 40 GB and your machine has 16 GB of RAM. You want to keep only rows where amount > 0 and save them for later analysis. Which call do you use, and why is scan_csv(...).filter(...).collect() a poor choice?
Show answer
Use pl.scan_csv(path).filter(pl.col("amount") > 0).sink_parquet("out.parquet"). The sink streams the data in batches and writes the output directly, so no full DataFrame is built. collect() builds the whole filtered result as a DataFrame in memory, and that can still exceed 16 GB if many rows pass the filter.
Exercise
Your streaming group_by query runs correctly on a small sample but uses far more memory than expected on the full file. Name two things to check.
Show answer
First, check whether the plan contains a step that cannot stream, such as a Python UDF in map_elements, a global sort or a join between two large inputs. Polars may have fallen back to the in-memory engine for that step. Second, check the number of distinct groups, because a group_by keeps one state entry per group and a very high-cardinality key makes that state large. Also confirm with explain() that the filter and column selection reached the scan.