Sub topic 13
Tuning and debugging memory use
This chapter assumes you can write lazy Polars queries and run them with collect(engine="streaming") or a sink. It covers how to measure memory, find the step that uses it, and reduce it.
Measure before you change anything
Guessing at memory problems wastes time, so first record the peak memory of the whole process. The script below reports it on Linux or macOS.
import os
# Set these before importing polars so the engine reads them at startup.
os.environ["POLARS_MAX_THREADS"] = "4"
os.environ["POLARS_VERBOSE"] = "1"
import resource
import sys
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")
peak = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
# ru_maxrss is in kilobytes on Linux and in bytes on macOS.
peak_mb = peak / 1024 if sys.platform != "darwin" else peak / 1024 / 1024
print(f"rows: {result.height}, peak memory: {peak_mb:.0f} MB")Run the script once per change and compare the peak memory numbers. A change that does not lower the peak is not a fix.
Find where the memory goes
Use three sources of information, from cheapest to most detailed.
- The query plan. Call
lf.explain()and check that the filter and the column list appear at the scan. If a filter sits above the scan, Polars could not push it down, and the scan reads more data than needed. - Verbose output. With
POLARS_VERBOSE=1, Polars prints extra information to stderr while the query runs. Look for messages saying that part of the query fell back to the in-memory engine. A fallback means that part loads its whole input. - Bisecting the query. Remove the last operation, such as the
group_by, and re-measure. The step where peak memory jumps is the one to fix.
Common ways to reduce memory
Apply these one at a time and measure after each.
| Change | Why it helps |
|---|---|
| Select only the columns you need | Unused columns are never read from Parquet. |
| Filter as early as possible | Rows that fail the filter are dropped before later steps. |
| Cast to smaller types | `Int32` or `Float32` take half the space of `Int64` or `Float64`. |
| Use `Categorical` for repeated strings | Each distinct string is stored once. |
| Lower `POLARS_MAX_THREADS` | Fewer chunks are in flight at the same time. |
| Sink instead of collect | The output is never held in memory. |
Reducing threads trades speed for memory. Each thread works on its own chunk, so fewer threads means fewer chunks held at once. The setting is read when Polars starts, so set it before import polars, as in the script above.
When the peak will not drop
Sometimes a step needs its whole state in memory. A group_by with millions of distinct keys keeps one accumulator per key. A sort or a join can hold large buffers. In these cases, splitting the work often helps more than tuning settings. For example, run the query once per file or per partition, sink each result, and combine the small outputs in a final step.
Exercise
Your streaming query's peak memory is higher than expected. The explain() output shows the status == "ok" filter above the Parquet scan, not inside it. What does this tell you, and what is your next step?
Show answer
The filter was not pushed down, so the scan reads rows that are discarded later. Next, check whether something prevents pushdown, such as an operation placed before the filter, then rewrite the query so the filter comes right after the scan. Re-run explain() to confirm the filter now appears at the scan, then re-measure peak memory.