Sub topic 9
Using a Client and the dashboard
The earlier chapters used Dask's local schedulers: threads, processes and synchronous. They run your graph and return a result, but they show you nothing while they work. The distributed scheduler adds two things. One is a pool of worker processes you can configure. The other is a live web dashboard that shows what those workers are doing. You reach both through a Client.
This chapter assumes you can build a Dask DataFrame, call compute() and persist(), and tell lazy objects from computed ones. It also assumes you know that Dask partitions are pandas DataFrames.
What a Client is
A Client is your Python session's connection to a Dask scheduler. Calling Client() with no arguments does three things:
- It starts a
LocalClusteron your machine. This is a scheduler plus several worker processes. - It connects your session to that cluster.
- It registers itself as the default scheduler, so
compute()andpersist()run on the cluster.
"Local" does not mean "single process". The workers are separate Python processes, each with its own threads and memory limit. The same code works on a real cluster, where you pass the scheduler's address instead of starting a local cluster.
Starting a Client
This script builds a small DataFrame, starts a Client and runs a groupby. Run it as a file.
import pandas as pd
import dask.dataframe as dd
from dask.distributed import Client
if __name__ == "__main__":
pdf = pd.DataFrame({
"zone": ["a", "b", "a", "b"] * 1000,
"fare": [10.0, 20.0, 30.0, 40.0] * 1000,
})
ddf = dd.from_pandas(pdf, npartitions=4)
mean_fare = ddf[ddf["fare"] > 15].groupby("zone")["fare"].mean()
client = Client() # starts a local cluster
print(client.dashboard_link)
print(mean_fare.compute())
client.close()The if __name__ == "__main__": guard matters. Worker processes may re-import your script when they start. This is always the case on Windows and macOS, which use the "spawn" start method. Without the guard, each worker would try to start its own cluster and the script fails with a bootstrapping error. Interactive sessions such as Jupyter notebooks do not need the guard.
client.dashboard_link prints a URL, by default http://127.0.0.1:8787/status. Open it in a browser while a computation runs. The dashboard needs the bokeh package. If it is missing, the Client still works but the dashboard page is unavailable, and you will see a warning.
Controlling the local cluster
The defaults pick a worker count and thread count from your CPU count. Set them yourself when you need predictable memory use:
from dask.distributed import Client, LocalCluster
if __name__ == "__main__":
cluster = LocalCluster(
n_workers=2,
threads_per_worker=2,
memory_limit="2GiB", # per worker, not total
)
client = Client(cluster)
print(client)
client.close()
cluster.close()memory_limit applies to each worker. Two workers with "2GiB" can use up to 4 GiB in total. Make sure the total fits your machine's RAM, with room left for your own session.
Choose the worker and thread split by workload:
| Workload | Better layout |
|---|---|
| Pure pandas and NumPy code that releases the GIL | Fewer workers, more threads each |
| Python-heavy code, such as string loops or custom row functions | More workers, 1 thread each |
| Large partitions that need a lot of memory | Fewer workers, so each gets a bigger `memory_limit` |
The GIL is Python's global interpreter lock. It lets only one thread run Python bytecode at a time. Separate processes avoid that limit, but they cost extra memory and need data copied between them.
A Client can also be a context manager, which closes it when the block ends:
from dask.distributed import Client
if __name__ == "__main__":
with Client(n_workers=2, threads_per_worker=2) as client:
print(client.dashboard_link)Reading the dashboard
The dashboard has many pages. Four views cover most debugging.
Status
The status page is the default. It combines several panels:
- Task Stream shows one row per worker thread. Each rectangle is a task, colored by task type. White gaps mean a thread sat idle. A stream full of gaps means the work is not parallel enough, or the scheduler is waiting on something.
- Progress shows one bar per task type, such as reading, filtering or aggregating. It tells you which stage you are in.
- Bytes stored and Memory per worker show how much data each worker holds.
- Processing and CPU show how busy workers are.
Workers
This page lists each worker with its memory use, CPU and number of tasks. Use it to spot one worker with much more memory than the others. That pattern points to unbalanced partitions.
Graph
The graph page draws the task graph as it executes. It is useful for seeing how work fans in at an aggregation step.
Profile
The profile page samples what the worker threads spend time on. It displays a flame graph of function calls. Use it when you ask "why is this task slow?" rather than "why is the cluster idle?".
Memory colors
Each worker's memory bar changes color as the worker approaches its limit. By default a worker starts moving data to disk at 70% of memory_limit. It pauses accepting new tasks at 80%, and the nanny process restarts it at 95%. In the bars, orange means the worker is under memory pressure or paused. Gray means data spilled to disk. Spilling keeps the job alive but slows it, because every access reads from disk.
Watching progress from code
You do not always have a browser open. The progress function shows a progress bar for a persisted collection:
import pandas as pd
import dask.dataframe as dd
from dask.distributed import Client, progress
if __name__ == "__main__":
pdf = pd.DataFrame({"x": range(1_000_000)})
ddf = dd.from_pandas(pdf, npartitions=8)
ddf["y"] = ddf["x"] * 2
with Client(n_workers=2) as client:
ddf = ddf.persist() # starts work in the background
progress(ddf) # blocks and shows a bar until done
print(ddf["y"].sum().compute())With a Client active, persist() returns right away while the cluster works in the background. The progress call then waits and draws a bar. A plain compute() also shows nothing until the end. So persist() plus progress() is the usual way to watch a long computation in a terminal.
How the Client changes your code
With a Client active, you do not pass a scheduler= argument. The distributed scheduler is the default. If you pass scheduler="threads" to compute, Dask uses the local threaded scheduler for that call and ignores the cluster. That is a useful way to check whether a bug comes from the cluster or from your code.
Two behaviors differ from the local schedulers:
- Results travel between processes. Workers send results back to your session. Calling
compute()on a large object copies all of it into your session's memory. Aggregate first, then compute. - Errors come back wrapped. An exception in a worker is sent back and raised in your session. The traceback shows the failing task, but you cannot step into it with a debugger the way you can with
scheduler="synchronous".
Common problems
- The script hangs or errors at startup. The
__main__guard is missing. Add it. - The dashboard page won't load. Check that
bokehis installed. If port 8787 is taken, Dask picks another port, so readclient.dashboard_linkinstead of assuming 8787. - A worker restarts and the job fails with
KilledWorker. A worker passed the 95% memory limit repeatedly. Use smaller partitions, fewer threads per worker, or a highermemory_limit. - The task stream is mostly white. Few partitions, or one slow task that everything waits on. Check
npartitionsand the Profile page. - You create many Clients. Each
Client()starts a new cluster. Close the old one withclient.close()before starting another.
Exercise
You start Client() and run compute() on a large aggregation. The Workers page shows one worker holding most of the data while the others are almost empty, and its memory bar is orange. What is the likely cause, and what is one change you could try?
Show answer
The partitions are probably uneven in size, or there are too few of them, so one worker received much more data than the rest. The orange bar means that worker is near its memory limit and may spill to disk. Repartition the data into more, evenly sized partitions (for example ddf.repartition(partition_size="100MB")), or raise memory_limit, then watch the Workers page again.
Exercise
Why does persist() followed by progress() show a progress bar, while a plain compute() call does not?
Show answer
With a Client active, persist() submits the graph to the cluster and returns immediately while work continues in the background, so progress() can track it. compute() blocks until the whole result is ready, so there is nothing to display in the meantime.