In this post we are going to cover performance and memory in Python for data engineers: slow apply calls, big DataFrames, pandas versus Polars and DuckDB, threads, processes and asyncio, the GIL, and building a DataFrame in a loop. These are 7 real Python interview questions, asked the way they come up on a real project, and the last one is a scenario where a nightly job went from twenty minutes to three hours.
Performance work in Python is mostly about one thing: keeping the heavy work out of slow Python loops and in compiled code, and knowing what your program is actually waiting on. Interviewers ask about it because every data engineer eventually inherits a job that got slow, and the answer shows whether you measure first or guess.
Every Python step below runs on the sample data, and the output under each step is the real result.
Part 5 of the Real Time Python for Data Engineers Interview Questions and Answers series on TechBrothersIT.
- The short answer
- Let's create some sample data
- Question 1: A transformation using apply on ten million rows takes an hour. How do you make it faster?
- Question 2: A DataFrame uses eight gigabytes of memory. How do you measure and reduce it?
- Question 3: A teammate wants to switch from pandas to Polars or DuckDB. When does it make sense?
- Question 4: A script calls an API for ten thousand IDs one by one. When do you use threads, processes or asyncio?
- Question 5: Someone says the GIL makes Python useless for parallel work. What do you tell them?
- Question 6: A loop builds a big DataFrame by appending one row at a time. Why is it slow, and what is the fix?
- Scenario 7: The nightly Python job went from twenty minutes to three hours. How do you find the bottleneck?
- The full script
The short answer
Make pandas work on whole columns instead of one Python call per row, measure memory with deep=True and shrink it with category and smaller types, and pick threads or asyncio for I/O and processes for CPU-bound Python. When a job slows down, measure each stage and profile before you change any code.
Keep that in mind. Every question below is one piece of it.
Let's create some sample data
We build 100,000 orders with NumPy, a small stand-in for the ten-million-row table, and save them as a Parquet file. We also build a nightly customer extract where the source sends three versions of every customer, and a fake fetch_customer function that waits like a network call, where ID 13 fails.
import time
import numpy as np
import pandas as pd
import requests
pd.set_option("display.width", 60)
# 100,000 orders: a small stand-in for the ten-million-row table
rng = np.random.default_rng(7)
n = 100_000
orders = pd.DataFrame({
"order_id": np.arange(1, n + 1),
"cust_id": rng.integers(1, 1001, n),
"region": rng.choice(["EU", "US", "APAC", "LATAM", "MEA"], n),
"status": rng.choice(["Open", "Shipped", "Cancelled"], n),
"qty": rng.integers(1, 21, n),
"amount": rng.integers(500, 50_000, n) / 100,
})
orders.to_parquet("orders.parquet")
# The nightly customer extract: the source now sends three versions of every customer
customers = pd.concat(
[pd.DataFrame({"cust_id": np.arange(1, 1001),
"tier": rng.choice(["gold", "basic"], 1000),
"updated_at": pd.Timestamp(day)})
for day in ["2026-10-20", "2026-10-21", "2026-10-22"]],
ignore_index=True,
)
def fetch_customer(cid):
"""Stands in for one API call: it waits like a network call, and ID 13 fails."""
time.sleep(0.01)
if cid == 13:
raise requests.ConnectionError(f"customer {cid}: reset")
return {"id": cid, "status": "active"}
customer_ids = range(1, 51)Question 1: A transformation using apply on ten million rows takes an hour. How do you make it faster?
Stop calling a Python function for every row. apply with axis=1 hands each row to your function as a small Series, so ten million rows means ten million Python calls. The fix is to vectorize: let pandas and NumPy work on whole columns in compiled code.
Let's try it with a tax rule. The slow way is a tax_row function, applied with axis=1. The fast way: np.where picks the rate for the whole region column at once, and one multiplication does every row. We run both on the 100,000 sample rows and compare them.
import numpy as np
def tax_row(row):
rate = 0.2 if row["region"] == "EU" else 0.1
return row["amount"] * rate
slow = orders.apply(tax_row, axis=1) # Python call per row
rate = np.where(orders["region"] == "EU", 0.2, 0.1)
fast = orders["amount"] * rate # whole columns
print(len(slow), "rows, same result:", slow.equals(fast))100000 rows, same result: True100000 rows, and same result: True. Always prove that with .equals() before you swap the code. We don't print timings here, because they change between runs.
For more cases, there is a vectorized tool for each:
np.selectfor many conditions.- The
.strand.dtaccessors for text and dates. - A
mapor amergefor lookups.
Fix the step that is actually slow, not the one you think is slow.
Question 2: A DataFrame uses eight gigabytes of memory. How do you measure and reduce it?
Measure first. memory_usage(deep=True) gives the full bytes per column. Without deep, object columns count only their pointers, not the text inside.
Let's measure the orders frame, then convert the repeated labels to category and downcast the integers that fit a smaller type.
before = orders.memory_usage(deep=True, index=False)
small = orders.astype({"region": "category",
"status": "category"})
for c in ["order_id", "cust_id", "qty"]:
small[c] = pd.to_numeric(small[c], downcast="integer")
after = small.memory_usage(deep=True, index=False)
print(pd.DataFrame({"dtype": small.dtypes.astype(str),
"before": before, "after": after}))
mb_before, mb_after = before.sum() / 1e6, after.sum() / 1e6
print(f"total: {mb_before:.1f} MB -> {mb_after:.1f} MB") dtype before after
order_id int32 800000 400000
cust_id int16 800000 200000
region category 1120148 100057
status category 1467500 100045
qty int8 800000 100000
amount float64 800000 800000
total: 5.8 MB -> 1.7 MBIn pandas 3, text uses the new default string type, backed by PyArrow, which is already far smaller than the old object columns. Still, region (1120148 bytes) and status (1467500 bytes) were the biggest columns, and they only repeat a few labels. As category they drop to 100057 and 100045 bytes. order_id becomes int32, cust_id becomes int16 and qty becomes int8. The whole frame goes from 5.8 MB to 1.7 MB.
Notice amount stays float64 at 800000 bytes. Leave the money column alone: float32 keeps only about seven significant digits, so large amounts lose their cents. Money stays float64 or Decimal.
The bigger wins come before loading:
- Read fewer columns, with
usecolsorcolumns=. - Set the dtypes at read time.
- Keep files as Parquet, which keeps the types.
- Process it in chunks if it still does not fit.
Measure with deep=True first, then shrink. Without it, the numbers for object columns leave out the text.
Question 3: A teammate wants to switch from pandas to Polars or DuckDB. When does it make sense?
When pandas is the bottleneck: the data is too big or too slow for one pandas process, but it still fits on one machine. Polars and DuckDB are columnar engines that use all your cores. Beyond one machine, that's Spark.
| Pick it when | Keep in mind | |
|---|---|---|
| pandas | small to medium data, existing code | the whole frame in memory |
| DuckDB | SQL team, Parquet files, big joins | query DataFrames by name |
| Polars | expression API, lazy and streaming | sort after group_by |
| Spark | data that needs a cluster | cluster cost and overhead |
DuckDB is the easy first step for a team that knows SQL. It queries a pandas DataFrame by its variable name, or Parquet files directly. Let's count the orders whose status isn't Cancelled, per region.
import duckdb
by_region = duckdb.sql('''
SELECT region, COUNT(*) AS orders
FROM orders -- the pandas DataFrame
WHERE status <> 'Cancelled'
GROUP BY region
ORDER BY region
''').df()
print(by_region) region orders
0 APAC 13319
1 EU 13343
2 LATAM 13383
3 MEA 13266
4 US 13217APAC has 13319, EU 13343, LATAM 13383, MEA 13266 and US 13217.
Polars has a lazy API. scan_parquet builds a plan, the optimizer pushes the filter down to the file, and collect runs it. In Polars 2, collect streams by default, and group_by never promised row order, so we sort explicitly. Let's run the same count on the Parquet file and compare it with DuckDB.
import polars as pl
by_pl = (
pl.scan_parquet("orders.parquet") # lazy: a plan
.filter(pl.col("status") != "Cancelled")
.group_by("region")
.agg(pl.len().alias("orders"))
.sort("region") # group_by order is not guaranteed
.collect()
)
want = list(by_region.itertuples(index=False, name=None))
print("same as DuckDB:", by_pl.rows() == want)same as DuckDB: TrueSame as DuckDB: True.
And it's not a rewrite. Both convert to and from pandas: DuckDB reads a DataFrame directly and returns one with .df(), and Polars has to_pandas() and pl.from_pandas(). So you can move just the slow step.
Small data, stay with pandas. Big joins and aggregations on one machine, DuckDB or Polars. Data that needs a cluster, Spark.
Question 4: A script calls an API for ten thousand IDs one by one. When do you use threads, processes or asyncio?
Calling an API is I/O bound: the program spends almost all its time waiting on the network. That needs more requests in flight, not more CPU. So threads or asyncio, not processes.
| Use it for | Example | |
|---|---|---|
| Threads | I/O with blocking libraries | requests, database drivers |
| asyncio | many concurrent I/O calls | an async client such as httpx |
| Processes | CPU-bound pure Python | parsing, row-by-row rules |
With requests, the simplest fix is a thread pool. We submit one call per ID to a fixed number of workers, and collect each result as it completes. fetch_customer is our fake API call, and ID 13 fails. Notice we catch requests.RequestException, so a connection error, a timeout or an HTTP error from requests lands in the failed list.
import requests
from concurrent.futures import (ThreadPoolExecutor,
as_completed)
ok, failed = [], []
with ThreadPoolExecutor(max_workers=10) as pool:
futures = {pool.submit(fetch_customer, c): c
for c in customer_ids}
for fut in as_completed(futures):
try:
ok.append(fut.result())
except requests.RequestException:
failed.append(futures[fut])
print(len(ok), "fetched, failed IDs:", sorted(failed))49 fetched, failed IDs: [13]49 fetched, and failed IDs: [13]. One bad call doesn't kill the run, and you retry the failures later.
Asyncio runs many requests on one thread, but it needs an async client such as httpx, because requests blocks. Processes are for CPU-bound work, like parsing.
Cap max_workers at what the API allows, or you just get rate limited. And ask for a bulk endpoint that takes many IDs per call. That often beats any concurrency.
Question 5: Someone says the GIL makes Python useless for parallel work. What do you tell them?
The GIL is real, but useless is wrong. In the default CPython build, only one thread runs Python bytecode at a time. That limits one thing: CPU-bound pure Python in threads.
Let's check the runtime we use in this post.
import sys
import sysconfig
print("Python", sys.version.split()[0])
ft = sysconfig.get_config_var("Py_GIL_DISABLED")
print("free-threaded build:", bool(ft))
print("GIL enabled:", sys._is_gil_enabled())Python 3.14.6
free-threaded build: False
GIL enabled: TruePython 3.14.6, free-threaded build: False, and GIL enabled: True.
Most data work isn't blocked by it. A thread releases the GIL while it waits on the network, the disk or a database. And NumPy, pandas, Polars and DuckDB run much of their heavy work in native code that can release it.
| Work | Is the GIL a problem? | Use |
|---|---|---|
| I/O waits: API, database, files | no, released while waiting | threads or asyncio |
| NumPy, pandas, Polars, DuckDB | rarely: native code often releases it | vectorize |
| CPU-bound pure Python | yes, in threads | processes |
For CPU-bound pure Python, use processes, each with its own interpreter and GIL. Since Python 3.14, Linux starts them with forkserver, so keep the main guard, and pass functions and arguments that can be pickled.
from concurrent.futures import ProcessPoolExecutor
from pathlib import Path
def parse_file(path): # CPU-bound pure Python
...
if __name__ == "__main__": # needed: forkserver, spawn
paths = sorted(Path("landing").glob("*.csv"))
with ProcessPoolExecutor() as pool:
results = list(pool.map(parse_file, paths))Python 3.14 officially supports a free-threaded build with no GIL. It's optional, not the default, and single-threaded code runs about 5-10% slower.
Question 6: A loop builds a big DataFrame by appending one row at a time. Why is it slow, and what is the fix?
Because a DataFrame isn't a list. Every append builds a new DataFrame and copies all the rows so far:
- Append row 1: copy 1 row.
- Append row 2: copy 2 rows.
- Append row n: copy n rows.
So the total copying grows with the square of the row count.
DataFrame.append was removed in pandas 2, so today the loop calls pd.concat each time. Same problem. Let's build 2,000 rows that way, count the rows each concat copies, and then build the same frame once from a list of records.
records = [{"order_id": i, "amount": i * 10}
for i in range(1, 2001)]
df, copied = pd.DataFrame(), 0
for r in records: # slow: copies every time
new = pd.DataFrame([r])
df = pd.concat([df, new], ignore_index=True)
copied += len(df)
fast = pd.DataFrame(records) # fix: build it once
print("has append:", hasattr(pd.DataFrame, "append"))
print(f"rows copied by the loop: {copied:,}")
print("same result:", df.equals(fast))has append: False
rows copied by the loop: 2,001,000
same result: TrueHas append: False. The loop copied 2,001,000 rows to build 2,000. The fix, collecting plain records in a list and building the DataFrame once, gives the same result: True.
Same rule for files or API pages: frames.append(df) in the loop, then pd.concat(frames) once at the end.
Quadratic. Double the rows, and the loop does about four times the copying. That's why it gets worse every month.
Scenario 7: The nightly Python job went from twenty minutes to three hours. How do you find the bottleneck?
Don't guess, measure. First ask what changed:
- More data? Check the rows per stage.
- New code or library? Compare the releases.
- Slower source? Check the API, the database or the disk.
Then time every stage. This small wrapper runs a stage, records its seconds, and logs its row count.
import logging
import time
logging.basicConfig(level=logging.INFO,
format="%(levelname)s %(message)s")
log, secs = logging.getLogger("nightly"), {}
def run_stage(name, fn, *args, **kwargs):
start = time.perf_counter()
out = fn(*args, **kwargs)
secs[name] = time.perf_counter() - start # log it too
log.info("%s: %d rows", name, len(out))
return outThis step prints nothing; it prepares the data for the next step.
Now let's run the job through it: load the Parquet file, join the customers, and apply the tax rule.
raw = run_stage("load", pd.read_parquet, "orders.parquet")
joined = run_stage("join", raw.merge, customers,
on="cust_id")
tax = run_stage("tax", joined.apply, tax_row, axis=1)
print("slowest stage:", max(secs, key=secs.get))INFO load: 100000 rows
INFO join: 300000 rows
INFO tax: 300000 rows
slowest stage: taxThe load reads 100000 rows, but the join returns 300000 rows, and the slowest stage is tax. In the real job, log the seconds too, so you can compare with last week.
Then profile the slow stage. Here cProfile runs it on a 10,000-row sample, and we also count the repeated keys in the customer extract.
import cProfile
import pstats
with cProfile.Profile() as prof: # profile a sample
joined.head(10_000).apply(tax_row, axis=1)
stats = pstats.Stats(prof).get_stats_profile()
tax_calls = stats.func_profiles["tax_row"].ncalls
print("tax_row calls:", tax_calls)
repeats = customers["cust_id"].duplicated().sum()
print("repeated customer keys:", repeats)tax_row calls: 10000
repeated customer keys: 2000tax_row was called 10000 times, once per row. For a whole job, use python -m cProfile -s cumulative job.py.
So why did the join triple? The customer extract has 2000 repeated keys: the source now sends every version of each customer. So the slow apply ran on three times the rows.
The fix: keep the latest version per customer, join with validate="many_to_one" so repeats fail loudly, and vectorize the tax.
latest = (customers.sort_values("updated_at")
.drop_duplicates("cust_id", keep="last"))
joined = run_stage("join", raw.merge, latest, on="cust_id",
validate="many_to_one")
rate = np.where(joined["region"] == "EU", 0.2, 0.1)
joined["tax"] = joined["amount"] * rate
print("rows after the fix:", len(joined))INFO join: 100000 rows
rows after the fix: 100000The join is back to 100000 rows, and so is the result. To keep it from happening again:
validate=on every join, so a repeated key fails loudly.- Log rows and seconds per stage, and compare with last week.
- Alert on a jump in rows or minutes.
Don't guess. Measure each stage, profile the slow one, then fix it.
Key points to remember
- Vectorize: whole columns, not apply(axis=1)
- memory_usage(deep=True), then category and smaller types
- DuckDB or Polars when pandas is the bottleneck on one machine
- Threads or asyncio for I/O, processes for CPU-bound Python
- Slow job: measure each stage, profile, then fix
The full script
Here is everything in one script: the sample data and every step from this post, in order. Copy it and run it top to bottom.
Show the full Python script (sample data and every step)
# ========================================================================
# Python Interview Q&A #5 - Performance and memory
# TechBrothersIT. Sample data is invented for teaching.
# Every step below was run with Python 3.14.6 and pandas 3.1.0; the outputs in the video and the blog
# post are the real outputs. Run it in an empty folder: it writes small sample files.
# ========================================================================
# Step 0: sample data
import time
import numpy as np
import pandas as pd
import requests
pd.set_option("display.width", 60)
# 100,000 orders: a small stand-in for the ten-million-row table
rng = np.random.default_rng(7)
n = 100_000
orders = pd.DataFrame({
"order_id": np.arange(1, n + 1),
"cust_id": rng.integers(1, 1001, n),
"region": rng.choice(["EU", "US", "APAC", "LATAM", "MEA"], n),
"status": rng.choice(["Open", "Shipped", "Cancelled"], n),
"qty": rng.integers(1, 21, n),
"amount": rng.integers(500, 50_000, n) / 100,
})
orders.to_parquet("orders.parquet")
# The nightly customer extract: the source now sends three versions of every customer
customers = pd.concat(
[pd.DataFrame({"cust_id": np.arange(1, 1001),
"tier": rng.choice(["gold", "basic"], 1000),
"updated_at": pd.Timestamp(day)})
for day in ["2026-10-20", "2026-10-21", "2026-10-22"]],
ignore_index=True,
)
def fetch_customer(cid):
"""Stands in for one API call: it waits like a network call, and ID 13 fails."""
time.sleep(0.01)
if cid == 13:
raise requests.ConnectionError(f"customer {cid}: reset")
return {"id": cid, "status": "active"}
customer_ids = range(1, 51)
# Step 1: apply with axis=1 vs a vectorized column expression
import numpy as np
def tax_row(row):
rate = 0.2 if row["region"] == "EU" else 0.1
return row["amount"] * rate
slow = orders.apply(tax_row, axis=1) # Python call per row
rate = np.where(orders["region"] == "EU", 0.2, 0.1)
fast = orders["amount"] * rate # whole columns
print(len(slow), "rows, same result:", slow.equals(fast))
# Step 2: Measure memory per column, then use category and smaller integer types
before = orders.memory_usage(deep=True, index=False)
small = orders.astype({"region": "category",
"status": "category"})
for c in ["order_id", "cust_id", "qty"]:
small[c] = pd.to_numeric(small[c], downcast="integer")
after = small.memory_usage(deep=True, index=False)
print(pd.DataFrame({"dtype": small.dtypes.astype(str),
"before": before, "after": after}))
mb_before, mb_after = before.sum() / 1e6, after.sum() / 1e6
print(f"total: {mb_before:.1f} MB -> {mb_after:.1f} MB")
# Step 3: DuckDB: SQL straight over a pandas DataFrame
import duckdb
by_region = duckdb.sql('''
SELECT region, COUNT(*) AS orders
FROM orders -- the pandas DataFrame
WHERE status <> 'Cancelled'
GROUP BY region
ORDER BY region
''').df()
print(by_region)
# Step 4: Polars: a lazy query over the Parquet file
import polars as pl
by_pl = (
pl.scan_parquet("orders.parquet") # lazy: a plan
.filter(pl.col("status") != "Cancelled")
.group_by("region")
.agg(pl.len().alias("orders"))
.sort("region") # group_by order is not guaranteed
.collect()
)
want = list(by_region.itertuples(index=False, name=None))
print("same as DuckDB:", by_pl.rows() == want)
# Step 5: A thread pool for I/O-bound API calls, with failures collected
import requests
from concurrent.futures import (ThreadPoolExecutor,
as_completed)
ok, failed = [], []
with ThreadPoolExecutor(max_workers=10) as pool:
futures = {pool.submit(fetch_customer, c): c
for c in customer_ids}
for fut in as_completed(futures):
try:
ok.append(fut.result())
except requests.RequestException:
failed.append(futures[fut])
print(len(ok), "fetched, failed IDs:", sorted(failed))
# Step 6: Check the build: is the GIL enabled?
import sys
import sysconfig
print("Python", sys.version.split()[0])
ft = sysconfig.get_config_var("Py_GIL_DISABLED")
print("free-threaded build:", bool(ft))
print("GIL enabled:", sys._is_gil_enabled())
# Step 7: Growing a DataFrame in a loop vs building it once
records = [{"order_id": i, "amount": i * 10}
for i in range(1, 2001)]
df, copied = pd.DataFrame(), 0
for r in records: # slow: copies every time
new = pd.DataFrame([r])
df = pd.concat([df, new], ignore_index=True)
copied += len(df)
fast = pd.DataFrame(records) # fix: build it once
print("has append:", hasattr(pd.DataFrame, "append"))
print(f"rows copied by the loop: {copied:,}")
print("same result:", df.equals(fast))
# Step 8: Scenario: a small wrapper that times each stage and logs its rows
import logging
import time
logging.basicConfig(level=logging.INFO,
format="%(levelname)s %(message)s")
log, secs = logging.getLogger("nightly"), {}
def run_stage(name, fn, *args, **kwargs):
start = time.perf_counter()
out = fn(*args, **kwargs)
secs[name] = time.perf_counter() - start # log it too
log.info("%s: %d rows", name, len(out))
return out
# Step 9: Scenario: run the nightly stages through the wrapper
raw = run_stage("load", pd.read_parquet, "orders.parquet")
joined = run_stage("join", raw.merge, customers,
on="cust_id")
tax = run_stage("tax", joined.apply, tax_row, axis=1)
print("slowest stage:", max(secs, key=secs.get))
# Step 10: Scenario: profile the slow stage, and check the join input
import cProfile
import pstats
with cProfile.Profile() as prof: # profile a sample
joined.head(10_000).apply(tax_row, axis=1)
stats = pstats.Stats(prof).get_stats_profile()
tax_calls = stats.func_profiles["tax_row"].ncalls
print("tax_row calls:", tax_calls)
repeats = customers["cust_id"].duplicated().sum()
print("repeated customer keys:", repeats)
# Step 11: Scenario: keep the latest customer version, validate the join, vectorize
latest = (customers.sort_values("updated_at")
.drop_duplicates("cust_id", keep="last"))
joined = run_stage("join", raw.merge, latest, on="cust_id",
validate="many_to_one")
rate = np.where(joined["region"] == "EU", 0.2, 0.1)
joined["tax"] = joined["amount"] * rate
print("rows after the fix:", len(joined))
Part 6: Working with APIs
The sample data on this page is invented for teaching. Every output is the real output of the code above it, run with Python 3.14.6 and pandas 3.1.0. Part of the Real Time Python for Data Engineers Interview Questions and Answers series on TechBrothersIT. Features, limits and their status (GA or preview) are current as of October 2026; check the official Python and library documentation for anything you quote in an interview.



No comments:
Post a Comment
Note: Only a member of this blog may post a comment.