Skip to main content

Data analysis · Advanced · 18 min

Process a file bigger than memory with Polars streaming

By Padding · Updated 18 Nov 2026
Python 3.15 · Polars 2.2.0 · uv 0.13 · GNU time (checked on python:3.15-slim, Debian 13)

You will query a 12-million-row partitioned Parquet dataset with Polars 2.2 lazily, let pushdown skip the files and columns you do not need, run it on the streaming engine, write a result to disk with sink_parquet, and measure each script's peak memory so you can see which operations still pull data into RAM.

On this page

A file that is bigger than your computer's memory cannot be loaded with read_parquet or read_csv: the process grows until the operating system kills it. Polars has a different way in. You describe the query lazily, Polars works out which files, columns and rows it really needs, and the streaming engine pushes the data through in batches, so only a slice of it sits in memory at any moment.

Streaming is not magic, though. Some operations need to see every row before they can answer, and those quietly hold data in RAM. The only reliable way to know what a query costs is to measure it, so in this tutorial every script runs under /usr/bin/time, which reports the peak memory the process used.

You generate a year of sales as 12 monthly Parquet files (12 million rows, about 100 MB on disk and close to 500 MB once loaded). That is small enough to load in full, which you do once to get a baseline, and big enough that the difference between loading and streaming is obvious. The same scripts work unchanged on a dataset 100 times larger, where only the streaming versions would finish.

This matters most on modest hardware. A 4 GB or 8 GB laptop, common for analysts across Nigeria and much of Africa, can work through a dataset several times its RAM this way, and Parquet files are a fraction of the size of the same data as CSV, which helps when you download them on prepaid data.

Everything lives in ~/polars-stream-demo, so you can delete it in one go at the end.

Step 1 · Create the project and install the tools

Make the project and add Polars at an exact version, so the plans and output you see match this page:

Bash
mkdir -p ~/polars-stream-demo
cd ~/polars-stream-demo
uv init --no-package --python 3.15
uv add "polars==2.2.0"

Peak memory comes from GNU time, a separate program from the time keyword built into your shell. On Ubuntu and Debian it is the time package:

Bash
sudo apt update
sudo apt install -y time

Check it worked

Bash
cd ~/polars-stream-demo
uv run python -c "import polars; print(polars.__version__)"
/usr/bin/time --version

The first line reads 2.2.0. The second starts with time (GNU Time) and a version number.

Step 2 · Generate a partitioned Parquet dataset

Create make_data.py. It writes one Parquet file per month into folders named month=01 to month=12. This layout is called Hive partitioning: the folder name carries a column value, so a query can skip whole folders without opening them. The script builds the rows from a hash of the row number, so the data is the same every time you run it, and it writes one month at a time so the generator itself never holds the whole year.

Bash
cd ~/polars-stream-demo
cat > make_data.py <<'PY'
import sys
from datetime import date
from pathlib import Path

import polars as pl

ROWS_PER_MONTH = int(sys.argv[1]) if len(sys.argv) > 1 else 1_000_000
out = Path("sales")

for month in range(1, 13):
    start = date(2025, month, 1)
    end = date(2025, month + 1, 1) if month < 12 else date(2026, 1, 1)
    days = (end - start).days
    i = pl.int_range(ROWS_PER_MONTH, dtype=pl.Int64)
    h = (i + month * ROWS_PER_MONTH).hash(seed=42)
    df = pl.select(
        order_id=i + (month - 1) * ROWS_PER_MONTH,
        day=pl.lit(start) + pl.duration(days=(h % days)),
        store=(h // 7 % 500).cast(pl.Int32),
        product=(h // 11 % 10_000).cast(pl.Int32),
        channel=pl.lit(["app", "web", "shop"]).list.get((h // 13 % 3).cast(pl.Int64)),
        qty=(h // 17 % 10 + 1).cast(pl.Int16),
        unit_price=((h // 19 % 50_000) / 100 + 0.5).cast(pl.Float64),
    )
    folder = out / f"month={month:02d}"
    folder.mkdir(parents=True, exist_ok=True)
    df.write_parquet(folder / "part-0.parquet")
    print(f"month {month:02d}: {df.height:,} rows")
PY
uv run python make_data.py

Each row is one order line: a day, a store (500 of them), a product, a sales channel (app, web or shop), a quantity and a unit price. The optional argument sets the rows per month, so uv run python make_data.py 10000000 gives you 120 million rows later if you want to push your machine.

Check it worked

Bash
cd ~/polars-stream-demo
ls sales
du -sh sales
uv run python -c "import polars as pl; print(pl.scan_parquet('sales/', hive_partitioning=True).select(pl.len()).collect().item())"

You see 12 folders from month=01 to month=12, a total of roughly 100 MB, and the row count 12000000. The count comes back almost instantly: Parquet stores row counts in each file's footer, so Polars did not read a single row to answer.

Step 3 · Measure the eager baseline

The question for the rest of the tutorial: which stores took the most revenue from app orders in June, July and August? Answer it first the way most scripts start, by loading everything and then filtering. Create eager.py:

Bash
cd ~/polars-stream-demo
cat > eager.py <<'PY'
import polars as pl

df = pl.read_parquet("sales/", hive_partitioning=True)
print(f"loaded {df.height:,} rows, {df.estimated_size('mb'):,.0f} MB in memory")

summer_app = df.filter(pl.col("month").is_between(6, 8), pl.col("channel") == "app")
result = (
    summer_app.group_by("store")
    .agg(revenue=(pl.col("qty") * pl.col("unit_price")).sum(), orders=pl.len())
    .sort("revenue", descending=True)
)
print(result.head(3))
PY

Run it under GNU time. -v asks for the full resource report and -o writes that report to a file, so it does not mix with the script's own output. Call the project's Python directly from .venv/bin/python rather than through uv run, so the figure is for your script alone:

Bash
cd ~/polars-stream-demo
/usr/bin/time -v -o mem-eager.txt .venv/bin/python eager.py
grep "Maximum resident set size" mem-eager.txt

On macOS, GNU time is not there by default, so skip the apt steps in step 1. The built-in /usr/bin/time takes -l instead and reports bytes, not kilobytes. Use the same swap for every later measurement (stream.py, sink.py, median.py):

Bash
/usr/bin/time -l .venv/bin/python eager.py 2>&1 | grep "maximum resident set size"

Check it worked

The script prints loaded 12,000,000 rows, 473 MB in memory (or close to it), then the top three stores, each with a revenue near 3 million and about 2,100 orders. The grep line shows the peak, something like Maximum resident set size (kbytes): 1200000, which is about 1.2 GB.

That peak is more than twice the size of the table itself. Polars decodes several files at once, and the filter creates a second, smaller copy before the first is freed. This is the number to beat. Make a note of it.

Step 4 · Build a lazy query and read its plan

Swap read_parquet for scan_parquet. A scan reads nothing yet: it returns a LazyFrame, a description of the query that Polars can optimise before it touches the disk. Create query.py, which builds the same question and prints the optimised plan instead of running it:

Bash
cd ~/polars-stream-demo
cat > query.py <<'PY'
import polars as pl

query = (
    pl.scan_parquet("sales/", hive_partitioning=True)
    .filter(pl.col("month").is_between(6, 8), pl.col("channel") == "app")
    .group_by("store")
    .agg(revenue=(pl.col("qty") * pl.col("unit_price")).sum(), orders=pl.len())
    .sort("revenue", descending=True)
)

print(query.explain())
PY
uv run python query.py

Read the plan from the bottom up, because that is the order the data flows in. The lines that matter look like this:

Text
      Parquet SCAN [sales/month=06/part-0.parquet, ... 2 other sources]
      PROJECT 5/8 COLUMNS
      SELECTION: (col("channel") == "app") & col("month").is_between([6, 8])

Three optimisations have happened without you asking:

  • Partition pruning. The scan lists month=06 and 2 other sources, not 12. The filter on month matched the folder names, so nine files are never opened.
  • Projection pushdown. PROJECT 5/8 COLUMNS means only the columns the query uses are read. order_id, day and product stay on disk.
  • Predicate pushdown. The SELECTION sits inside the scan, so rows are filtered as they are decoded instead of after a full table exists. Parquet also stores minimum and maximum values per chunk, which lets Polars skip chunks that cannot match.

Check it worked

Your plan shows Parquet SCAN with 3 sources (one named, ... 2 other sources), PROJECT 5/8 COLUMNS, and a SELECTION line with both conditions. If the scan lists all 12 files, check you passed hive_partitioning=True so Polars knows month is a column.

Step 5 · Collect with the streaming engine

Pushdown cuts what is read. The streaming engine then limits how much of it is held at once, by processing the data in batches and keeping only the running totals for each store. Create stream.py; the only change from a normal lazy query is engine="streaming" in collect:

Bash
cd ~/polars-stream-demo
cat > stream.py <<'PY'
import polars as pl

query = (
    pl.scan_parquet("sales/", hive_partitioning=True)
    .filter(pl.col("month").is_between(6, 8), pl.col("channel") == "app")
    .group_by("store")
    .agg(revenue=(pl.col("qty") * pl.col("unit_price")).sum(), orders=pl.len())
    .sort("revenue", descending=True)
)

result = query.collect(engine="streaming")
print(result.head(3))
print(f"{result.height} stores")
PY
/usr/bin/time -v -o mem-stream.txt .venv/bin/python stream.py
grep "Maximum resident set size" mem-stream.txt

Check it worked

The top three stores, their revenue and their order counts match the eager run, and the script prints 500 stores. The peak is a fraction of the eager one: on the laptop used to write this page it was about 140 MB against 1.2 GB. Your figures depend on your core count and memory allocator, but the gap should be large.

Raising the data size shows the point of all this. If you regenerate with make_data.py 4000000, you should see the eager peak grow roughly in line with the data, while the streaming peak grows only a little, because it depends mostly on batch size and thread count, not on row count. On a machine where even that is too much, set POLARS_MAX_THREADS=2 before the command: fewer threads means fewer batches in flight and a lower peak, at the cost of speed.

Step 6 · Write a large result with sink_parquet

The query above ends in 500 rows, so collecting it is fine. Often the output is large too: a cleaned or enriched copy of the data for the next tool. Calling collect() and then write_parquet() would build the whole result in memory first. sink_parquet runs the query on the streaming engine and writes batches to the file as they are produced.

Create sink.py. It keeps every app order from the whole year, adds a revenue column, drops channel (now always app), writes the result, and reads back only the footer and one column to check it:

Bash
cd ~/polars-stream-demo
cat > sink.py <<'PY'
import polars as pl

(
    pl.scan_parquet("sales/", hive_partitioning=True)
    .filter(pl.col("channel") == "app")
    .with_columns(revenue=pl.col("qty") * pl.col("unit_price"))
    .drop("channel")
    .sink_parquet("app_orders.parquet")
)

check = (
    pl.scan_parquet("app_orders.parquet")
    .select(rows=pl.len(), revenue=pl.col("revenue").sum())
    .collect()
)
print(check)
PY
/usr/bin/time -v -o mem-sink.txt .venv/bin/python sink.py
grep "Maximum resident set size" mem-sink.txt
ls -lh app_orders.parquet

Check it worked

The script prints a one-row table with about 4 million rows (a third of the orders are app orders) and a revenue total around 5.5 billion. app_orders.parquet is close to 50 MB. The peak is well under the eager baseline even though the output holds a third of the whole dataset: about 350 MB on the laptop used for this page, against about 430 MB for collect() followed by write_parquet() on the same query, a gap that widens as the output grows.

The same pattern converts a huge CSV you cannot open into Parquet: pl.scan_csv("big.csv").sink_parquet("big.parquet"). There are matching sink_csv, sink_ipc and sink_ndjson methods for other formats.

Step 7 · Find the operations that pull data into memory

Not every operation can stream. Polars sorts the steps of a streaming query into three kinds:

  • Streams. Scans, filters, with_columns and selects handle one batch at a time and forget it.
  • Streams but holds state. A group_by keeps one running total per group, and a sort has to keep every row it is sorting. Their memory grows with the number of groups, or the number of rows, rather than staying flat.
  • Falls back to the in-memory engine. Operations without a streaming version yet. Polars runs them the old way, which means the whole input to that step is gathered in memory first.

Polars draws this as a graph with show_graph(plan_stage="physical", engine="streaming"), which needs Graphviz installed to render. With raw_output=True it returns the graph as text instead, and the colour of each node tells you its kind. Create plan_check.py, which turns that text into a short report for four queries:

Bash
cd ~/polars-stream-demo
cat > plan_check.py <<'PY'
import re

import polars as pl

HOLDS_STATE = "0.16 0.3 1.0"
FALLBACK = "0.0 0.3 1.0"


def report(name, query):
    dot = query.show_graph(engine="streaming", plan_stage="physical", raw_output=True)
    nodes = re.findall(r'label="(.*?)"(?:,style=filled,fillcolor="(.*?)")?\];', dot)
    print(f"== {name}")
    for label, colour in reversed(nodes):
        node = label.split("\\n")[0]
        if colour == FALLBACK:
            kind = "IN-MEMORY FALLBACK"
        elif colour == HOLDS_STATE:
            kind = "streams, holds state"
        else:
            kind = "streams"
        print(f"  {node:<26} {kind}")


sales = pl.scan_parquet("sales/", hive_partitioning=True)

report("sum per store", sales.group_by("store").agg(pl.col("qty").sum()))
report("sort everything", sales.sort("unit_price"))
report("median per store", sales.group_by("store").agg(pl.col("unit_price").median()))
report("rank prices", sales.select(pl.col("unit_price").rank()))
PY
uv run python plan_check.py | tee plan.txt

The colours come from the graph's legend in Polars 2.2. Treat the script as a tool for this version: if a later release changes the colours, render the graph with Graphviz and read the legend instead.

Now measure what a fallback costs. Create median.py, which asks for the median price per store across the whole year, on the streaming engine:

Bash
cd ~/polars-stream-demo
cat > median.py <<'PY'
import polars as pl

result = (
    pl.scan_parquet("sales/", hive_partitioning=True)
    .group_by("store")
    .agg(median_price=pl.col("unit_price").median())
    .collect(engine="streaming")
)
print(f"{result.height} stores")
PY
/usr/bin/time -v -o mem-median.txt .venv/bin/python median.py
grep "Maximum resident set size" mem-median.txt

Check it worked

The report shows something like this (select steps are omitted here):

Text
== sum per store
  multi-scan[parquet]        streams
  group-by                   streams, holds state
== sort everything
  multi-scan[parquet]        streams
  sort                       streams, holds state
== median per store
  multi-scan[parquet]        streams
  in-memory-map              IN-MEMORY FALLBACK
== rank prices
  multi-scan[parquet]        streams
  columnar-function          IN-MEMORY FALLBACK

A sum per store streams with 500 small totals. A median per store needs every price, so the whole aggregation falls back, and median.py peaks several times higher than stream.py: about 525 MB against 140 MB on the laptop used for this page, even though it reads only two columns. On a file bigger than memory, that fallback is where the process would be killed.

When a fallback is unavoidable, shrink its input first: filter rows and select columns before the step, or run it one partition at a time (one month's median per store is a small job) and combine the results. Check the plan again after each change.

Step 8 · Tidy up

The next command deletes the whole demo folder, including the dataset and every result, so copy out anything you want to keep first. Nothing outside ~/polars-stream-demo was created except the time package.

Bash
rm -rf ~/polars-stream-demo

If you do not want GNU time any more, remove it with sudo apt remove time (on macOS there is nothing to remove).

Check it worked

Bash
test ! -e ~/polars-stream-demo && echo "demo folder removed"

The command prints demo folder removed.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

AI-Integrated Solutions

Get new tutorials

New tutorials, about twice a month.