Sub topic 14
Common pitfalls and how to debug them
This chapter assumes you know pandas DataFrames, the idea of partitions, lazy evaluation, compute and persist, and the basics of schedulers and the distributed Client. It collects the mistakes that most often slow down or break Dask DataFrame code, and gives you a routine for finding the cause.
Why Dask bugs look different
In pandas, each line runs immediately, so an error points at the line that caused it. In Dask, most lines only add nodes to a task graph. The work runs later, on partitions, often in other threads or processes. This causes three kinds of confusion:
- An error appears at
compute(), far from the line that caused it. - A slow or memory-hungry step shows up as a vague slowdown, not a clear failure.
- Code that works on a small sample fails on the full data, because one partition holds something the sample did not.
The fixes below follow from this.
Pitfall 1: calling compute too early or too often
compute() pulls all results into your process as a pandas object. Two mistakes are common.
Computing a huge result. Calling .compute() on a whole large DataFrame tries to build one pandas DataFrame in memory. That defeats the purpose of Dask. Reduce first (filter, aggregate, sample), then compute.
Computing several times on the same source. Every compute() runs the whole graph again, including reading the files. If you ask for a sum and then a count, the data is read twice.
import pandas as pd
import dask
import dask.dataframe as dd
pdf = pd.DataFrame({
"zone": ["a", "b", "a", "b"],
"fare": [10.0, 20.0, 30.0, 40.0],
})
ddf = dd.from_pandas(pdf, npartitions=2)
total = ddf["fare"].sum()
count = ddf["fare"].count()
# Two separate computes: the source is processed twice.
slow_total, slow_count = total.compute(), count.compute()
# One call: Dask merges the graphs and shares common work.
total_value, count_value = dask.compute(total, count)
print(total_value, count_value) # 100.0 4Use dask.compute(a, b, ...) when you need several results from the same data. Use persist() when you will run many separate computations later, and the data fits in memory.
Pitfall 2: persisting data that does not fit
persist() keeps computed partitions in memory. It helps when you reuse an intermediate result, but it has costs.
- If the data is larger than the cluster's memory, workers spill to disk or are killed.
- A persisted DataFrame stays in memory until you delete the variable. Reassigning
ddf = ddf.persist()releases the old reference, but other variables that point to the old object keep it alive. - Persisting early, before a filter, stores rows you will throw away. Filter and select columns first, then persist.
A good order is: read only the needed columns, filter, then persist the reduced result.
Pitfall 3: treating a Dask DataFrame like pandas
Some pandas habits do not carry over.
| pandas habit | Problem in Dask | Better approach |
|---|---|---|
| `df.iloc[100:200]` | Row positions are not known across partitions, and row-wise positional indexing is not supported | Filter by value or index label, or use `head()` |
| `df.loc[5]` on an unsorted index | Dask must search all partitions | Set a sorted index once, then select by label |
| `for row in df.iterrows()` | Pulls everything to your process, one row at a time | Write a vectorized `map_partitions` function |
| `df.apply(f, axis=1)` without `meta` | Dask guesses the output type, which can be wrong or slow | Pass `meta=` explicitly |
| `len(df)` in a loop | Each call runs a full computation | Compute the length once and store it |
| In-place edits such as `df["a"][mask] = 0` | Dask objects are immutable, and chained assignment is not supported | Use `assign` or `where` |
Printing a Dask DataFrame shows structure only. Use head() to look at real rows. Note that head() reads only the first partition by default, so it can miss problems in later partitions.
Pitfall 4: wrong or missing meta
Dask needs to know column names and dtypes before it runs anything. It gets this from meta, an empty pandas object that describes the output. When you use map_partitions, apply, or similar functions, Dask often infers meta by running your function on a small fake frame. This can fail or give the wrong answer when the function:
- raises an error on empty or fake data,
- returns different dtypes depending on the values it sees,
- has side effects such as writing files or printing.
The usual symptom is a dtype error or a ValueError about mismatched columns, sometimes only at compute time. The safe fix is to state the output yourself.
import pandas as pd
import dask.dataframe as dd
pdf = pd.DataFrame({
"zone": ["a", "b", "a", "b"],
"fare": [10.0, 20.0, 30.0, 40.0],
})
ddf = dd.from_pandas(pdf, npartitions=2)
def add_fare_cents(part):
return part.assign(fare_cents=(part["fare"] * 100).astype("int64"))
meta = pd.DataFrame({
"zone": pd.Series(dtype="object"),
"fare": pd.Series(dtype="float64"),
"fare_cents": pd.Series(dtype="int64"),
})
ddf2 = ddf.map_partitions(add_fare_cents, meta=meta)
print(ddf2.dtypes)
print(ddf2.compute())Declared meta is a promise. If the real output differs, Dask does not always check, and later steps may fail in confusing ways. Compare against a real partition when in doubt, for example ddf2.partitions[0].compute().dtypes.
A related dtype problem comes from reading CSV files. Dask infers dtypes from a sample of the first rows. If a column looks like integers in the sample but contains missing values or text later, a later partition fails to parse. Pass dtype={"col": "float64"} or dtype="object" explicitly, or read Parquet, which stores the types.
Pitfall 5: expensive operations hidden in innocent code
Some operations need data from every partition to meet in one place. They are called shuffles, and they cost network transfer, memory, and often disk.
mergeorjoinof two large DataFrames on a column that is not their sorted index.set_indexon a column, which sorts the data and splits it by value.groupby(...).apply(...)with a custom function, and groupby with very many distinct keys.drop_duplicatesandnuniqueon large columns.sort_valueson the whole dataset.
Cheap, by contrast, are row-wise operations (filters, assign, column arithmetic) and reductions that combine small partial results (sum, count, mean, and groupby().agg() with few groups).
Practical rules:
- Prefer built-in aggregations such as
groupby(...).agg(...)overgroupby(...).apply(...). - If one side of a join is small, load it into pandas and let Dask broadcast it. A merge of a Dask DataFrame with a pandas DataFrame needs no shuffle.
- If you join or group on the same key repeatedly, run
set_indexonce, save to Parquet, and reuse that layout.
Pitfall 6: partitions that are too small or too large
Each partition is one unit of scheduling work, and the scheduler adds a small overhead per task.
- Thousands of tiny partitions make the graph large and the overhead dominant. Symptoms: the scheduler is busy, workers are idle, and the dashboard shows a flood of very short tasks.
- A few huge partitions cause memory errors, because one worker must hold a whole partition plus working copies, often two to three times its size. They also limit parallelism.
A common target is partitions of roughly 100 MB in memory. Filters often leave many nearly empty partitions, so repartition after a heavy filter.
import pandas as pd
import dask.dataframe as dd
pdf = pd.DataFrame({"zone": list("abcd") * 1000, "fare": range(4000)})
ddf = dd.from_pandas(pdf, npartitions=40)
small = ddf[ddf["fare"] > 3900]
print(small.npartitions) # still 40, most of them nearly empty
small = small.repartition(npartitions=1)
print(small.npartitions) # 1Pitfall 7: scheduler and process issues
- Python-heavy code on threads. The default threaded scheduler shares one Python interpreter lock. Pure-Python loops over rows do not run in parallel on threads. Pandas and NumPy release the lock in many operations, so vectorized code scales, but row loops do not. Try the
processesscheduler or aClientwith several worker processes. - Missing main guard. Process-based schedulers start new Python processes. On Windows and macOS, a script that creates a
Clientor usesscheduler="processes"withoutif __name__ == "__main__":can start processes in a loop or fail at startup. - Unpicklable objects. Processes and distributed workers receive your function by serializing it. Open files, database connections, and lambdas that capture them can fail to serialize. Create such resources inside the function instead.
- Globals that differ on workers. A global variable you change in your session is not changed on the workers.
A debugging routine
Work from the smallest case up to the full run.
- Inspect the structure without computing. Check
ddf.dtypes,ddf.columns,ddf.npartitions, andddf.divisions. - Test on one partition.
ddf.partitions[0].compute()runs the graph on a single partition and returns pandas. Run your function directly on that pandas object, where a normal traceback and a debugger work. - Use the synchronous scheduler. It runs everything in one thread in your process, so
pdb,print, and full tracebacks behave normally. - Scale up gradually. Try a few partitions, then the whole dataset, first on threads and then on a
Client. - Watch the dashboard. Look at the task stream for idle workers, the memory panel for workers near their limit, and the progress bars for a single slow task that holds up the rest.
import pandas as pd
import dask.dataframe as dd
pdf = pd.DataFrame({
"zone": ["a", "b", "a", "b"],
"fare": [10.0, 20.0, 30.0, 40.0],
})
ddf = dd.from_pandas(pdf, npartitions=2)
mean_fare = ddf[ddf["fare"] > 15].groupby("zone")["fare"].mean()
# One partition, normal traceback
print(ddf.partitions[0].compute())
# Whole graph in one thread, debugger-friendly
print(mean_fare.compute(scheduler="synchronous"))Quick checklist
- Combine related results in one
dask.computecall. - Select columns and filter before you persist.
- Give
metaexplicitly for custom functions, and givedtypefor CSV reads. - Replace row loops with
map_partitionson vectorized code. - Avoid shuffles when you can, and do
set_indexonce. - Keep partitions near 100 MB, and repartition after heavy filters.
- Debug on one partition, then synchronous, then scale up.
Exercise
A script calls ddf["fare"].sum().compute() and then ddf["fare"].count().compute() on a DataFrame read from 500 CSV files. It is slow, and each call re-reads all the files. Name two ways to avoid the repeated reading, and say when you would choose each.
Show answer
First, use dask.compute(ddf["fare"].sum(), ddf["fare"].count()), which merges both graphs into one run so the files are read once. Choose this when you want a known set of results right now. Second, call ddf = ddf.persist() (after selecting needed columns and filtering) so the partitions stay in memory and later computations reuse them. Choose this when you will run many different computations on the same data and it fits in cluster memory.
Exercise
A map_partitions call fails with a dtype mismatch only when you call compute(), and the function works fine on a small pandas sample. What are two likely causes, and how do you diagnose and fix them?
Show answer
One cause is that Dask inferred meta by running the function on fake data and got the wrong columns or dtypes. Another is that a later partition contains values (such as missing values or text) that change the output dtype. To diagnose, run ddf.partitions[i].compute() or the function on individual partitions with the synchronous scheduler and compare dtypes with ddf2.dtypes. To fix, pass an explicit meta that matches the real output, set explicit dtype values when reading CSV, or read Parquet so types are stored.