Generic selectors
Exact matches only
Search in title
Search in content
Post Type Selectors
Filter by Categories
About Article
AI Tools
Analyze Data
Archive
Best Practices
Better Outputs
Blog
Code Optimization
Code Quality
Command Line
Course
Daily tips
Dashboard
Data Analysis & Manipulation
Data Engineer
Data Visualization
DataFrame
Delta Lake
DevOps
DuckDB
Environment Management
Feature Engineer
Git
Jupyter Notebook
LLM
LLM Tools
Machine Learning
Machine Learning & AI
Machine Learning Tools
Manage Data
MLOps
Natural Language Processing
Newsletter Archive
NumPy
Pandas
Polars
PySpark
Python Helpers
Python Tips
Python Utilities
Scrape Data
SQL
Testing
Time Series
Tools
Visualization
Visualization & Reporting
Workflow & Automation
Workflow Automation

DuckDB 2.0 vs Polars 2.2: Which Is Better for Big Data?

DuckDB 2.0 vs Polars 2.2: Which Is Better for Big Data?

Table of Contents

Introduction

When a group-by or join needs more memory than you have, your query might fail if the engine can’t spill to disk. DuckDB has been able to spill for years, which gave it an advantage over Polars when memory is tight, as covered in pandas vs Polars vs DuckDB.

Polars 2.x now does it too, for both group-bys and joins. That means both tools can run a group-by or a join on data bigger than the memory they have, but which one performs better at different memory sizes?

To find out, I ran the same group-by and the same join in DuckDB 2.0 and Polars 2.2 under different memory limits and compared the results. By the end, you’ll know which tool to reach for, depending on your memory and your query.

💻 Get the Code: The scripts are on GitHub.

Stay Current with CodeCut

Easy-to-digest articles on Python, AI, and open-source tools. Delivered twice a week.

What Is Spilling to Disk?

A group-by or join keeps a working table in memory while it runs. The bigger the data, the bigger that table gets.

When that working table outgrows the memory limit, there’s nowhere to put the next row, so the process runs out of memory and stops.

Spilling to disk avoids that. The engine splits the work into parts, keeps the parts that fit in memory, and writes the rest to temporary files to process one at a time later.

without spilling                      with spilling

memory  [████████████████] full       memory  [██████     ]  part 1, now
        -> out of memory, stops       disk    [░░░░] [░░░░]  parts 2 and 3, later

While spilling to disk avoids running out of memory, it has some drawbacks:

  • Time: writing to disk and reading back is slower than staying in memory.
  • Disk space: on a very large query, the temporary files can fill your free disk.

DuckDB and Polars can both spill to disk, but that doesn’t mean they take the same time or use the same memory. The rest of this article tests which one performs better at different memory limits.

Results at a Glance

  • Memory: DuckDB 2.0 needed less memory than Polars 2.2 to finish both queries.
  • Speed: With tight memory, DuckDB ran the group-by faster than Polars, but Polars ran the join faster than DuckDB.
ResultDuckDB 2.0Polars 2.2Better
Memory needed to finish the join2 GB2.5 GBDuckDB
Memory needed to finish the group-by1 GB1.5 GBDuckDB
Join time with tight memory3.20 s2.00 sPolars
Group-by time with tight memory0.46 s0.76 sDuckDB

Group-By Performance

The data is 34 million NYC yellow taxi trips from 2024, in 10 monthly files. The group-by counts trips and averages the fare per pickup zone, dropoff zone and hour. That’s 12.4 million groups, so the result alone takes a lot of memory.

In DuckDB, any SQL query can spill to disk when it runs out of memory.

import duckdb

con = duckdb.connect()
routes_by_hour = con.sql("""
    SELECT PULocationID, DOLocationID,
           date_trunc('hour', tpep_pickup_datetime) AS pickup_hour,
           count(*) AS trips, avg(fare_amount) AS avg_fare
    FROM '/data/yellow_tripdata_2024-*.parquet'
    GROUP BY ALL
""").to_arrow_table()  # columnar result, like Polars

In Polars, the query has to be lazy (scan_parquet, then collect) to spill to disk.

import polars as pl

months = [f"/data/yellow_tripdata_2024-{m:02d}.parquet" for m in range(1, 11)]
routes_by_hour = (
    pl.scan_parquet(months)  # scan the Parquet files lazily
    .group_by(
        "PULocationID",
        "DOLocationID",
        pl.col("tpep_pickup_datetime").dt.truncate("1h").alias("pickup_hour"),
    )
    .agg(pl.len().alias("trips"), pl.col("fare_amount").mean().alias("avg_fare"))
    .collect()  # run the query, spilling if needed
)

I ran each query at least 3 times in a Docker container at memory limits from 6 GB down to 1 GB, and the charts show the median. The speed gaps held in every run, not just the median. The example README has the full setup. Here is how each one did as the memory shrank.

At 6 and 4 GB, both tools have room to spare, so their peak memory barely changes. Polars uses about 1 GB more than DuckDB, or about 75% more.

Grouped bar chart of group-by peak memory at 6 and 4 GB limits. DuckDB 2.0 uses 1,505 and 1,534 MB. Polars 2.2 uses 2,605 and 2,697 MB.

At 1.5 GB, Polars starts spilling to disk to stay under the limit, while DuckDB still fits in memory. At 1 GB, DuckDB spills about 80 MB and finishes, while Polars is killed every time before it writes anything to disk.

Grouped bar chart of group-by peak memory at 1.5 and 1 GB limits. DuckDB 2.0 uses 1,140 and 908 MB. Polars 2.2 uses 1,360 MB at 1.5 GB and is killed at 1 GB.

Speed barely changes with the limit. Both tools finish in under a second.

Takeaway: For a large group-by, DuckDB is the safer choice when memory is tight.

Join Performance

The join matches two tables, rides and payments, on trip_id. Each has 100 million rows.

To join in DuckDB, use a SQL query with a JOIN clause.

tips_by_zone = con.sql("""
    SELECT r.PULocationID, avg(p.tip_amount) AS avg_tip
    FROM '/data/rides.parquet' r
    JOIN '/data/payments.parquet' p USING (trip_id)
    GROUP BY ALL
""").to_arrow_table()

To join in Polars, call join on two lazy frames from scan_parquet.

rides = pl.scan_parquet("/data/rides.parquet")
payments = pl.scan_parquet("/data/payments.parquet")

tips_by_zone = (
    rides.join(payments, on="trip_id")
    .group_by("PULocationID")
    .agg(pl.col("tip_amount").mean().alias("avg_tip"))
    .collect()
)

At 6 and 4 GB, the two tools are close in speed, at about 2 seconds each. Below that, DuckDB starts spilling to disk and slows down as memory shrinks, while Polars’ speed stays about the same.

Grouped bar chart of join time at 3, 2.5 and 2 GB limits. DuckDB 2.0 takes 2.44, 3.20 and 4.85 seconds. Polars 2.2 takes 1.85 and 2.00 seconds at 3 and 2.5 GB, and is killed at 2 GB.

A likely reason is how much each tool writes to disk. Polars spills a little at every limit, while DuckDB writes more and more as memory shrinks.

Memory limitDuckDB spillPolars spill
4 GB0 MB~300 MB
3 GB~950 MB~360 MB
2.5 GB~1,350 MB~420 MB
2 GB~1,730 MBkilled

But DuckDB uses about 200 MB less memory when memory is tight. That’s why it finishes at 2 GB, while Polars is killed every time. At 1 GB, neither tool finishes the join.

Grouped bar chart of join peak memory at 2.5 and 2 GB limits. DuckDB 2.0 uses 2,225 and 1,862 MB. Polars 2.2 uses 2,439 MB at 2.5 GB and is killed at 2 GB.

Takeaway: Polars is the faster choice for a large join when memory is tight, but DuckDB is the safer one.

Conclusion

DuckDB 2.0 needs less memory than Polars 2.2 to finish both queries. Polars 2.2 can be faster on a large join when memory is tight.

But I think that speedup isn’t worth giving up DuckDB’s safety. If you work with large data on a small machine, use DuckDB.

If you already have a Polars pipeline and some memory to spare, you don’t need to rewrite it in DuckDB. Polars 2.2 can spill to disk now, and on large joins it can even be faster.

References

Related Tutorials

Stay Current with CodeCut

Easy-to-digest articles on Python, AI, and open-source tools. Delivered twice a week.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top

Work with Khuyen Tran

Work with Khuyen Tran