Sub topic 16
Migrating and mixing tools in one pipeline
This chapter assumes you have read the earlier chapters on the four tools, on Parquet and Arrow, and on the decision framework. You should be comfortable with the basics of pandas, Polars, DuckDB and Spark, and with the idea that a tool choice depends on data size, workload, team and deployment.
The decision framework tells you which tool fits a task today. Real projects rarely start from a blank page. You usually have existing pandas code, an existing Spark cluster, or a mix of both. This chapter covers two questions. When is a migration worth its cost? When is it better to keep several tools and connect them?
Decide whether to migrate at all
A migration has a cost: engineering time, new bugs, retraining, and a period where two versions of the pipeline exist. Rewriting code only pays off when it removes a real problem. Use this test before you start.
- Name the problem. Examples: the job runs out of memory, it misses its deadline, the cluster costs too much, or nobody can maintain the code.
- Measure it. Use the benchmarking approach from the earlier chapter on your own data and queries. "Polars is faster" is not a measurement of your pipeline.
- Check whether a smaller fix works. Read fewer columns, filter early, store data as Parquet, or use a more efficient data type before you change tools.
- Estimate the cost of the rewrite and the expected gain. Migrate only if the gain clearly exceeds the cost.
Common reasons that justify a migration:
- A pandas job no longer fits in memory, and the data is still within what one machine can handle with an out-of-core engine such as DuckDB or Polars.
- A Spark job processes a few gigabytes on a cluster. Startup time and cluster cost dominate, and a single-node engine would be simpler and cheaper.
- Data has grown beyond one machine, and a single-node tool can no longer finish in an acceptable time.
Common reasons that do not justify a migration:
- A new tool is fashionable.
- A published benchmark shows it winning on a different workload.
- The current job works, runs fast enough, and rarely changes.
Migration paths
The table summarizes the usual directions and what you gain and risk in each.
| From | To | Typical reason | Main risks |
|---|---|---|---|
| pandas | Polars | Memory use, speed, multi-core use | Different API; no index; stricter typing; missing-value semantics differ |
| pandas | DuckDB | Larger-than-memory data, SQL-friendly team | Logic moves from Python to SQL; row-order assumptions break |
| Spark | DuckDB or Polars | Data fits on one machine; cluster cost and startup dominate | Loss of horizontal scaling; different ecosystem for scheduling and storage |
| pandas or single-node | Spark | Data no longer fits on one machine | Shuffle costs; cluster operations; slower for small data |
Behavior differences that cause silent bugs
The same-looking operation can give a different result. Check these during a migration.
- Row order. pandas keeps rows in their original order in most operations. SQL engines and Spark do not guarantee order unless you sort. Add an explicit sort whenever downstream code depends on order.
- Index. pandas has a row index that many scripts rely on, for example in joins and in
loclookups. Polars and Spark have no index. Turn the index into an ordinary column first. - Missing values. pandas uses
NaNfor missing floats, and it may convert integer columns to floats when a value is missing. Polars and SQL engines keep a separate null, distinct fromNaN. A filter such asrevenue > 0treats null as not matching in SQL. - Data types. Check that integers stay integers and that timestamps keep their time zone and precision.
- Group-by keys. Many tools drop or keep null keys differently. pandas drops them by default in
groupby. SQL keeps them as a group.
The last point is easy to test. This script shows that two tools disagree on the same input.
import duckdb
import pandas as pd
pdf = pd.DataFrame({"region": ["eu", None, "eu"], "revenue": [10, 20, 5]})
pandas_result = pdf.groupby("region")["revenue"].sum()
duckdb_result = duckdb.sql(
"SELECT region, sum(revenue) AS revenue FROM pdf GROUP BY region ORDER BY region"
).df()
print(pandas_result)
print(duckdb_result)The pandas result has one group, eu, with a sum of 15. The DuckDB result has two rows: eu with 15 and a null region with 20. Neither is wrong. They follow different rules, and your pipeline must pick one on purpose.
Migrate in small, verified steps
A safe migration changes one piece at a time and proves that the output did not change.
- Choose the slowest or most memory-hungry stage, not the whole pipeline.
- Save the current output of that stage as a reference file.
- Write the new version of the stage.
- Compare the new output with the reference.
- Run both versions side by side for a few cycles before you remove the old one.
For the comparison, sort both results by a key and compare them with a tolerance for floating-point sums. This function does that for a pandas result and a Polars result.
import pandas as pd
import polars as pl
def same_result(expected: pd.DataFrame, actual: pl.DataFrame, key: str) -> bool:
left = expected.sort_values(key).reset_index(drop=True)
right = actual.to_pandas().sort_values(key).reset_index(drop=True)
if list(left.columns) != list(right.columns):
return False
try:
pd.testing.assert_frame_equal(left, right, check_dtype=False, rtol=1e-9)
except AssertionError:
return False
return True
old = pd.DataFrame({"region": ["eu", "us"], "revenue": [15, 20]})
new = pl.DataFrame({"region": ["us", "eu"], "revenue": [20, 15]})
print(same_result(old, new, "region"))actual.to_pandas() needs pyarrow installed. The function prints True because the two results hold the same rows once sorted.
Mixing tools in one pipeline
Often the best answer is not to choose one tool. Each tool is strong at a different stage, and the cost of moving data between them is low when they share formats.
A common layout:
- Spark reads very large raw data and writes a reduced, cleaned Parquet dataset.
- DuckDB or Polars queries that Parquet dataset on one machine for reporting and exploration.
- pandas takes the small final result for plotting, statistics or a machine learning library that expects a pandas DataFrame.
The principle is to shrink the data at each step. Large tools reduce the data, and small, convenient tools finish the job on the result.
Pass data through files, not objects
You have two ways to hand data from one stage to the next.
- In memory, within one Python process. DuckDB can query a pandas DataFrame by variable name, and Arrow-backed conversions such as
.pl()and.to_pandas()move results between DuckDB, Polars and pandas. This is fast for data that fits in memory. - Through Parquet files. One stage writes, the next reads. This works across processes, machines and tools, including Spark. It also gives you a checkpoint you can inspect and rerun from.
For stages that run as separate jobs, prefer Parquet files. For steps inside one script, in-memory conversion is simpler. This example runs a DuckDB aggregation and hands the result to Polars, then to pandas.
import duckdb
import pandas as pd
pdf = pd.DataFrame({"region": ["eu", "us", "eu"], "revenue": [10, 20, 5]})
plf = duckdb.sql(
"SELECT region, sum(revenue) AS revenue FROM pdf GROUP BY region"
).pl()
back_to_pandas = plf.to_pandas()
print(back_to_pandas)Costs of mixing
Mixing tools is not free. Watch for these.
- Copies. Some conversions share memory through Arrow, and others copy data. A copy of a large table can double your memory use at the moment of conversion. Convert only after you have reduced the data.
- Type drift. Each conversion is another chance for types, nulls or time zones to change. Test them at the boundaries.
- More dependencies. Each tool adds installation, versions and security updates. Four tools in one environment cost more to maintain than two.
- Skill spread. Every tool in the pipeline is something your team must be able to debug. Keep the number of tools small, and give each a clear role.
A practical rule set
- Start with the problem, and measure it before changing anything.
- Try cheap fixes first: fewer columns, earlier filters, Parquet storage.
- Migrate one stage at a time and compare outputs against a saved reference.
- Fix behavior differences deliberately: sort order, nulls, types and keys.
- Mix tools when stages differ greatly in data size, and pass data through Parquet between jobs.
- Keep the set of tools as small as the problem allows.
Exercise
A nightly pandas script reads a 40 GB CSV file on a machine with 16 GB of memory and fails with an out-of-memory error. Name two steps you would take before deciding to move the whole pipeline to Spark, and say what you would check after changing the slow stage.
Show answer
First, convert the CSV to Parquet and read only the needed columns, filtering as early as possible. Second, try a single-node engine that can handle larger-than-memory data, such as DuckDB or Polars with its lazy API, on the stage that fails. The data is far smaller than the scale where a cluster is needed. After changing the stage, compare its output with the saved pandas output (or the output of a smaller run). Sort both results by a key, compare floating-point sums with a tolerance, and check null handling, group-by keys and data types.
Exercise
Your pipeline uses Spark to clean 2 TB of logs, then a pandas script groups the cleaned data by day. Why might you write the Spark output as Parquet and read it with DuckDB, and what must you decide about null group keys?
Show answer
Parquet gives a checkpoint between the two jobs and works across tools. The cleaned data may still be too large for pandas, and DuckDB can query it without loading everything into memory. Because pandas drops null group keys by default and SQL engines such as DuckDB keep them as a group, you must decide which behavior you want and test it, for example by filtering nulls explicitly or labeling them.