Sub topic 1
Why Large Data Breaks Eager Pipelines
Prerequisites
Assume you know basic Python, DataFrames, and Polars expressions such as pl.col, filter, with_columns, and group_by. You should also recognize CSV and Parquet files.
Why Large Data Breaks Eager Pipelines
An eager operation runs immediately. When you read a file eagerly, Polars creates a DataFrame containing the input rows and columns before filtering or selecting anything.
import polars as pl
df = pl.read_csv("events.csv")
result = df.filter(pl.col("status") == "ok").select("user_id", "amount")This pipeline may use much more memory than the final result requires. The complete input must fit in memory, and intermediate DataFrames can require additional space. If the file and intermediate data exceed available RAM, the process can fail with an out-of-memory error.
From Eager DataFrames to Lazy Queries
A lazy query describes work without running it immediately. Polars can inspect the complete query, optimize it, and execute it later.
import polars as pl
query = (
pl.scan_csv("events.csv")
.filter(pl.col("status") == "ok")
.select("user_id", "amount")
)
result = query.collect(engine="streaming")collect starts execution. The streaming engine processes compatible work in chunks instead of requiring the entire input at once. The final result still must fit in memory, so streaming does not make every result memory-free.
Scanning Files Instead of Reading Them
Use scan_csv or scan_parquet to create a LazyFrame from a file. scan_parquet can also read a group of files:
lf = pl.scan_parquet("events/*.parquet")A scan lets Polars avoid reading unnecessary columns and rows. Parquet usually works better than CSV because it stores columns separately and includes metadata that helps skip irrelevant data. Partitioning files by a commonly filtered field, such as date, can reduce the amount read.
Reading the Query Plan
Use explain before collecting a query:
print(query.explain())The optimized plan should show the filter and selected columns close to the file scan. This indicates predicate pushdown and projection pushdown. Predicate pushdown moves filtering toward the scan. Projection pushdown reads only required columns. Both reduce input and memory use.
Exercise
Why can a lazy query still run out of memory?
Show answer
Its final result or an intermediate operation may be too large, or the query may contain an operation that needs substantial memory.