Sub topic 2
How the tools execute work: eager, lazy, single-node, distributed
This chapter explains how pandas, Polars, DuckDB, and Spark run a query. It assumes you can read basic Python and SQL, that you have loaded and transformed a dataset with pandas or SQL, and that you know a table has rows, columns, and types. You do not need to have used Polars, DuckDB, or Spark.
Two separate questions describe how a tool runs work:
- When does computation happen? Right away (eager) or later, after the tool has seen the whole query (lazy).
- Where does computation happen? On one machine (single-node) or across many machines (distributed).
The answers explain most of the speed, memory, and cost differences you will see later in the tutorial.
Eager and lazy evaluation
In eager evaluation, each operation runs the moment you call it. You get a real result after every line. In lazy evaluation, operations only record what you want. The tool builds a query plan, which is a description of the steps. It runs the plan when you ask for a result.
Eager execution is easy to debug because you can print any intermediate result. Its cost is that the tool cannot see what comes next. If you load 40 columns and then use 2, the other 38 were already read.
Lazy execution lets the tool look at the whole plan first and rewrite it. This rewriting is called query optimization. Common rewrites:
- Projection pushdown: read only the columns the query uses.
- Predicate pushdown: apply filters as early as possible, ideally inside the file reader, so rows that fail never enter memory.
- Operator fusion: combine adjacent steps so data is not copied between them.
The next chapters cover optimization in more detail. Here the point is that laziness is what makes these rewrites possible.
Where each tool sits
| Tool | Default evaluation | Parallelism | Runs where |
|---|---|---|---|
| pandas | Eager | Mostly one CPU core | Inside your Python process |
| Polars | Eager `DataFrame` or lazy `LazyFrame`, your choice | All cores | Inside your Python process |
| DuckDB | Declarative SQL, optimized before running | All cores | Inside your Python process |
| Spark | Lazy | Many cores on many machines | A driver process plus executors, or local mode |
pandas is the pure eager tool. Each statement such as df[df.revenue > 0] allocates a new object immediately.
Polars offers both modes. pl.read_parquet and pl.DataFrame are eager. pl.scan_parquet and .lazy() give a LazyFrame, which is lazy.
DuckDB is a SQL engine, and SQL describes a result rather than a procedure. The engine always plans the query before running it. The Python relation returned by duckdb.sql(...) is also lazy. It runs when you ask for output with .df(), .pl(), .fetchall(), or .show().
Spark is lazy throughout. Operations on a Spark DataFrame are transformations, which only extend the plan. Operations that need a result are actions, such as show(), count(), collect(), and write.
Seeing the difference in code
Create a small file first so the examples run as shown. This step needs pyarrow installed.
import pandas as pd
pd.DataFrame(
{
"region": ["eu", "us", "eu", "apac", "us"],
"revenue": [10, 20, -5, 7, 30],
"note": ["a", "b", "c", "d", "e"],
}
).to_parquet("sales.parquet")Now run a filter and an aggregation lazily in Polars:
import polars as pl
lf = (
pl.scan_parquet("sales.parquet")
.filter(pl.col("revenue") > 0)
.group_by("region")
.agg(pl.col("revenue").sum())
)
print(type(lf)) # a LazyFrame: nothing has been read yet
print(lf.explain()) # the optimized plan
print(lf.sort("region").collect()) # runs the planscan_parquet does not read the file. It records that a file will be read. explain() prints the optimized plan, and in it you should see that only region and revenue are projected from the file and that the filter is pushed into the scan. The note column is never loaded. collect() is the action that triggers execution.
The same idea applies in DuckDB, where the optimizer is part of every query:
import duckdb
query = (
"SELECT region, sum(revenue) AS revenue "
"FROM 'sales.parquet' WHERE revenue > 0 GROUP BY region ORDER BY region"
)
duckdb.sql("EXPLAIN " + query).show()
print(duckdb.sql(query).df())By contrast, pandas performs each step as you write it:
import pandas as pd
df = pd.read_parquet("sales.parquet") # reads all three columns now
positive = df[df["revenue"] > 0] # creates a new DataFrame now
result = positive.groupby("region", as_index=False)["revenue"].sum()
print(result)You can pass columns=["region", "revenue"] to read_parquet to avoid loading note. In pandas, you do this by hand. A lazy engine works it out for you.
Single-node execution
Single-node means one machine. pandas, Polars, and DuckDB all run inside your Python process on the machine you are using. There is no server to start and no network between steps.
The tools still differ in how they use that machine:
- pandas runs most operations on one core. Its operations call optimized compiled code (mostly NumPy), but one operation usually does not spread across cores. It also tends to hold several copies of the data while it works, because each step creates a new object.
- Polars splits work across all available cores. Its engine is written in Rust, and it stores data in a columnar layout (the previous chapter on columnar formats covers why that helps). Its lazy mode can also process data in chunks, called streaming, so some queries run on data larger than memory.
- DuckDB uses a vectorized engine. It processes batches of values at a time instead of one row at a time, and it runs different batches on different threads. It can also spill intermediate state to disk for some operations, such as large sorts and joins.
All three are limited by one machine's CPU cores, RAM, and disk. When the data or compute outgrows that machine, you move up to a bigger machine or to a distributed tool.
Distributed execution with Spark
A distributed engine splits data into partitions and spreads them over several machines. Spark has one driver process that holds your program, builds the plan, and schedules work. Executors are worker processes that each process some partitions.
When you call an action, Spark turns the lazy plan into a graph of stages. A stage is a set of tasks that can run in parallel without exchanging data. Stage boundaries appear at shuffles. A shuffle redistributes rows across the network so that rows with the same key end up on the same executor. A groupBy or a join usually needs one.
You can see Spark's plan with explain(). Nothing is read until the action at the end:
from pyspark.sql import SparkSession, functions as F
spark = SparkSession.builder.master("local[*]").appName("plan").getOrCreate()
df = (
spark.read.parquet("sales.parquet")
.filter(F.col("revenue") > 0)
.groupBy("region")
.agg(F.sum("revenue").alias("revenue"))
)
df.explain() # prints the physical plan, runs nothing
df.orderBy("region").show() # action: executes the plan
spark.stop()master("local[*]") runs Spark in a single process using all cores. This is useful for learning and tests, but it keeps Spark's planning and scheduling overhead without giving you a cluster.
Because Spark is lazy, two things catch people out:
- Errors appear late. A typo in a column name may only fail when an action runs, not on the line that contains it.
- Repeated actions repeat work. Calling
count()and thenshow()on the same DataFrame runs the plan twice unless you cache the result withdf.cache().
Common errors when reading the model
- Assuming lazy means slow to debug. You can inspect a lazy plan with
explain()(Polars, Spark) orEXPLAIN(DuckDB). Use it before you run an expensive query. - Assuming one tool is always lazy or always eager. Polars switches by API choice, and DuckDB is lazy through its relation API but returns materialized results from
.df()or.fetchall(). - Confusing in-process with small. DuckDB and Polars run in your process but can handle data much larger than pandas can on the same machine.
- Expecting pandas to use all cores. Buying a machine with more cores rarely speeds up a plain pandas script.
Exercise
A teammate writes pl.read_parquet("big.parquet").lazy().filter(pl.col("year") == 2025).select("id").collect() and complains that it is slow and uses a lot of memory. What is wrong, and how do you fix it?
Show answer
read_parquet is eager, so the whole file is loaded into memory before .lazy() is called. The optimizer can no longer push the year filter or the id projection into the file read. Replace pl.read_parquet(...).lazy() with pl.scan_parquet("big.parquet"). The scan then reads only the id and year columns and can skip data that fails the filter.
Exercise
In Spark, you run df.count() and then df.show() on the same lazy DataFrame, and the input file is large. How many times does Spark read and process the data, and how can you reduce it?
Show answer
Each action runs the plan, so the data is read and processed twice. Call df.cache() (or persist()) before the actions so the computed result is kept for reuse, or restructure the code to need only one action.
Exercise
Name the step in a Spark job that moves rows between executors, and say why a groupBy usually needs it.
Show answer
That step is a shuffle. Rows with the same group key must be processed together, but they may start on different executors. The shuffle sends them over the network so each key ends up on one executor, which splits the job into two stages.