Sub topic 10
Where Memory Still Goes: group_by, join, and sort
This chapter assumes you can write lazy Polars queries, run them with collect(engine="streaming"), and read a query plan. The streaming engine processes data in chunks, but some operations must remember state across chunks. That state is what uses memory.
Why some operations need state
A filter or a column calculation looks at one row at a time. Once a chunk is processed, the engine can discard it. Other operations cannot work this way, because a row's result depends on rows that may arrive later.
| Operation | What it must keep in memory |
|---|---|
| `filter`, `select`, `with_columns` | Almost nothing beyond the current chunk |
| `group_by` + `agg` | One accumulator per distinct group key |
| `join` | The data of at least one side, indexed by the join key |
| `sort` | Potentially all rows, unless the engine can spill to disk |
group_by: memory grows with distinct keys
A group_by keeps one running result per group. Aggregations such as sum, count, min, and max need only a small value per group. So memory depends on the number of distinct keys, not the number of input rows.
import polars as pl
lf = (
pl.scan_parquet("events/*.parquet")
.group_by("user_id")
.agg(
pl.col("amount").sum().alias("total_amount"),
pl.len().alias("n_events"),
)
)
result = lf.collect(engine="streaming")Ten billion rows for 50,000 users is cheap. Ten billion rows with a nearly unique key, such as an event ID, produces almost as many groups as rows, and the accumulators can approach the size of the input. Aggregations that must keep values, such as list or median, cost more per group than a simple sum.
join: the build side must fit
A hash join reads one input, called the build side, into a lookup table. It then streams the other input, called the probe side, past that table. Only the probe side is processed in chunks. If both tables are large, the build side can still exhaust memory.
import polars as pl
events = pl.scan_parquet("events/*.parquet")
users = pl.scan_parquet("users.parquet").select("user_id", "country")
joined = events.join(users, on="user_id", how="left")
joined.sink_parquet("events_with_country.parquet")Here users is small, so it works well as the build side. Select only the columns you need from it before joining, because every extra column on the build side costs memory. Reduce both sides with filters before the join whenever you can.
sort: the hardest case
A global sort cannot emit its first output row until it has seen every input row, because the smallest value could be in the last chunk. The engine must hold, or spill, all the data.
import polars as pl
lf = pl.scan_parquet("events/*.parquet").sort("amount", descending=True)
# Often a better question: do you need the whole sorted dataset?
top = (
pl.scan_parquet("events/*.parquet")
.select("user_id", "amount")
.top_k(100, by="amount")
.collect(engine="streaming")
)top_k keeps only 100 rows at a time, so memory stays small. Prefer it, or a sort followed by head, when you need only the extremes. If you truly need a full sorted file, write it with a sink, and keep the column list short.
Reducing the cost
- Drop columns before the stateful step. Projection pushdown helps at the scan, but an explicit
selectalso protects against columns added by earlier steps. - Filter early so fewer rows reach the stateful operation.
- Use narrow types, such as
Int32instead ofInt64, orCategoricalfor repeated strings. - Put the smaller table on the build side of a join.
Exercise
You group 5 billion event rows by event_id, and every event_id is unique. Why can this run out of memory even with the streaming engine, and what would you change?
Show answer
A groupby keeps one accumulator per distinct key. With unique keys, the number of groups is close to the number of rows, so the state is about as large as the input. Check whether you need to group by that key at all. Group by a coarser key such as `userid` or a date, or filter the data first so fewer groups exist.
Exercise
You need the 10 largest amount values in a file too big for memory. Should you use sort(...).head(10) or top_k(10, by="amount"), and why?
Show answer
Use top_k. It only has to track the 10 best rows seen so far, so memory stays small. A full sort must hold or spill every row before it can return any.