Sub topic 10
Where memory still goes: group_by, join, and sort
This chapter assumes you can write basic Polars lazy queries with scan_parquet, filter, group_by, and agg. You should also know how to run a query with collect(engine="streaming") or sink_parquet, which earlier chapters covered. Streaming keeps memory low for operations that handle one chunk at a time. Three common operations need more, and each one grows memory in a different way.
Pipelined work versus work that must remember
Streaming runs a query as a pipeline. Chunks of rows flow from the scan through each operation, and a chunk can be discarded once the next step has used it.
filter,select,with_columns, and casts look only at the current chunk. Memory use stays about the size of a few chunks.group_by,join, andsortmust keep information from many chunks. A group total, for example, cannot be final until the last chunk has been seen.
So the streaming engine does not remove memory use. It makes memory depend on something other than the number of input rows.
Sample data
The examples below use two Parquet files. This script creates them, so you can run everything as shown.
import os
import polars as pl
os.makedirs("events", exist_ok=True)
n = 1_000_000
events = pl.DataFrame({"event_id": pl.int_range(n, eager=True)}).with_columns(
(pl.col("event_id") % 50_000).alias("user_id"),
pl.when(pl.col("event_id") % 10 == 0)
.then(pl.lit("error"))
.otherwise(pl.lit("ok"))
.alias("status"),
((pl.col("event_id") % 97) + 1).cast(pl.Float64).alias("amount"),
)
events.write_parquet("events/part-0.parquet")
users = pl.DataFrame({"user_id": pl.int_range(50_000, eager=True)}).with_columns(
pl.format("region-{}", pl.col("user_id") % 20).alias("region")
)
users.write_parquet("users.parquet")group_by: memory follows the number of groups
An aggregation such as sum does not need the original rows. For each group key, the engine keeps a small running state, such as a partial sum. Each incoming chunk updates those states, and the chunk is then dropped.
The memory cost is therefore roughly the number of distinct keys times the size of the state for each aggregation. The input row count has little effect.
import polars as pl
events = pl.scan_parquet("events/*.parquet")
# 2 distinct keys: the state is tiny, whatever the input size.
by_status = (
events.group_by("status")
.agg(pl.col("amount").sum().alias("total"))
.collect(engine="streaming")
)
# 50,000 distinct keys: the state grows with the number of users.
by_user = (
events.group_by("user_id")
.agg(pl.col("amount").sum().alias("total"))
.collect(engine="streaming")
)
print(by_status)
print(by_user.height)Both queries read the same rows. The second one holds about 25,000 times more group state. With a billion users, that state alone can exceed RAM, even though each input chunk is small.
Three things make group_by costlier:
- High-cardinality keys. Grouping by an ID, a timestamp with fine resolution, or a combination of several columns produces many groups.
- Aggregations that keep values. Functions such as
median,n_unique, orimplodeneed more than a running number. They may need to keep the values themselves per group, so the state grows with the data. - Many aggregations. Each one adds state per group.
If you can reduce the key first, do so. For example, group by pl.col("ts").dt.truncate("1d") instead of the raw timestamp.
join: memory follows the build side
A hash join splits its two inputs into two roles:
- The build side is loaded into a hash table keyed on the join columns. All of it must be in memory before any matching starts.
- The probe side streams through in chunks. Each chunk looks up its keys in the hash table, and matched rows are emitted.
The streaming join therefore costs about the size of the build side. The probe side can be any size.
import polars as pl
events = pl.scan_parquet("events/*.parquet")
users = pl.scan_parquet("users.parquet")
enriched = (
events.filter(pl.col("status") == "ok")
.join(users, on="user_id", how="inner")
.select("event_id", "user_id", "region", "amount")
)
enriched.sink_parquet("events_enriched.parquet")Here users is small, so it fits easily in a hash table, while events streams past it. The result goes to disk through a sink, so neither input nor output is collected.
Which table becomes the build side depends on your Polars version and on the optimizer's size estimates. Do not rely on argument order alone. Keep these points in mind:
- Reduce the smaller side before the join, with a
filterand aselectof only the columns you need. A hash table of two columns is much smaller than one of twenty. - If both tables are larger than memory, a plain hash join cannot work. Options are to partition both tables by the join key and join each partition separately, or to use another tool (see the last chapter).
- Some join types may not run natively in the streaming engine. As-of joins and joins on inequality conditions are examples. Those parts fall back to the in-memory engine, as the next chapter explains.
sort: memory follows the whole input
A sort cannot emit its first output row until it has seen every input row, because the smallest row might be in the last chunk. A full sort therefore has to buffer all of its input before it produces any output.
import polars as pl
events = pl.scan_parquet("events/*.parquet")
# Buffers every row that reaches the sort. Memory ~ size of the data.
events.sort("amount", descending=True).sink_parquet("events_sorted.parquet")Sinking the result avoids a second copy of the output in a DataFrame. It does not remove the buffering inside the sort. Whether your Polars version can spill a sort to disk is a version-specific detail. Check the release notes for the version you run, and test with data close to your real size.
Often you do not need a full sort. If you only want the largest or smallest rows, use top_k or bottom_k. These keep only k rows at a time.
import polars as pl
events = pl.scan_parquet("events/*.parquet")
top_events = events.top_k(10, by="amount").collect(engine="streaming")
print(top_events)Other ways to avoid a full sort:
- Sort after aggregating. Sorting 50,000 group totals is much cheaper than sorting 1,000,000 rows.
- Remove the sort if it is only for appearance. Sort the small final result in a regular DataFrame.
- For
Parquetoutput that downstream readers will filter by a column, partition by that column instead of sorting globally.
Other operations that remember
The same reasoning applies elsewhere. Ask what the operation must keep before it can emit a row.
| Operation | What it keeps | Memory grows with |
|---|---|---|
| `filter`, `select`, `with_columns` | Nothing between chunks | Chunk size |
| `group_by` with `sum`, `mean`, `count` | Running state per key | Distinct keys |
| `group_by` with `median`, `n_unique` | Possibly values per key | Distinct keys and group sizes |
| `join` (hash) | Hash table of the build side | Build side size |
| `sort` | All input rows | Total input size |
| `unique` | One entry per distinct row | Distinct rows |
| `top_k` | `k` rows | `k` |
Window expressions such as over(...) need whole groups at once, so treat them as expensive and check that they run in streaming mode in your version.
Check before you run
Use the plan to see which operations are in your query, and then reason about each one:
import polars as pl
events = pl.scan_parquet("events/*.parquet")
users = pl.scan_parquet("users.parquet")
lf = (
events.filter(pl.col("status") == "ok")
.join(users, on="user_id")
.group_by("region")
.agg(pl.col("amount").sum().alias("total"))
)
print(lf.explain())Look for JOIN, AGGREGATE, and SORT nodes. For each one, estimate the build side, the number of groups, or the input size. Then run the query on a sample and watch peak memory in your system monitor.
Exercise
A query reads 2 billion event rows from Parquet, joins them with a 300,000-row users table on user_id, filters to status == "ok", and runs .sort("amount") before sink_parquet. It runs out of memory. Which operation is the most likely cause, and how would you change the query?
Show answer
The most likely cause is the sort. It must buffer every row that survives the filter and the join before it can write the first output row, so memory grows with the whole input. The join is a lesser concern, because a 300,000-row build side is small and the 2 billion events stream past it. Fix it by removing the sort if the order does not matter, by using top_k if only the largest rows are needed, or by aggregating first and then sorting the small result. If a global order is required, write the unsorted data to disk and check whether your Polars version or another tool can sort out of core.