Sub topic 11
Keeping the final result small enough
This chapter assumes you can write basic Polars expressions and have read the earlier chapters on lazy scans, query plans, and collect(engine="streaming"). It covers one limit that streaming does not remove: the final result has to fit in memory unless you write it to disk.
Streaming bounds the work, not the answer
The streaming engine processes input in chunks, so the input can be much larger than RAM. When you call collect, though, Polars builds a single in-memory DataFrame from the output. If the query produces 40 GB of output, collect(engine="streaming") needs room for 40 GB.
import polars as pl
# Assumed columns: user_id (Int64), status (String), amount (Float64), ts (Datetime)
lf = pl.scan_parquet("events/*.parquet").filter(pl.col("status") == "ok")
# Risky: if most rows have status "ok", this result is almost as large as the input.
result = lf.collect(engine="streaming")The filter is correct and the scan streams, but the result keeps most of the rows and all of the columns. The query can still fail with an out-of-memory error, this time at the end. The error looks the same as the eager failure, so it is easy to blame the wrong stage.
Two places use memory, and they behave differently:
- Intermediate state is the working memory for chunks, hash tables, and sort buffers. The engine manages it.
- The final result is whatever you ask
collectto return. Your query design controls it.
The rest of the chapter is about the second one.
Estimate the result before you collect it
A cheap check can save a failed run. Count the output rows first, which streams through the data and returns one number:
import polars as pl
lf = pl.scan_parquet("events/*.parquet").filter(pl.col("status") == "ok")
n_rows = lf.select(pl.len()).collect(engine="streaming").item()
n_cols = len(lf.collect_schema())
print(f"{n_rows:,} rows x {n_cols} columns")Multiply rows by the bytes per row to get a rough size. An Int64 or Float64 takes 8 bytes per value. A string column is usually larger and depends on string length.
When you do collect, you can measure the result:
import polars as pl
summary = (
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"{summary.estimated_size('mb'):.1f} MB, {summary.height:,} rows")estimated_size is an approximation, but it is accurate enough to tell megabytes from gigabytes.
Ways to shrink the result
Each technique below reduces either the number of rows or the bytes per row.
| Technique | What it reduces | Caveat |
|---|---|---|
| Select only needed columns | Bytes per row | Do it in the query so projection pushdown skips unread columns too |
| Filter early | Rows | Only helps if the filter is selective |
| Aggregate (`group_by`, `agg`) | Rows, often by orders of magnitude | Output size equals the number of groups, and a high-cardinality key can be huge |
| `top_k` or `head` | Rows, to a fixed bound | `head` without a sort gives arbitrary rows, and a full sort is memory heavy |
| Smaller dtypes | Bytes per row | Casting to a narrower type can lose range or precision |
| Sink to disk | Result held in memory, down to nearly zero | You work with a file afterwards, not a DataFrame |
Select columns and aggregate
Selecting columns matters twice. Parquet lets the scan skip unused columns, and the result carries fewer bytes per row. Aggregation changes the size most. Raw events might be billions of rows, but per-day or per-user summaries are often thousands to millions.
import polars as pl
daily = (
pl.scan_parquet("events/*.parquet")
.filter(pl.col("status") == "ok")
.group_by(pl.col("ts").dt.date().alias("day"))
.agg(
pl.len().alias("events"),
pl.col("amount").sum().alias("total_amount"),
pl.col("user_id").n_unique().alias("active_users"),
)
.sort("day")
.collect(engine="streaming")
)The result has one row per day. The sort here runs on the small aggregated output, which is much cheaper than sorting the raw input. Where you put sort in a pipeline matters. Sort after you reduce, not before.
Bound the output with top_k
If you need only the largest few rows, say so. top_k keeps a small running set instead of sorting everything:
import polars as pl
biggest = (
pl.scan_parquet("events/*.parquet")
.select("user_id", "amount")
.top_k(100, by="amount")
.collect(engine="streaming")
)For a quick look at the data, head(n) is fine, but treat the rows as a sample, not a meaningful selection. Without an explicit sort, the rows you get depend on file and chunk order.
Use narrower dtypes
When the result must stay row-level, bytes per row decide the size. Polars infers wide types by default. If you know the value ranges, cast them down:
import polars as pl
slim = (
pl.scan_parquet("events/*.parquet")
.select(
pl.col("user_id").cast(pl.UInt32),
pl.col("status").cast(pl.Categorical),
pl.col("amount").cast(pl.Float32),
)
.filter(pl.col("status") == "ok")
.collect(engine="streaming")
)Check the ranges first. UInt32 holds values up to about 4.29 billion, and Float32 carries about 7 significant decimal digits, which is not enough for exact currency totals. A low-cardinality string column such as status shrinks well as Categorical. A string column with mostly unique values does not.
When the result is large by nature
Some tasks produce a large output on purpose. Examples are cleaning a file, converting CSV to Parquet, or adding a derived column to every row. Collecting these is the wrong approach. Use a sink, which writes chunks to disk as the engine produces them.
import polars as pl
(
pl.scan_csv("events.csv")
.filter(pl.col("amount") > 0)
.with_columns((pl.col("amount") * 100).cast(pl.Int64).alias("amount_cents"))
.sink_parquet("events_clean.parquet")
)Memory use here stays near the chunk size, however large events_clean.parquet becomes. You can then scan the output lazily and continue with a smaller follow-up query:
import polars as pl
totals = (
pl.scan_parquet("events_clean.parquet")
.group_by("user_id")
.agg(pl.col("amount_cents").sum().alias("total_cents"))
.collect(engine="streaming")
)Splitting a pipeline into a large "clean and write" stage and a small "aggregate and collect" stage is a common pattern. Each stage fits in memory, and the intermediate file can be reused.
A decision flow
Common mistakes
- Collecting a row-level result "just to look". Use
head,top_k, or apl.len()count instead. - Treating an aggregate as small. A
group_byon a near-unique key such asuser_idor a session ID produces about as many rows as the input. Check the group count withpl.col("user_id").n_unique()first. - Converting to pandas at the end.
.to_pandas()copies the data, so peak memory can reach roughly twice the result size. Keep the result small before converting. - Sorting the full input to get a small answer. Reduce first, or use
top_k. - Casting too aggressively. A silent range or precision error is worse than an out-of-memory error. Verify ranges before narrowing types.
Summary of the working model
The streaming engine keeps intermediate memory bounded, but the final DataFrame is yours to size. Estimate the row count and bytes per row. Shrink with column selection, filters, aggregation, top_k, and narrower dtypes. When the output is large by design, sink it to disk and scan it again.
Exercise
A query scans 500 GB of Parquet, filters to status == "ok" (about 90% of rows), selects all columns, and calls collect(engine="streaming"). It fails with an out-of-memory error. Name two changes that could fix it without changing the answer you need, which is total amount per user. Then describe what you would do if the number of users is itself too large to fit in memory.
Show answer
First, select only userid and amount, and aggregate with groupby("userid").agg(pl.col("amount").sum()) so the result has one row per user instead of about 90% of the input rows. The filter alone does not help much because it keeps most rows. If the per-user result is still too large, do not collect it. Call sinkparquet on the aggregated lazy query to write it to disk, then scan that file for later steps. Be aware that the group_by itself needs memory proportional to the number of groups.