Sub topic 9
Lazy evaluation and query optimization
This chapter assumes you can write basic Python, run a SQL GROUP BY, and have loaded a Parquet file with pandas. It explains what "lazy" means, why lazy engines can run a query faster than the same steps run one at a time, and where laziness causes confusion.
Eager and lazy evaluation
An eager tool runs each operation as soon as you write it. pandas works this way. After df[df.revenue > 0], the filtered rows already exist in memory. The next line starts from that result.
A lazy tool records your operations as a plan and runs nothing until you ask for a result. Polars LazyFrame, Spark, and DuckDB's relational API all work this way. The plan is a tree of steps such as scan, filter, project (choose columns), and aggregate. Before running it, the engine can rewrite the tree into a cheaper one that returns the same answer.
The distinction matters because an eager tool cannot see what comes next. When pandas reads a file, it does not know that you will use only two columns and only the rows from one region. A lazy engine sees the whole query first.
| Tool | Default style | What triggers execution |
|---|---|---|
| pandas | Eager | Every operation runs immediately |
| Polars | Eager `DataFrame`, lazy `LazyFrame` | `collect()` on a `LazyFrame` |
| DuckDB | Lazy relations and SQL | A call such as `.df()`, `.pl()`, `.fetchall()`, or `.show()` |
| Spark | Lazy | An action such as `show()`, `count()`, `collect()`, or a write |
What the optimizer does
A query optimizer is the part of an engine that rewrites a plan before running it. The common rewrites are the same across Polars, DuckDB, and Spark.
- Projection pushdown. Read only the columns the query needs. With a columnar format such as Parquet, unneeded columns are never read from disk.
- Predicate pushdown. Apply filters as early as possible, ideally inside the file reader. Parquet stores minimum and maximum values for each row group (a block of rows), so the reader can skip whole groups that cannot match.
- Filter reordering. Run filters before joins and aggregations so later steps see fewer rows.
- Common subexpression elimination. Compute an expression used several times once.
- Join planning. Choose a join strategy and, in some engines, the join order using size estimates.
Here is a Polars query, with a filter written after the column selection:
import polars as pl
lf = (
pl.scan_parquet("sales.parquet")
.filter(pl.col("revenue") > 0)
.select("region", "revenue")
)
print(lf.explain())scan_parquet does not read the file. It creates a LazyFrame. explain() prints the optimized plan without running it. In the output you should see that the scan lists only region and revenue as columns to read, and that the revenue > 0 condition is attached to the scan itself instead of being a separate step. The exact text varies between Polars versions, so read it for those two features rather than matching a fixed string.
You can compare with the unoptimized plan using lf.explain(optimized=False). Seeing both side by side is the quickest way to learn what the optimizer changed.
The same idea in each engine
DuckDB optimizes SQL in the same way. Its query reads only the columns it needs from the Parquet file, and it can use row-group statistics to skip data:
import duckdb
result = duckdb.sql(
"SELECT region, sum(revenue) AS revenue "
"FROM 'sales.parquet' GROUP BY region"
).df()
print(result)To see the plan, prefix the SQL with EXPLAIN, for example duckdb.sql("EXPLAIN SELECT ...").show().
Spark builds a logical plan, optimizes it with its Catalyst optimizer, and then produces a physical plan that runs on executors:
from pyspark.sql import SparkSession, functions as F
spark = SparkSession.builder.appName("sales").getOrCreate()
result = (
spark.read.parquet("sales.parquet")
.groupBy("region")
.agg(F.sum("revenue").alias("revenue"))
)
result.explain()
result.show()Here explain() prints the plan and show() is the action that runs it. In the physical plan, look for ReadSchema listing only the needed columns and PushedFilters when a filter is present.
pandas has no optimizer. If you write the same job with pd.read_parquet("sales.parquet") and then select columns, you read every column first. You can recover part of the benefit by hand:
import pandas as pd
df = pd.read_parquet("sales.parquet", columns=["region", "revenue"])
result = df.groupby("region", as_index=False)["revenue"].sum()
print(result)Passing columns= is projection pushdown done manually. pandas also supports filters= in read_parquet with the pyarrow engine for row-level pruning. The skill moves from the engine to you.
Why laziness reduces memory use
Optimization lowers memory as well as time. If the plan reads two of forty columns and drops most rows at the scan, the data that ever reaches memory is a small fraction of the file. Lazy engines can also process data in batches, so the whole intermediate table never needs to exist at once. This is the basis of larger-than-memory work, which a later chapter covers. In Polars you request it with collect(engine="streaming") on recent versions. Not every operation supports streaming, so check that the plan actually streams.
Common errors and gotchas
Nothing happens. A lazy pipeline with no action does no work. If a Spark job finishes instantly and writes nothing, check that you called an action or a write.
Running the work twice. In Spark, each action re-runs the plan from the source unless you cache. Calling count() and then show() on the same expensive DataFrame computes it twice. Use df.cache() when you reuse a result, and remember that the cache is itself a memory cost. In Polars, calling collect() twice on the same LazyFrame also runs the query twice. Collect once and reuse the DataFrame.
Errors appear late. Some mistakes, such as a misspelled column, surface at plan time in Polars and Spark, but a data-dependent failure, such as a bad cast, appears only when the action runs. A stack trace may point at collect() or show() rather than the line that caused it.
Timing the wrong thing. Building a lazy query takes microseconds. If you time only that part, every lazy tool looks instant. Always time through the action, including conversion to a result object.
Breaking the optimizer. Opaque code stops pushdown. In Polars, map_elements with a Python function and in Spark a Python UDF (user-defined function) are black boxes to the optimizer. It cannot know which columns they use or move filters past them. Prefer built-in expressions.
Trusting the plan blindly. The optimizer works from statistics and heuristics. It can choose a poor join strategy or fail to push a filter through a complex expression. Reading the plan is how you notice.
Choosing with laziness in mind
Laziness gives the most when the query touches a small part of a wide file, filters selectively, or chains many steps. It gives little when the work is a single pass over all columns, or when your logic is mostly custom Python functions. For interactive exploration, eager pandas is often easier, because each line shows its result and errors point at the line that caused them. For repeatable pipelines over Parquet, a lazy engine tends to be faster and lighter on memory with the same logic.
Exercise
You run pl.scan_parquet("events.parquet").filter(pl.col("country") == "DE").select("user_id") and the call returns in a few milliseconds on a 50 GB file. A colleague says the filtering is done. Is that right, and how would you check what the engine will read when you do run it?
Show answer
No. scan_parquet and the later calls only build a LazyFrame, so no filtering has happened. The work runs when you call collect(). To check what will be read, print lf.explain() and look for a scan that lists only country and user_id as columns and has the country == "DE" condition pushed into the scan.
Exercise
A Spark job calls df.count() and then df.show() on a DataFrame built from a slow join. The job takes twice as long as expected. Why, and what is one fix with its cost?
Show answer
Each action re-runs the whole plan, including the slow join, because Spark does not keep results by default. Calling df.cache() before the actions lets the second action reuse the stored result. The cost is the memory (or disk) used to hold the cached data.