Sub topic 12
Shuffles, joins and the index: what is expensive
This chapter assumes you know pandas joins, groupby, and set_index. You should also know that a Dask DataFrame is a set of pandas partitions, and that Dask is lazy until you call compute() or persist().
Most Dask operations are cheap because each partition is handled alone. A few operations need rows from many partitions to meet in one place. Those operations are called shuffles, and they are where most slow Dask jobs spend their time.
Why some operations are cheap and others are not
Operations fall into three groups.
- Row-wise (embarrassingly parallel). Filters,
assign,astype, andmap_partitionswith a row-local function. Each output partition depends on exactly one input partition. No data moves between partitions. - Reductions.
sum,mean,count, andgroupby(...).agg(...)with a small number of groups. Each partition computes a partial result, and the partial results are combined in a tree. Only small intermediate objects move. - Shuffles. Operations that must reorganize rows so that related rows end up in the same partition. Whole rows travel between workers, and they may be written to disk if memory runs short.
A shuffle is an all-to-all exchange. If the input has N partitions and the output has M, up to N x M small pieces are created and moved. The cost grows with the amount of data, with the number of partitions, and with network and disk speed.
Which operations shuffle
| Operation | Cost | Why |
|---|---|---|
| `ddf[ddf.x > 0]`, `assign`, `astype` | Cheap | Partition-local |
| `ddf.x.sum()`, `ddf.x.mean()` | Cheap | Small partial results combined |
| `groupby("k").agg(...)` with few groups | Cheap | Partial aggregates per partition, then combined |
| `groupby("k").agg(...)` with many groups | Moderate to costly | The combined result is large, so a shuffle-based reduction is better |
| `groupby("k").apply(func)` | Costly | Needs all rows of a group in one partition |
| `set_index("col")` on an unsorted column | Costly | Sorts and redistributes all rows |
| `merge` on columns, both sides large | Costly | Both sides are shuffled by the join key |
| `merge` with one small side | Cheap | The small side is broadcast |
| `merge` on already-sorted indexes with known divisions | Cheap | Matching partitions are aligned |
| `drop_duplicates`, `nunique`, `value_counts` on high-cardinality columns | Moderate to costly | Large intermediate results |
The index and divisions
In pandas the index is a label for each row. In Dask it also describes where rows live. If a Dask DataFrame is sorted by its index, Dask can record the boundary values of each partition. These boundaries are called divisions.
import pandas as pd
import dask.dataframe as dd
pdf = pd.DataFrame(
{"user_id": [1, 2, 3, 4, 5, 6], "amount": [5, 8, 3, 9, 1, 7]}
)
ddf = dd.from_pandas(pdf.set_index("user_id"), npartitions=3, sort=True)
print(ddf.known_divisions) # True
print(ddf.divisions) # (1, 3, 5, 6)The divisions (1, 3, 5, 6) say that partition 0 holds index 1 to 2, partition 1 holds 3 to 4, and partition 2 holds 5 to 6. With this knowledge Dask can do three things without a shuffle:
ddf.loc[3:4]reads only partition 1 instead of scanning all partitions.- Joins between two frames with matching divisions can pair up partitions directly.
- Index-based groupby and resample can work partition by partition.
If divisions are unknown, known_divisions is False. This is the normal state after read_csv, and often after read_parquet. Dask then treats the index as a plain label with no location information.
set_index: pay once, benefit many times
set_index on a column that is not already sorted is a full shuffle. It samples the column to choose partition boundaries, then sends each row to the right new partition, then sorts inside each partition.
indexed = ddf.reset_index().set_index("user_id") # full sort and shuffle
indexed = indexed.persist() # keep the result in memoryTwo habits make this worthwhile:
- Do the
set_indexonce, then save the result withto_parquet. Later jobs read a file that is already sorted, and the divisions can be read back from the Parquet metadata. - Call
persist()after theset_indexso later steps do not repeat the shuffle.
If you already know the boundaries, you can pass them and skip the sampling step:
indexed = ddf.reset_index().set_index("user_id", divisions=[1, 3, 5, 6])The values must be sorted and must cover your data, or rows will be misplaced.
Joins
dd.merge (or ddf.merge) takes the same arguments as pandas. Dask chooses one of three strategies depending on what it knows about the inputs.
Broadcast join
If one side is small (a lookup table), Dask can send a copy of it to every partition of the large side. No shuffle of the large side is needed.
import pandas as pd
import dask.dataframe as dd
trips = dd.from_pandas(
pd.DataFrame({"zone_id": [1, 2, 1, 3, 2, 3], "fare": [10, 20, 30, 40, 50, 60]}),
npartitions=3,
)
zones = pd.DataFrame({"zone_id": [1, 2, 3], "zone": ["north", "south", "east"]})
joined = trips.merge(zones, on="zone_id", how="left")
print(joined.compute())Here the right side is a plain pandas DataFrame, so each partition of trips is merged with the full zones table. For a left join with a small right side, this is the cheapest option. A small Dask frame (one or a few partitions) is also broadcast automatically in many cases. You can request it with broadcast=True on merge.
Hash join
If both sides are large and have no useful divisions, Dask hashes the join key, shuffles both sides so that equal keys land in the same partition number, and then merges each pair of partitions. Both inputs move across the network. This is the default for two big frames.
Sorted (aligned) join
If both frames are indexed by the join key, and both have known divisions, Dask merges on the index with left_index=True, right_index=True. If the divisions match, no data moves. If they differ, Dask re-slices one side to match the other, which is cheaper than a full shuffle.
left = ddf # indexed by user_id, divisions known
right = dd.from_pandas(
pd.DataFrame({"user_id": [1, 2, 3, 4, 5, 6], "plan": list("aabbcc")}).set_index("user_id"),
npartitions=3,
sort=True,
)
both = left.merge(right, left_index=True, right_index=True)
print(both.compute())Join checklist
- Make the smaller side as small as you can: select only the needed columns and filter rows before the merge.
- If it fits comfortably in memory, convert it to pandas with
.compute()so it is broadcast. - If you join the same large tables repeatedly, sort both by the key once, save them, and join on the index.
- Watch for skew. If one key holds 40% of the rows, one output partition receives 40% of the data and may exceed worker memory while the others sit idle.
Shuffle methods
Dask can run a shuffle in different ways. You choose the method with a configuration option.
import dask
with dask.config.set({"dataframe.shuffle.method": "tasks"}):
result = joined.compute()| Method | Where it works | Trade-off |
|---|---|---|
| `tasks` | Any scheduler | Simple and general. Builds many small tasks, so graph size grows quickly with partition count. |
| `disk` | Local schedulers | Writes pieces to disk. Handles data larger than memory on one machine. |
| `p2p` | Distributed `Client` only | Streams pieces directly between workers, with low memory use and a small graph. Preferred on a cluster. |
The default is chosen from your environment: p2p when a distributed Client is active, and a local method otherwise. The setting name and the available methods have changed between Dask releases, so check the documentation for your installed version.
Spotting shuffles
Before running a large job, look at the graph.
print(joined.npartitions)
joined.visualize(filename="graph.svg") # needs graphviz installedShuffle stages show up as dense bands where every input node connects to many output nodes. On the dashboard (see the chapter on the Client), a shuffle appears as a burst of transfer activity, a rise in memory, and possibly spilling to disk.
Reducing shuffle cost
- Filter and select first. Drop rows and columns before any shuffle. Less data means less movement.
- Use reductions instead of
apply. Prefergroupby("k").agg({"x": "sum"})overgroupby("k").apply(custom). Built-in aggregations compute partial results per partition. - Control the output size of groupby. For many groups, pass
split_out, for examplegroupby("k").sum(split_out=8). The result then has 8 partitions instead of being gathered into one. - Avoid repeated shuffles. Persist after
set_indexor a large merge. - Reduce partition count first. Shuffle cost grows with the number of partitions. Repartitioning to fewer, larger partitions before a shuffle can help, as long as each partition still fits in memory.
- Store sorted data. Save partitions in sorted order so that later jobs start with known divisions.
Common errors
- Memory errors during merge. Usually key skew or a large right side. Check the value counts of the join key and shrink the right side.
- Unexpected row order. A shuffle does not preserve the original order. If you need order, sort explicitly by a column afterward, or index by that column.
known_divisionsis False after reading. Reading Parquet or CSV does not guarantee sorted data. Check the documented options ofread_parquetfor your version, or runset_indexonce and save.- Duplicate index values.
set_indexallows duplicates, but all rows with the same index value land in a single partition. A very frequent value makes an oversized partition. - A very slow
compute()with a tiny result. The result is small, but the work before it was a shuffle. The size of the output says nothing about the cost.
Exercise
You have a 500 GB events table with a user_id column and a 20 MB users table with the same column. You need to attach user attributes to each event. Which join strategy should you use, and what would you do differently if both tables were 500 GB and you needed to run this join every day?
Show answer
Load users into pandas with .compute() (or read it as a single-partition frame) and merge events with it. Dask broadcasts the small table to each partition of events, so the 500 GB table is not shuffled. If both tables were 500 GB and the join ran daily, a hash join would shuffle both sides every time. Instead, run set_index("user_id") once on each table, write both to Parquet, and read them back with known divisions. Later jobs can then join on the index with little or no data movement. Also check the distribution of user_id for skew.
Exercise
A teammate wrote ddf.groupby("customer_id").apply(summarize).compute() and the job runs out of memory, although the final result is tiny. Give two reasons the job is expensive and one change to try.
Show answer
First, groupby().apply() needs every row of a group in the same partition, so Dask shuffles the whole DataFrame by customer_id. Second, if some customers have far more rows than others, those partitions grow large and exceed worker memory. A change to try: rewrite the logic as built-in aggregations such as groupby("customer_id").agg(...), which compute partial results per partition. Alternatively, run set_index("customer_id") once, persist it, and use map_partitions on data that is already grouped by partition.