Run on a Dask cluster
This page helps you choose where DEFAIR’s work runs: in threads on one machine, in several processes on one machine, or on a remote cluster.
Prerequisites
No. 1 A processing environment and data
Install DEFAIR as described in Install DEFAIR, and have inputs you can read. The local thread and process examples run on your machine, so choose worker counts and memory limits that fit its resources.
No. 2 Remote cluster access, when selected
For the remote examples, you need a Dask scheduler you can connect to or
a Dask Gateway, and permission to start the number of workers you ask
for. Replace cluster_options_here with options your Gateway accepts.
No. 3 Worker access to packages and storage
Remote workers need the DEFAIR packages and the workflow’s dependencies, read access to the inputs and write access to remote outputs. Remote workers cannot see files on your machine, so keep inputs in object storage. DEFAIR computes a write to a local path on local threads. If your credentials come only from a local AWS profile or role, give the workers the same access. Credentials and endpoints describes the credentials DEFAIR reads.
Overview
DEFAIR uses Dask, the Python library that lets you work on arrays too
large for memory. Operations are lazy by default: they build a graph of
tasks, and nothing runs until you write output or call .compute().
Dask’s scheduler decides where each task runs.
DEFAIR returns Dask-backed datasets by default. Computation runs on
Dask’s default threaded scheduler unless a managed client is requested
(via dask_client_kwargs, dask_client_context, or gateway
configuration), in which case DEFAIR creates and manages the client for
you. You can also provide your own client using set_dask_client().
If a Dask client is already running when DEFAIR first needs one, DEFAIR adopts it rather than starting a cluster of its own. A script that connects to a cluster before its first DEFAIR call therefore runs its work there without passing the client anywhere:
from dask.distributed import Client
from defair_data.core import Dataset
client = Client("tcp://scheduler:8786")
# The first read that needs a client picks up the one above.
dataset = Dataset.from_source("s3://bucket/product.nc", source="s3")
DEFAIR reaches for a client only where one is needed, such as sending S3
credentials to the workers, so a read from a local file adopts nothing
and starts nothing. An adopted client remains yours:
close_dask_client() detaches from it and leaves it running, while a
client handed over with set_dask_client() belongs to DEFAIR and is
closed.
Client Lifecycle
DEFAIR uses a singleton DaskClientManager to ensure only one Dask
client exists across all readers, writers, and transformations. The
client is created when first requested and lives until explicitly
closed:
from defair_data.dask_manager import close_dask_client
# Process your data...
dataset = Dataset.from_source("/path/to/file.nat")
result = dataset.transform("reprojection", target="EPSG:4326")
result.to_file("/path/to/output.zarr")
# Close the client when done with all Dask operations
close_dask_client()
Three main processing options are available:
Mode |
Description |
Best For |
|---|---|---|
Local Threads |
Single process, multiple threads (default) |
Development, I/O-bound work, small-medium datasets |
Local Processes |
Multiple Python processes on one machine |
Reading many scenes at once, and CPU-bound work that a write computes |
Remote Cluster |
Distributed cluster via Dask Gateway |
Large datasets, production workloads, shared resources |
Processing Modes Explained
Local Threads (Default)
By default no distributed client is created at all: lazy operations
execute on Dask’s threaded scheduler. When a managed client is requested
(e.g. non-empty dask_client_kwargs or dask_client_context),
DEFAIR creates its own Dask Client() with a LocalCluster in threaded
mode (processes=False, n_workers=None). Either way this mode:
Runs all workers in a single Python process with multiple threads
Shares memory between workers (efficient for I/O-bound operations)
Avoids multiprocessing spawn issues
Works well for most filtering and data selection operations
from defair_data.core import Dataset
# Default: uses local threads
dataset = Dataset.from_source("/path/to/file")
To customize the default client configuration, pass
dask_client_kwargs:
# Customize the default LocalCluster
dataset = Dataset.from_source(
"/path/to/file",
dask_client_kwargs={"n_workers": 4, "memory_limit": "2GB"}
)
Pros:
Minimal overhead
Efficient memory sharing
No cost for moving data between processes
Works reliably across all platforms
Cons:
Limited by Python’s GIL for CPU-bound operations
Cannot exceed single-machine resources
When to use:
Development and testing
I/O-bound operations (reading, filtering, subsetting)
Datasets that fit in memory
Quick exploratory analysis
Local Processes
Uses multiple Python processes on a single machine, bypassing the GIL limitation for CPU-bound work.
from dask.distributed import Client, LocalCluster
from defair_data.dask_manager import set_dask_client
# Create a local cluster with multiple processes
cluster = LocalCluster(
n_workers=4,
threads_per_worker=2,
memory_limit="4GB",
processes=True # Use separate processes
)
client = Client(cluster, set_as_default=False)
# Register with DEFAIR
set_dask_client(client)
# Now use DEFAIR as usual
dataset = Dataset.from_source(["/path/to/scene1.nat", "/path/to/scene2.nat"])
On its own, Client(cluster) would also make this client Dask’s
process-wide scheduler. set_as_default=False stops that. Whether the
client is the process-wide scheduler decides where each piece of work
runs:
DEFAIR sends its own work to the registered client explicitly. A multi-file read therefore sends one task per scene to the worker processes either way. That task opens the scene and builds its graph. The chunk reads it leaves for later run on the process-wide scheduler, like everything in the next point.
Your own
.compute(),.persist()and.load()calls run on the process-wide scheduler. So does the graph that a Zarr, NetCDF or imageto_file()write computes. Withset_as_default=False, all of them stay on local threads.The Parquet, GeoParquet and CSV writers are the exception. They compute their columns on the registered client explicitly. A column output therefore sends its data to the worker processes and back, whatever this flag says.
Which arrangement is faster depends on what your own compute does. If it mostly moves data that is cheap to produce, keeping that data in the driver is faster, and this recipe is the one to use. If the compute is CPU-bound per byte, as decompressing an FCI channel is, the worker processes repay the cost of moving the data to them. The measurements below cover both cases.
To run one call on the workers, pass it to
compute_with_managed_client from defair_data.dask_manager. It
sends that single computation to the registered client and leaves Dask’s
global configuration alone. with client.as_current(): also works,
but it makes the cluster the process-wide scheduler for the whole block.
Any other thread that computes at the same time is then sent to the
cluster too.
Pros:
True parallelism for CPU-bound operations
Can utilize all CPU cores effectively
Better isolation between workers
Cons:
Higher memory overhead (each process has its own memory space)
Data is copied when it passes between worker processes
May encounter spawn issues (use
if __name__ == "__main__":guard)
When to use:
Reading many scenes at once
Large datasets that benefit from parallel computation
Multiple CPU cores are available
The parallelism is across scenes rather than across files. The reader assembles every file belonging to one scene in a single call, so an MTG FCI repeat cycle of 40 chunk files is one unit of work. Reading a single scene takes the serial path, however many files it holds.
Measured: reading several scenes at once
The example below globs four repeat cycles for that reason:
from pathlib import Path
from defair_data.core import Dataset
# Four repeat cycles of about 40 chunk files each, which the reader groups into four scenes.
chunks = [
str(path)
for cycle in sorted(Path("/path/to/fdhsi").iterdir())
for path in sorted(cycle.glob("*CHK-BODY*.nc"))
]
dataset = Dataset.from_source(chunks, reader="mtg_fci_l1c_nc", channels=["ir_105", "wv_63"])
loaded = dataset.data.load()
Measured on a 12-core cloud node reading from local disk, with
LocalCluster(n_workers=4, threads_per_worker=1, memory_limit="6GB", processes=True)
and DEFAIR_MULTI_SOURCE_PARALLELISM=4. Five repeats per mode, each
in its own process, with the mode order rotated so drift cannot favour
one of them. Medians in seconds for the read plus a .load() of the
listed channels:
workload |
no cluster |
keeping the process default |
set_as_default=False |
|---|---|---|---|
MTG FCI, 4 scenes (160 chunk files), 2 IR channels |
58.4 |
18.4 |
23.1 |
MSG SEVIRI, 6 scenes, 4 channels |
6.3 |
9.5 |
6.8 |
The two missions load the cluster differently. Assembling an FCI scene
from its chunks is real work, and it is the part that fans out. That
read costs 47.4 s serially and 10.4 s on the cluster, whichever setting
you choose. DEFAIR submits one task per scene to the registered client,
whatever the flag says. A SEVIRI read is already cheap and lazy at 1.8 s
in every mode, so for MSG the whole question is where the .load()
runs, and there the process-wide default costs more than using no
cluster at all.
Read the recipe accordingly. Keep set_as_default=False for MSG, and
for any compute that mostly ships finished data back. For a multi-scene
FCI read whose compute is decompression, or for a CPU-bound transform
that a write computes, the process-wide scheduler is what puts that work
on the processes: copy the variant under CPU-Intensive
Operations instead.
Remote Cluster (Dask Gateway)
Connects to a distributed Dask cluster, typically managed by Dask Gateway in cloud environments.
from dask_gateway import Gateway
from defair_data.dask_manager import set_dask_client
# Connect to Dask Gateway
gateway = Gateway()
# Create a new cluster with desired resources
cluster = gateway.new_cluster(
**cluster_options_here
)
# Scale to desired number of workers
cluster.scale(4)
# Get the client and register with DEFAIR
client = cluster.get_client()
set_dask_client(client)
dataset = Dataset.from_source("s3://bucket/file.nat")
result = dataset.transform("reprojection", target="EPSG:4326")
result.to_file("s3://bucket/output.zarr")
# Clean up when done
cluster.close()
cluster.get_client() registers the gateway client as the
process-wide scheduler, and here that is what you want: the workers sit
next to the data, so unscoped computation belongs on them rather than in
the driver. DEFAIR still computes a write to a local path on threads,
because remote workers cannot reach the driver’s filesystem.
Pros:
Scales beyond single-machine resources
Better for production workloads
Cons:
Additional setup
Network latency between client and workers
Resource management overhead
When to use:
Datasets larger than local machine memory
Production pipelines requiring reliability
Multi-user environments with shared resources
Memory in notebook kernels and workers
Set MALLOC_ARENA_MAX=2 in the environment of notebook kernels and
Dask workers. The C allocator gives each thread that reads its own
memory pool and keeps freed pages in it. A read that runs on new worker
threads therefore leaves memory behind. Reading a day of Lightning
Imager granules a second time kept 177 MB, and 126 MB with the setting.
The variable takes effect only when the process starts, so put it in the
env of the kernel specification (kernel.json) and in the
environment the workers start with; setting it from a running notebook
changes nothing.
When to use which Dask profile
Lightweight Operations
(e.g.: Content Filter, Temporal Filter, Spatial Filter)
These operations perform metadata selection or create boolean masks without heavy computation:
# These operations are efficient with local threads
dataset = Dataset.from_source("/path/to/file.nat")
# All of these are very fast with default configuration
filtered = (
dataset
.transform("content_filter", include_vars=["ch1", "ch9"])
.transform("temporal_filter", start_time="2024-01-01", end_time="2024-01-31")
.transform("spatial_filter", lat_min=35, lat_max=45, lon_min=5, lon_max=20)
)
Recommendation: Use default Local Threads. Overhead of processes or remote cluster is not justified.
CPU-Intensive Operations
(e.g.: Reprojection)
Coordinate transformation and resampling require significant CPU work per chunk:
from dask.distributed import Client, LocalCluster
from defair_data.dask_manager import set_dask_client
# For datasets > 5GB, consider local processes
cluster = LocalCluster(n_workers=4, threads_per_worker=1, processes=True)
# Unlike the read-oriented recipe above, keep this client as the process-wide
# scheduler: the write below computes the reprojection, and it is the process-wide
# scheduler that executes it.
client = Client(cluster, set_as_default=True)
set_dask_client(client)
dataset = Dataset.from_source("/path/to/large_file.nat")
reprojected = dataset.transform(
"reprojection",
target="EPSG:4326",
resolution=0.05,
resampling="bilinear"
)
reprojected.to_file("/path/to/output.zarr")
Recommendation: Local Processes for medium datasets (5-50GB), Remote Cluster for larger. The two local-process recipes differ on purpose: opt out of the process-wide scheduler when reads dominate and results come back to the driver, keep it when a transform is the expensive part and a write computes it. Keeping it also sends unrelated small computations in the same process through the cluster, which is the slower path for them.
The 2D lat/lon grid is deferred
Geostationary readers can attach a 2D lat/lon grid derived from
the projection axes, and xarray computes a variable’s coordinates
whenever you compute its data. On a full-disk scene that grid is most of
the read cost, so a plain read does not build it:
dataset = Dataset.from_source(path, reader="mtg_l2_clm") # projection-only
located = dataset.with_latlon() # pair on demand, per grid
The 1D x/y axes and the CF grid mapping place every pixel, so
the transformations work out what they need themselves:
Reprojection and HEALPix work from the CRS.
The spatial filter builds lat/lon only on the window of pixels it needs, not on the full grid.
Conservative regridding and alignment take their geometry from the projection axes.
Writers compute and store the pair, so a written store is complete. The full model is in Add latitude and longitude coordinates.
For sizing, the operation to watch is conservative regridding. Its weights are computed eagerly, so peak memory follows the source pixel count and neither the target grid nor the Dask configuration bounds it. Both memory and time scale close to linearly with that count. Measured on a cluster worker onto a 0.1 degree target:
source |
cells |
peak RSS |
wall clock |
|---|---|---|---|
2048 x 2048 |
4.2 M |
3.26 GB |
89.7 s |
4096 x 4096 |
16.8 M |
7.92 GB |
228.6 s |
5568 x 5568 (full MTG disk) |
31.0 M |
12.89 GB |
399.9 s |
A full disk therefore fits comfortably on a 40 GiB worker, at roughly 13
GB and six and a half minutes. Size the worker from the source pixel
count on that basis. The case that does not fit is a padded MSG HRV grid
(124 M cells), which extrapolates to near 50 GB and has not been run. On
a laptop, filter or select_grid() first, or use a different
regridding method.
What to do next
Continue with Configure logging to set the log level for your processing runs. To compare threaded and single-threaded execution on the same dataset, follow Faster reads with Dask.