Sub topic 8
Sinking results straight to disk
This chapter assumes you can write a lazy Polars query with scan_csv or scan_parquet, and that you know what collect(engine="streaming") does. Here you will learn how to stop a query's output from ever becoming an in-memory DataFrame.
Why collecting is not always enough
Streaming the input solves only half of the memory problem. Take a query that scans a 200 GB CSV and keeps most of its rows. If you call collect(engine="streaming"), the engine reads the input in chunks, but it must also assemble every output row into one DataFrame in memory. A result that is larger than RAM still fails.
A sink solves this. A sink is a terminal operation on a LazyFrame that runs the query and writes each finished chunk to a file as it is produced. The full result never exists in memory.
The first sink: sink_parquet
Replace collect() with sink_parquet(). The call below creates a small input file first, so you can run it as shown.
import polars as pl
# Create a small sample input so the example runs as written.
pl.DataFrame(
{
"user_id": [1, 2, 3, 4],
"status": ["ok", "ok", "error", "ok"],
"amount": [10.5, -2.0, 7.25, 3.0],
}
).write_csv("events.csv")
lf = (
pl.scan_csv("events.csv")
.filter(pl.col("amount") > 0)
.with_columns((pl.col("amount") * 100).cast(pl.Int64).alias("amount_cents"))
)
lf.sink_parquet("events_clean.parquet")
print(pl.read_parquet("events_clean.parquet"))Three details matter here:
sink_parquetreturnsNone. It does not give you a DataFrame or a LazyFrame to keep working with, and it runs the query immediately.- You do not pass
engine="streaming". Sinks run on the streaming engine by design. - The last line reads the output back only because this sample file is tiny. With real data you would scan it again instead, with
pl.scan_parquet("events_clean.parquet").
The input is optimized exactly as in a normal lazy query. Filters and column selection are still pushed down to the scan, so the sink only processes the rows and columns it needs.
Choosing a sink function
Each output format has its own sink method on LazyFrame.
| Method | Output format | Typical use |
|---|---|---|
| `sink_parquet` | Parquet | Default choice. Compressed, columnar, and fast to scan again. |
| `sink_csv` | CSV | Handing data to tools that only read text. |
| `sink_ipc` | Arrow IPC (Feather v2) | Fast reload with little decoding work. |
| `sink_ndjson` | Newline-delimited JSON | Log pipelines and tools that read one JSON object per line. |
Prefer Parquet for intermediate results. A later query can scan it with pushdown and read only the columns it needs, which CSV cannot offer. The Parquet sink also accepts options such as compression (for example "zstd"), compression_level, row_group_size, and statistics. Row groups are the blocks that Parquet readers can skip. Writing reasonably sized row groups with statistics gives later scans more to skip.
import polars as pl
lf = pl.scan_csv("events.csv").filter(pl.col("status") == "ok")
lf.sink_parquet(
"events_ok.parquet",
compression="zstd",
row_group_size=100_000,
)Output order and speed
By default a sink keeps rows in the order the query produces them. The engine processes chunks in parallel, so preserving order means it may have to hold finished chunks until earlier ones are written. If your downstream consumer does not depend on row order, you can tell the sink it may write chunks as they finish:
import polars as pl
pl.scan_csv("events.csv").filter(pl.col("amount") > 0).sink_parquet(
"events_unordered.parquet",
maintain_order=False,
)Use this only when order is truly irrelevant. Without a sort, the order of unordered output can differ between runs.
Creating the output folder
A sink writes one file at a time and does not create missing parent directories unless you ask it to. Pass mkdir=True to create them:
import polars as pl
pl.scan_csv("events.csv").sink_parquet("out/clean/events.parquet", mkdir=True)Without mkdir=True, a path inside a folder that does not exist raises an error.
Running several sinks from one query
Sometimes you want several outputs from one scan, for example a cleaned copy and a summary. Running two separate sinks reads the input twice. In recent Polars versions, you can pass lazy=True to a sink. It then returns a LazyFrame that has not run yet, and pl.collect_all runs all of them together so shared work is not repeated.
import polars as pl
base = pl.scan_csv("events.csv").filter(pl.col("amount") > 0)
clean = base.sink_parquet("clean.parquet", lazy=True)
totals = (
base.group_by("user_id")
.agg(pl.col("amount").sum().alias("total_amount"))
.sink_parquet("totals.parquet", lazy=True)
)
pl.collect_all([clean, totals])What a sink does not remove
A sink moves the output off the memory budget. It does not change what the operators in the middle of the query need.
- A streaming
filter,select, orwith_columnsholds only the current chunks, so a sink makes these stages cheap. - A
group_bymust keep one running state per group until the last row arrives. A query that groups by a high-cardinality column can still exhaust memory even when it ends in a sink. - A
joinnormally builds a hash table from one side. That side must fit in memory. - A
sortof the whole dataset needs all rows before it can emit the first output row.
The sink writes whatever these operators emit, but it cannot make them smaller. Later chapters cover these operators and how to reduce their memory use.
Common mistakes
- Collecting, then writing.
lf.collect(engine="streaming").write_parquet(path)still builds the full DataFrame in memory. Uself.sink_parquet(path)instead. - Chaining after the sink. The sink is the last step. Add any filtering or column work before it, not after it.
- Overwriting your input. Do not sink to the same path you are scanning. The reader and writer will conflict, and you can corrupt the source. Use a different path.
- Expecting a DataFrame back. If you need the data afterwards, scan the output file again. Do not look for a return value.
- Assuming every query can stream into a sink. If the plan contains an operation the streaming engine does not support, Polars may fall back to the in-memory engine for that part, and memory use rises. Check the plan with
lf.explain()before running on the full dataset.
Verifying the result
After a long sink, confirm the output without loading it. A lazy scan reads only what it needs:
import polars as pl
rows = pl.scan_parquet("events_clean.parquet").select(pl.len()).collect()
print(rows)This reads little data and tells you how many rows were written. Compare it with the count you expect from the source.
Exercise
You have a 150 GB directory of Parquet files. You want every row where status == "ok" and amount > 0, keeping only the columns user_id and amount, saved as one new Parquet file. The result is about 60 GB and your machine has 16 GB of RAM. Write the query, and explain why collect(engine="streaming") followed by write_parquet is the wrong approach.
Show answer
Use a lazy scan and a sink: pl.scan_parquet("events/*.parquet").filter((pl.col("status") == "ok") & (pl.col("amount") > 0)).select("user_id", "amount").sink_parquet("ok_events.parquet"). The collect approach builds the whole 60 GB result as a DataFrame before write_parquet runs, so it needs more memory than the machine has, even though the input was read in chunks. The sink writes each chunk to the file as it is produced and releases it, so memory stays near the size of a few chunks.