Sub topic 1
Why large data breaks eager pipelines
Prerequisites
This chapter assumes you know the following:
- Basic Python: functions, imports, and running a script.
- DataFrames: rows, columns, filtering, and aggregation.
- Basic Polars expressions such as
pl.col,filter,with_columns, andgroup_by. - Common file formats such as CSV and Parquet.
You do not need to know anything about lazy queries or streaming yet. This chapter explains the problem that those features solve.
The problem in one example
Most Polars tutorials start with pl.read_csv. That call is fine for small files. It becomes a problem when the file is large.
import polars as pl
# Eager: loads the whole file into memory before any work happens.
df = pl.read_csv("events.csv")
result = df.filter(pl.col("status") == "ok").select("user_id", "amount")This code is correct. The eager version reads every row and column into memory first, which fails when the file is larger than available RAM. Only after that does the filter run. The select at the end keeps two columns, but by then every column has already been loaded.
If events.csv is 40 GB and the machine has 16 GB of RAM, the script never reaches the filter line. It stops at read_csv.
What "eager" means
An eager pipeline runs each step as soon as Python reaches the line. Each step produces a complete result before the next step starts.
read_csvparses the whole file and builds a DataFrame.filterscans that DataFrame and builds a second DataFrame with the matching rows.selectbuilds a third DataFrame with two columns.
Each line returns a full object. Polars cannot look ahead and see that you only need two columns or only the rows where status is "ok". At step 1 it has no idea what step 2 will ask for.
The final result may be small, but peak memory is set by the biggest intermediate object, and that is usually the first one.
Why the memory cost is larger than the file size
The file size on disk is a poor guide to the memory you need. Several factors push memory use above it.
- Text becomes typed columns. A CSV stores numbers as text. In memory, Polars stores them as typed arrays, such as 8 bytes per
Int64. A short number like7takes one byte in a CSV and eight in memory. A long string column may shrink or grow depending on how it is stored. - Strings carry overhead. Variable-length string columns need extra bookkeeping for offsets and, in some cases, validity information.
- Nulls need tracking. Columns that can hold missing values keep a separate validity bitmap.
- Parsing needs scratch space. Reading a CSV needs temporary buffers on top of the final columns.
- Intermediate copies add up. Each eager step can create a new DataFrame. Polars shares data between DataFrames where it can, so not every step copies everything. A
filterthat keeps most rows, however, builds new column data. The input and the output exist at the same time.
Compressed formats make the gap bigger. A Parquet file is compressed and encoded on disk. A 5 GB Parquet file can easily expand to 20 GB or more once decoded into memory.
As a rough planning rule, check your estimate against a real sample instead of trusting the file size. You can measure a sample like this:
import polars as pl
sample = pl.read_csv("events.csv", n_rows=1_000_000)
print(f"{sample.estimated_size('mb'):.1f} MB for {sample.height:,} rows")estimated_size reports the in-memory size of the DataFrame. Divide the size by the number of sampled rows, then multiply by the total row count. The result is an estimate, not a guarantee. Strings and nulls vary across a file, so a sample from the top of the file can mislead you.
How the failure shows up
An out-of-memory (OOM) failure does not always look the same. It depends on the operating system and how the program is run.
| Environment | Typical symptom |
|---|---|
| Linux with no swap | The kernel's OOM killer ends the process. You see `Killed` in the terminal and no Python traceback. |
| Linux or macOS with swap | The machine slows down sharply as it moves memory to disk. The job may finish very slowly or never. |
| Container with a memory limit | The container is killed, often with exit code 137. |
| Windows | A `MemoryError` or a process crash. |
The first row matters most. Because the process is killed from outside, Python gets no chance to raise an exception. A try/except block cannot catch it. You cannot write code that recovers from an OOM kill. You have to avoid it by design.
Why a bigger machine only postpones the problem
The simplest fix is more RAM. Sometimes that is the right call. It has limits:
- Data grows. A machine sized for this month's file may not fit next quarter's.
- Cost grows faster than size. Large-memory instances are priced at a premium.
- A laptop cannot be upgraded after the fact, and many pipelines run on laptops or small CI runners.
- Memory is not only about the input. A join or a sort can need a multiple of the input size.
The better question is whether the job needs everything in memory at once. For many pipelines it does not. A filter looks at one row at a time. A sum can be built up from partial sums. Neither needs the full dataset to exist in memory.
The core idea behind the fix
Two ideas let Polars work with data bigger than RAM. The rest of this tutorial builds on them.
- Describe the work first, then run it. If Polars sees the whole query before it reads any data, it can skip columns and rows you never use.
- Process the data in pieces. If Polars reads a chunk, works on it, and passes on the result, the whole input never has to sit in memory at once.
The first idea is lazy evaluation. The second is the streaming engine. Here is the same query written lazily and run in chunks:
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")You do not need to understand every call yet. Later chapters cover scan_parquet, the query plan, and collect(engine="streaming") one at a time. For now, notice two differences from the eager example:
- There is no read step that returns a DataFrame.
scan_parquetreturns aLazyFrame, a description of work to do. - Nothing runs until
collect. At that point Polars can optimize the whole query and run it in chunks.
Edge cases to keep in mind
Streaming does not remove every memory limit. Knowing the limits early saves debugging time later.
- The result still has to fit. If your query returns 30 GB of rows and you call
collect, the result is a DataFrame that must fit in memory. Later chapters show how to write such results to disk instead. - Some operations are memory-heavy by nature. A
group_bywith hundreds of millions of distinct keys must remember every key. Ajoingenerally needs to hold one side. Asortneeds to see all rows before it can emit the first one. - Not every operation streams. If part of a query is unsupported, Polars may fall back to the in-memory engine for that part.
- A lazy query can still be eager by accident. Calling
pl.read_csvfirst, or calling.collect()early in a pipeline, brings the data into memory and loses the benefit.
Summary of the chapter
- Eager loading reads the full file before any filter or selection can reduce it.
- In-memory size is often much larger than file size, especially for compressed Parquet.
- An OOM kill cannot be caught in Python, so the fix has to be in the design of the pipeline.
- Lazy queries let Polars see the whole job, and the streaming engine lets it work on chunks.
- Streaming reduces memory use but does not make every query fit.
Exercise
A 6 GB Parquet file is read with pl.read_parquet, then filtered to 1% of the rows, on a machine with 8 GB of RAM. The script is killed with exit code 137 during the read. Give two reasons why a 6 GB file can fail to load, and name the change in approach that would let the filter reduce the data before it is fully loaded.
Show answer
The file is compressed on disk, so the decoded in-memory data can be much larger than 6 GB. Also, the operating system, Python, and other processes need memory, and the read can need temporary buffers. The approach is to use a lazy query: pl.scan_parquet(...) followed by the filter, then collect(engine="streaming"). Polars then sees the filter before reading, and processes the data in chunks instead of loading it all first.
Exercise
Why can't you wrap pl.read_csv("events.csv") in try/except MemoryError to handle an out-of-memory failure on Linux?
Show answer
On Linux the kernel's OOM killer usually ends the process from outside. Python never gets to raise an exception, so there is nothing to catch. The pipeline has to be designed so that it does not need that much memory.