Sub topic 10
Memory limits and larger-than-memory data
This chapter assumes you know basic pandas, can read a Parquet file, and understand the eager and lazy execution models from earlier chapters. It covers how to estimate whether data fits in RAM and what each tool does when it does not.
Estimating whether data fits
File size on disk is a poor guide. Parquet is compressed and columnar, so the same data often takes 3 to 10 times more space once loaded. Strings and Python objects expand the most.
A rough in-memory estimate is rows × columns × bytes per value. For example, 100 million rows of 5 numeric columns at 8 bytes each is about 4 GB. Operations such as joins, sorts, and group-bys create intermediate copies, so plan for peak memory of 2 to 5 times the loaded size.
import pandas as pd
df = pd.read_parquet("sales.parquet", columns=["region", "revenue"])
print(df.memory_usage(deep=True).sum() / 1e9, "GB")Use deep=True. Without it, pandas does not count the memory held by string values.
What each tool does at the limit
| Tool | Behavior when data exceeds RAM |
|---|---|
| pandas | Loads everything eagerly. Raises `MemoryError` or the operating system kills the process. |
| Polars | The lazy API can stream in chunks with `collect(engine="streaming")`. Not every operation supports streaming. |
| DuckDB | Spills intermediate results to a temporary directory when it hits its memory limit. Many operators work out of core. |
| Spark | Partitions data across executors and spills to disk. Capacity grows with the cluster. |
Reduce what you load
Before changing tools, load less. This works in every tool.
- Read only the columns you need.
- Filter rows as early as possible. Parquet readers can skip row groups using statistics.
- Use smaller types, such as
int32instead ofint64, or categoricals for repeated strings. - Process the data in chunks and combine partial results.
import pandas as pd
df = pd.read_parquet("sales.parquet", columns=["region", "revenue"])
df["region"] = df["region"].astype("category")
print(df.memory_usage(deep=True).sum() / 1e9, "GB")Streaming and spilling in practice
DuckDB lets you set a memory cap and a spill location. A query over a file larger than RAM then runs, though more slowly.
import duckdb
con = duckdb.connect()
con.execute("SET memory_limit = '4GB'")
con.execute("SET temp_directory = '/tmp/duckdb_spill'")
result = con.sql(
"SELECT region, sum(revenue) AS revenue "
"FROM 'sales.parquet' GROUP BY region"
).df()
print(result)Here the group-by result is small, so the query needs little memory even when the file is huge. Large outputs and high-cardinality groupings are what push a query into spilling.
Common errors
- Judging by file size instead of in-memory size.
- Forgetting peak memory during joins and sorts.
- Assuming Polars streaming covers every operation. Check the query plan or test it.
- Pointing the DuckDB temp directory at a small disk, which then fills up.
- Moving to Spark when one machine with spilling would be enough. A bigger machine is often cheaper than a cluster.
Exercise
A 3 GB Parquet file holds 40 million rows of mostly string columns. You want to join it to a similar table in pandas on a 16 GB laptop. Why might this fail, and what are two ways to avoid it?
Show answer
Strings expand a lot in memory, so each table may take far more than 3 GB, and a join creates further copies. Peak memory can exceed 16 GB. Two fixes: load only the needed columns and filter early, or run the join in DuckDB or Polars lazy mode, which can spill or stream instead of loading everything.