Sub topic 13
Tuning and debugging memory use
This chapter assumes you can write lazy Polars queries with scan_parquet, filter, group_by, and agg. It also assumes you have run a query with collect(engine="streaming") or a sink. Here you will measure how much memory a query uses, find the step responsible when it uses too much, and apply the adjustments that usually help.
Measure before you tune
Memory problems are easy to misdiagnose by guessing. Before changing anything, record peak memory for the query as it runs today. The peak matters because it decides whether you hit an out-of-memory kill.
The first script creates a test file of 5 million rows. Run it once.
import polars as pl
n = 5_000_000
df = pl.select(
user_id=pl.int_range(n) % 100_000,
amount=(pl.int_range(n) % 997).cast(pl.Float64),
status=pl.when(pl.int_range(n) % 10 == 0)
.then(pl.lit("error"))
.otherwise(pl.lit("ok")),
)
df.write_parquet("events.parquet")
print(df.estimated_size("mb"), "MB in memory")The second script runs the same aggregation in either mode and reports the process's peak resident memory. Run each mode in a separate process (python measure.py eager, then python measure.py streaming), because the peak value never goes down within a process. The resource module is available on Linux and macOS only.
import resource
import sys
import polars as pl
def peak_mb() -> float:
peak = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
# ru_maxrss is bytes on macOS and kilobytes on Linux.
return peak / 1024 / 1024 if sys.platform == "darwin" else peak / 1024
mode = sys.argv[1]
if mode == "eager":
result = (
pl.read_parquet("events.parquet")
.filter(pl.col("status") == "ok")
.group_by("user_id")
.agg(pl.col("amount").sum().alias("total_amount"))
)
else:
result = (
pl.scan_parquet("events.parquet")
.filter(pl.col("status") == "ok")
.group_by("user_id")
.agg(pl.col("amount").sum().alias("total_amount"))
.collect(engine="streaming")
)
print(f"{mode}: {result.height} groups, peak {peak_mb():.0f} MB")Compare the two numbers. The streaming run should peak lower, because it never holds the whole file. On a file this small the gap is modest. The pattern is what matters, since the eager peak grows with the file size and the streaming peak grows mostly with the number of groups.
A debugging workflow
Most memory failures come from one of four causes. Check them in this order, because the early checks are cheap and fix the most cases.
Check 1: pushdown reached the scan
If the filter or column selection is not applied at the scan, the engine reads more data than it needs. Print the plan and look at the scan node.
import polars as pl
pl.Config.set_verbose(True)
lf = (
pl.scan_parquet("events.parquet")
.filter(pl.col("status") == "ok")
.select("user_id", "amount")
)
print(lf.explain())
print(lf.explain(engine="streaming"))In the optimized plan, the scan should list only user_id, amount, and status as its projection, with the predicate attached to it. The second call prints the plan as the streaming engine will run it. It needs a recent Polars release. If your version rejects the engine argument, use the first call only.
Pushdown can be blocked by logic Polars cannot see through. Typical culprits are map_elements with a Python function, and a select of pl.all() early in the query when you only need a few columns. Replace Python functions with native expressions and name only the columns you need.
Check 2: fallback to in-memory execution
The streaming engine does not support every operation. When it meets one, it can run that part of the query on the in-memory engine. That part then materializes its input, which defeats the purpose.
With verbose mode on (pl.Config.set_verbose(True) or the environment variable POLARS_VERBOSE=1), Polars prints extra diagnostic lines to stderr as the query runs. Read them for notes about the engine used. The streaming plan from explain(engine="streaming") is also worth reading for steps that look out of place.
If you find a fallback, try these in order:
- Replace the unsupported expression with a supported one that gives the same result.
- Move the unsupported step later in the query, after the data has been filtered and aggregated down to a small size.
- Split the pipeline. Sink the first part to Parquet, then scan that file in a second query for the unsupported step.
Check 3: operations that hold state
Even fully streamed, some operators must keep state while chunks flow through. This is where memory goes after the basics are right.
| Operation | What it keeps | Practical reduction |
|---|---|---|
| `group_by` | One accumulator row per distinct key | Fewer keys, smaller key dtypes, fewer aggregated columns |
| `join` | The build side of the join, usually the smaller input | Filter and select columns on the build side before joining |
| `sort` | Potentially all rows being sorted | Sort after aggregating, or sort only the columns you need |
| `unique`, `n_unique` | The set of values seen | Apply after a filter, or on a narrower column set |
Three habits cut state without changing the result:
- Select early. Every extra column in a join or sort is carried for every row held.
- Shrink dtypes. Casting a column that holds small integers from
Int64toInt32, or a repeated string toCategorical, reduces the size of keys and values. - Aggregate before joining. If you only need per-user totals, compute them first and join the small result.
The next query applies all three ideas.
import polars as pl
events = (
pl.scan_parquet("events.parquet")
.filter(pl.col("status") == "ok")
.select(
pl.col("user_id").cast(pl.Int32),
pl.col("amount"),
)
.group_by("user_id")
.agg(pl.col("amount").sum().alias("total_amount"))
)
result = events.collect(engine="streaming")
print(result.head())Check 4: the result itself
If the final result is large, collect has to build it in memory no matter how well the middle of the query streams. Two options avoid that. You can sink to disk, or you can reduce the result with a final aggregation or a head-style limit. The sink pattern is the most common fix.
import polars as pl
(
pl.scan_parquet("events.parquet")
.filter(pl.col("amount") > 0)
.with_columns((pl.col("amount") * 100).cast(pl.Int64).alias("amount_cents"))
.sink_parquet("events_clean.parquet")
)Tuning knobs
When the four checks pass and memory is still tight, these settings trade speed for memory.
| Setting | Effect | Cost |
|---|---|---|
| `POLARS_MAX_THREADS` environment variable | Fewer worker threads means fewer chunks in flight at once | Slower execution |
| `low_memory=True` on `scan_parquet` | Reduces memory use during the read | Slower reads |
| Smaller Parquet row groups | Smaller units of work per read | Slightly larger files, less compression |
| Splitting input into several files | Lets the scan skip files and work on smaller units | More files to manage |
POLARS_MAX_THREADS must be set before Polars is imported, because the thread pool is created at import time. In a script, set it in the shell (POLARS_MAX_THREADS=4 python measure.py streaming), or set os.environ before import polars. Change one setting at a time and re-run the measurement script, so you know which change helped.
Common mistakes
- Tuning threads first. Reducing threads hides a pushdown or fallback problem behind slower runs. Check the plan before touching settings.
- Reading peak memory from the wrong place. Measuring inside a long-lived notebook includes earlier DataFrames. Use a fresh process.
- Collecting to inspect. Calling
collect()on a large lazy query just to look at it can reproduce the original out-of-memory error. Useexplain()to inspect the plan, and.head(5).collect()or a small sink to inspect data. - Testing only on small samples. Memory in
group_bydepends on the number of distinct keys, which grows with the data. A sample can hide a key-count problem.
Exercise
A streaming query that reads a Parquet dataset, joins it to a second large table, and sorts the result runs out of memory. The plan shows the filter at the scan. List three changes you could try, in a sensible order, and say how you would confirm each one worked.
Show answer
First, reduce the joined data: select only the needed columns from both inputs, filter the build side early, and cast wide dtypes to narrower ones. Second, move or remove the sort: sort after an aggregation, or drop it if the order is not needed, and sink the output to Parquet instead of collecting it. Third, if memory is still high, lower POLARSMAXTHREADS or split the input into partitions processed one at a time. After each change, run the measurement script in a fresh process and compare peak memory to the previous run, and check the verbose output and the streaming plan to confirm no step fell back to in-memory execution.