Sub topic 10
Memory limits and larger-than-memory data
This chapter assumes you can read basic pandas and Polars code, know what a Parquet file is (see the columnar formats chapter), and understand the difference between eager and lazy execution. It covers how to estimate whether a dataset fits in RAM, what each tool does when it does not, and which techniques keep a job alive.
Why "fits in memory" is not the file size
The size of a file on disk tells you little about the memory a job needs. Three factors change the number.
- Encoding and compression. A Parquet file is compressed and column-encoded. The same data in memory is often several times larger. A CSV file is plain text, so its in-memory size can be smaller or larger depending on the types.
- Data types. An integer column stored as 64-bit values uses 8 bytes per row. A string column in pandas with the default
objecttype stores a pointer to a separate Python string object per row, which costs far more than the characters themselves. - Working copies. Operations create intermediate results. A sort, a join, or a group-by builds new arrays or hash tables beside the input.
A working rule for eager engines such as pandas is that you need free RAM of about two to five times the in-memory size of the data. The range depends on the operations you chain. Treat it as a starting point, then measure.
Measuring before you guess
Measure a sample, then scale up. This pandas example shows how much a type change saves.
import pandas as pd
df = pd.DataFrame(
{
"region": ["eu", "us", "apac", "eu"] * 250_000,
"revenue": range(1_000_000),
}
)
before = df.memory_usage(deep=True).sum() / 1e6
print(f"before: {before:.1f} MB")
df["region"] = df["region"].astype("category")
df["revenue"] = pd.to_numeric(df["revenue"], downcast="integer")
after = df.memory_usage(deep=True).sum() / 1e6
print(f"after: {after:.1f} MB")deep=True makes pandas count the memory used by the string objects. Without it, the object column looks much smaller than it is. The category type stores each distinct string once and keeps a small integer code per row. That helps most when a column has few distinct values compared to its row count.
To estimate a full dataset, load a representative sample, such as the first million rows, measure it, and multiply by the ratio of total rows to sample rows. Check that the sample includes the longest strings, because string columns are the usual source of surprises.
What happens at the limit
Each tool fails or degrades in its own way.
| Tool | Behavior when data exceeds RAM | Main remedy |
|---|---|---|
| pandas | Raises `MemoryError`, or the operating system kills the process | Read fewer columns, smaller types, chunking |
| Polars (eager) | Same as pandas: the whole DataFrame must fit | Switch to the lazy API |
| Polars (lazy) | Streaming engine processes data in batches for supported operations | `collect` with the streaming engine |
| DuckDB | Spills intermediate state to a temporary directory on disk | Set `memory_limit` and `temp_directory` |
| Spark | Spills to executor disks and spreads partitions over machines | Tune partitions and executor memory |
Two points deserve emphasis. First, the operating system's out-of-memory killer often ends the process without a Python traceback, so a job that "just disappears" is usually a memory problem. Second, "supported operations" in Polars streaming matters. Some operations cannot run in batches, and the engine may fall back to loading data into memory. Check the plan with explain() or test on a large sample.
Technique 1: read less
The cheapest fix is to load only what you need. Columnar formats make this effective, because unread columns are never decoded.
import pandas as pd
df = pd.read_parquet("sales.parquet", columns=["region", "revenue"])Filtering rows early helps as well. Parquet stores min/max statistics per row group, and engines such as DuckDB, Polars lazy, and Spark use them to skip groups that cannot match a filter. This is called predicate pushdown. The lazy optimization chapter explains it in detail.
Technique 2: process in chunks with pandas
If you must stay with pandas, split the work. This works when the result can be built from partial results, such as sums and counts. It does not work directly for operations that need all rows at once, like a median or a global sort.
import pandas as pd
total = None
reader = pd.read_csv(
"sales.csv",
usecols=["region", "revenue"],
chunksize=1_000_000,
)
for chunk in reader:
part = chunk.groupby("region")["revenue"].sum()
total = part if total is None else total.add(part, fill_value=0)
print(total)Each pass holds one chunk plus a small partial result. The fill_value=0 argument handles regions that appear in one chunk but not another. An average needs a sum and a count kept separately, then divided at the end.
Technique 3: let a lazy engine stream
Polars can run a lazy query in batches, so the whole file never sits in memory. Recent Polars releases select the streaming engine through the engine argument of collect. Older releases used streaming=True, so check your installed version.
import polars as pl
result = (
pl.scan_parquet("sales.parquet")
.filter(pl.col("revenue") > 0)
.group_by("region")
.agg(pl.col("revenue").sum())
.collect(engine="streaming")
)
print(result)The result must still fit in memory. A group-by with a few regions produces a tiny result, but a group-by on a column with hundreds of millions of distinct values does not.
Technique 4: use an engine that spills
DuckDB handles larger-than-memory work by writing intermediate data to disk during joins, sorts, and aggregations. You control the budget and the spill location.
import duckdb
con = duckdb.connect()
con.sql("SET memory_limit = '4GB'")
con.sql("SET temp_directory = '/tmp/duckdb_spill'")
result = con.sql(
"SELECT region, sum(revenue) AS revenue "
"FROM 'sales.parquet' GROUP BY region"
).df()
print(result)Spilling trades speed for survival. A query that spills runs slower than one that fits in memory, and it needs free disk space in the temporary directory. Some operators spill more gracefully than others, and a query can still fail if a single stage needs more memory than the limit allows, so set the limit below the machine's real RAM to leave room for Python and the operating system.
Spark spills too, and it adds a second option: more machines. Its memory use is set through executor settings and the number of partitions. If a single partition is too large for one executor, tasks fail even when the cluster as a whole has plenty of memory. Increasing the partition count shrinks each piece.
Choosing a response
The diagram shows the order in which to try the options. Each step costs more effort than the one before it.
Most teams stop at the third box. A modern single machine with a fast SSD and 64 GB or more of RAM can process datasets many times larger than its memory with DuckDB or Polars, so Spark is rarely forced by memory alone. The distribution costs chapter covers when other factors push you there.
Common mistakes
- Measuring the file instead of memory. A 2 GB Parquet file can need 10 GB or more when loaded.
- Forgetting
deep=True. pandas underreports string columns without it. - Setting
memory_limitequal to total RAM. The process and the operating system need space too. - Assuming streaming covers every query. Verify with
explain()and a large test run. - Ignoring result size. Streaming and spilling bound the working memory, not the output.
Exercise
A 6 GB Parquet file expands to about 20 GB in pandas. Your machine has 16 GB of RAM. You need the total revenue per region, and the Parquet file has 40 columns, of which you need two. Name two steps, in order of increasing effort, that could let you finish without adding hardware.
Show answer
First, read only the two needed columns with pd.read_parquet(..., columns=["region", "revenue"]). This likely shrinks the memory need to a small fraction of 20 GB, because 38 columns are never loaded, and you can also convert region to category. If the data still does not fit, switch to an engine that streams or spills, such as pl.scan_parquet(...).collect(engine="streaming") in Polars or the same SQL in DuckDB with a memory_limit set below 16 GB. Chunked reading in pandas is another option, but it works poorly with Parquet unless you read by row group.