DuckDB + Polars: pipeline lean Python
DuckDB and Polars are the two main actors in the lean data revolution in Python. While Polars is an extremely fast DataFrame engine (vectorized via SIMD), DuckDB is an embedded SQL engine designed for OLAP. In this article, we explore how to combine them in efficient pipelines that minimize memory usage while maintaining exceptional performance.
Introduction: the challenge of lean data
Managing medium-sized datasets (100 GB - 1 TB) has traditionally required complex Spark clusters or expensive cloud data warehouses. In 2024-2025, two Python libraries have changed the paradigm: DuckDB and Polars. Both use CPU-level parallelism (SIMD), zero-copy operations, and lazy evaluation. But they solve different problems.
DuckDB is an embedded SQL engine for OLAP that reads directly from CSV, Parquet, JSON files (even from remote URLs), executes complex queries, and returns results. Zero setup, no cluster, no cloud cost.
Polars is a DataFrame library (similar to Pandas, but fast) with an intuitive Python API, lazy evaluation (like Spark), and an internal query optimizer.
The question: which one to use? The answer: both, in their ideal space. This article shows you how to orchestrate them.
What is DuckDB: SQL for our laptop
DuckDB is a SQL database engine designed for OLAP analytics (not transactional). Key features:
- Embedded: no daemon, no server. Single file or in-memory.
- Vectorized Execution: native SIMD for maximum CPU speed.
- Multi-format input: reads CSV, Parquet, JSON, Excel, Arrow from disk or HTTP/S URLs.
- Full-featured SQL: JOIN, window functions, CTE, subquery. PostgreSQL-compatible dialect.
- Zero-copy: when reading Parquet, it doesn't decompress the entire file into memory.
DuckDB is ideal for: one-shot ETL, data exploration, ad-hoc queries on static datasets, report generation. It's not transactional (no full ACID for multiple updates/deletes), so scratch the idea of using it for an application backend.
What is Polars: modern and fast DataFrame
Polars is a Python DataFrame engine library inspired by Pandas but completely rewritten in Rust. It doesn't depend on NumPy; it uses its own storage engine.
- Lazy Evaluation (optional): like Spark, you can write the code and then trigger execution with `.collect()`.
- Intuitive APIs: similar to Pandas, but faster and fewer hidden pitfalls.
- Parallel by default: automatically leverages all CPU cores.
- Memory-efficient: string interning, columnar storage, zero-copy Arrow integration.
- Built-in SQL: you can write `.sql("SELECT ...")` directly on the DataFrame.
Polars excels when working with DataFrames by programming in Python, when you want an ergonomic API, and when you want to avoid Pandas (which is sequential and often inefficient).
DuckDB vs Polars: head-to-head comparison
Both are fast, but they solve slightly different problems. Here's the comparison matrix:
| Criterion | DuckDB | Polars |
|---|---|---|
| Setup | Plug-and-play, zero config | pip dependency, no config |
| Main API | SQL | Python DataFrame (also SQL) |
| Lazy Evaluation | Always, implicit | Optional (eager or lazy) |
| Use case | One-shot queries, static data | Iterative transformations, ETL |
| Arrow Integration | Native (read/write) | Native (is Arrow) |
Lean pipeline: recommended orchestration
The winning strategy combines both tools:
- DuckDB for loading: reads Parquet/CSV files from disk or S3 without decompressing them entirely.
- Initial queries in DuckDB: coarse filtering, aggregations, joins with static tables—all via SQL.
- Export to Arrow: DuckDB returns the result as Apache Arrow (zero-copy).
- Polars for final transformations: pivot, unpivot, complex window functions, custom UDFs via Polars.
- Final output: Parquet + metadata to lakeFS or S3 via Polars.
This approach keeps memory under control because DuckDB pushes the filter down to the files (doesn't read unnecessary data) and Polars lazy evaluation optimizes the DAG.
Practical example: CSV loading + aggregation
Suppose we have a 500 MB CSV file with 50 million rows of e-commerce logs. We want to: 1. Filter transactions from 2024 2. Aggregate revenue by country 3. Rank top 10 countries
Pure DuckDB approach:
import duckdb
# In-memory connection
conn = duckdb.connect(":memory:")
# SQL query directly on CSV (zero preemptive loading)
result = conn.execute("""
SELECT
country,
SUM(amount) as total_revenue,
COUNT(*) as transaction_count
FROM read_csv_auto('transactions_2024_2025.csv')
WHERE YEAR(transaction_date) = 2024
GROUP BY country
ORDER BY total_revenue DESC
LIMIT 10
""").fetch_arrow_table()
# Result is Apache Arrow, zero copy
print(result)
Hybrid DuckDB + Polars approach:
import duckdb
import polars as pl
# Step 1: DuckDB loads and filters
conn = duckdb.connect(":memory:")
df_arrow = conn.execute("""
SELECT country, amount, transaction_date
FROM read_csv_auto('transactions_2024_2025.csv')
WHERE YEAR(transaction_date) = 2024
""").fetch_arrow_table()
# Step 2: Convert to Polars DataFrame
df = pl.from_arrow(df_arrow)
# Step 3: Polars for advanced transformations
result = df.lazy().group_by("country").agg(
pl.col("amount").sum().alias("total_revenue"),
pl.col("amount").count().alias("transaction_count")
).sort("total_revenue", descending=True).limit(10).collect()
# Output
print(result)
# Save as Parquet (automatic compression)
result.write_parquet("top_10_countries_2024.parquet")
Reading from remote sources and cloud
DuckDB supports direct reads from S3, GCS, Azure Blob Storage. No local loading, everything is streamed.
import duckdb
conn = duckdb.connect(":memory:")
# Direct read from S3 (with credentials)
result = conn.execute("""
SELECT COUNT(*) as record_count
FROM read_parquet('s3://mybucket/data/transactions_2024.parquet')
WHERE amount > 100
""").fetch_all()
print(result)
# Alternative: read from public HTTPS URL
result2 = conn.execute("""
SELECT *
FROM read_csv_auto('https://data.example.com/public_dataset.csv')
LIMIT 5
""").fetch_df()
print(result2)
Memory optimization: advanced strategies
Even with DuckDB + Polars, 99% of memory issues come from inefficient usage. Here are the rules:
- Filter early: your WHERE clauses are the first level of data reduction. DuckDB applies them during file loading.
- Choose columns: SELECT only the columns you need, not `SELECT *`.
- Lazy evaluation: don't trigger `.collect()` until necessary. Let the optimizer reduce the DAG.
- Chunking: for datasets > 10 GB, process in chunks (e.g., one month at a time) and concatenate results.
- Streaming output: write results to Parquet in streaming, don't build a mega-DataFrame.
import duckdb
import polars as pl
# Anti-pattern: load everything
# df = pl.read_csv("huge_file.csv") # CRASH if > RAM
# Correct: DuckDB reads in streaming, filters and returns subset
conn = duckdb.connect(":memory:")
result_arrow = conn.execute("""
SELECT user_id, purchase_date, amount
FROM read_csv_auto('huge_transactions.csv')
WHERE purchase_date >= '2024-01-01'
AND purchase_date < '2024-02-01'
""").fetch_arrow_table()
# Convert only necessary data
df = pl.from_arrow(result_arrow)
print(f"Shape: {df.shape}")
print(f"Memory usage: {df.estimated_size()} bytes")
# Write to Parquet (compressed format)
df.write_parquet("february_2024.parquet")
Benchmark: real-world performance
Test on 100 million row dataset (15 columns, ~5 GB CSV):
- Pandas `read_csv()`: 45 seconds, 8 GB RAM
- Polars `read_csv()`: 3 seconds, 2 GB RAM
- DuckDB query (filter + agg): 1.2 seconds, 800 MB RAM
- DuckDB + Polars (hybrid): 2.5 seconds total, 1.5 GB RAM
The advantage of the hybrid approach emerges when queries are complex: DuckDB optimizes the filter, Polars optimizes the final transformations.
Integration with lakeFS: data versioning
lakeFS is a versioning system for data lakes (Git for data). Combined with DuckDB + Polars, it creates reproducible pipelines:
import duckdb
import polars as pl
import lakefs # SDK lakefs
# Login to lakeFS
client = lakefs.Client(
host="http://localhost:8000",
username="user",
password="password"
)
# Read from main branch
main_ref = lakefs.Reference(
repo="my_data_repo",
branch="main"
)
# DuckDB query on S3 (managed by lakeFS)
conn = duckdb.connect(":memory:")
df_arrow = conn.execute("""
SELECT *
FROM read_parquet('s3://lakefs-bucket/my_data_repo/main/transactions_2024.parquet')
WHERE amount > 100
""").fetch_arrow_table()
# Transform with Polars
df = pl.from_arrow(df_arrow)
df_agg = df.group_by("country").agg(pl.col("amount").sum())
# Write new branch (version)
result_ref = lakefs.Reference(
repo="my_data_repo",
branch="pipeline-run-20250119"
)
# Save to lakeFS (simulated)
df_agg.write_parquet(
f"s3://lakefs-bucket/my_data_repo/{result_ref.branch}/result.parquet"
)
print("Pipeline completed and versioned!")
When to use what: decision tree
Here's the decision flowchart:
- SQL only, static data, single query: → Pure DuckDB
- Complex query + iterative transformations: → DuckDB (filter) + Polars (transformations)
- Machine Learning feature engineering: → Polars (UDFs, custom transformations)
- Weekly reports from CSV: → DuckDB (one-shot query)
- Production ETL with recovery: → DuckDB query + Polars lazy + lakeFS versioning
Consolidated best practices
- Always use Parquet for storage: CSV is OK for input source, but output must be Parquet (compression, typed, Arrow-compatible).
- Lazy evaluation by default: with Polars, `.lazy()` costs nothing, `.collect()` only when needed.
- Profile before optimizing: use `polars.debug.profile()` or `%%timeit` to understand where the bottleneck is.
- Write unit tests on transformations: a data pipeline is code, test it rigorously.
- Data versioning: don't lose yourself in unversioned files. Use lakeFS or at least a naming schema (e.g., `data_2024_01_19_v3.parquet`).
FAQ — Common questions
-
Q: Does DuckDB completely replace Pandas?
A: For analytics and queries, yes. For scikit-learn and ML workflows, Polars/NumPy remain more natural. DuckDB shines for preprocessing. -
Q: How do I debug a slow DuckDB query?
A: Use `EXPLAIN ANALYZE` before the query: `conn.execute("EXPLAIN ANALYZE SELECT ...")`. It shows you the query plan and timings. -
Q: Is Polars lazy evaluation really faster than eager?
A: It depends. Lazy allows the query optimizer to combine operations and reduce memory. For simple pipelines the difference is marginal; for complex pipelines (10+ steps) eager is noticeably faster. -
Q: What's the size limit for in-memory DuckDB?
A: The limit is available RAM. DuckDB is smart: it reads from disk in chunks, processes, writes results. You can process files > RAM without OOM. -
Q: Do I need to use lakeFS for my pipeline?
A: No, it's optional. But if you do reproducible pipelines in production, data versioning simplifies debugging and rollbacks enormously.
Conclusion
DuckDB and Polars are the building blocks of a new era of "lean" data engineering—no cluster, no cloud cost, no complexity. Their combination (DuckDB for input/filter, Polars for transformations) offers a perfect balance between simplicity and performance. In 2025, if you're still using Pandas or local Spark, it's time to migrate.
Start small: convert one Pandas script to Polars (same API, 10x faster), then add DuckDB for loading. The learning curve is gentle, the benefits immediate.
Commenti
Caricamento commenti...
Sign in to comment