Faster reads with Dask

Note

Download the executable 05_parallel_reads_with_dask.ipynb to run this tutorial in JupyterLab.

DEFAIR reads lazily. Dataset.from_source returns a description of the work: it reads each file’s header, which is what tells it the shape of the arrays, and defers every science value until something asks for it. That matters most when the work is many files: three MTG FCI scenes are about a hundred and twenty chunk files, and whether they are opened and decoded one after another or at the same time is the difference this tutorial measures.

The same three scenes are computed twice, from the same lazy dataset, under two Dask schedulers. Nothing else changes. The elapsed times printed below come from the run that produced this notebook’s committed output; they are illustrative, and your own numbers will depend on your link to the object store.

Before running this notebook, complete the shared setup in Tutorials.

Prerequisites

No. 1 Input data

The notebook reads these products from the public demo bucket of the DestinE Data Lake, without an account or credentials:

  • Three MTG FCI Level-1c scenes, 120 chunk files in total

To use your own files instead, change FDHSI_PREFIX and the scene names in SCENE_SUFFIXES and follow Prepare data access for DEFAIR. It explains how to read them from your own object store, from a local disk or through HDA. HDA does not carry FCI Level 1c. Download it from the EUMETSAT Data Store.

Set up the notebook

import time
from pathlib import Path

import dask
import numpy as np

from defair_data.core import Dataset
from defair_data.dask_manager import close_dask_client
from defair.logging import setup_logging
from defair.plugin_manager import load_source

# Readers log every step at DEBUG. WARNING keeps this notebook's output to the timings it
# prints, and is the level to raise when a read does something unexpected.
setup_logging(log_level="WARNING")

OUTPUT_DIR = Path("output")
OUTPUT_DIR.mkdir(exist_ok=True)

Three full-disc scenes

One channel of each, which is what keeps this tutorial to a few minutes. The chunk count is the number that matters: every one of those files is a separate object to fetch.

# The public Data Lake demo bucket, which needs no credentials.
PUBLIC_S3 = {"endpoint_url": "https://s3.central.data.destination-earth.eu", "anon": True}
s3 = load_source("s3", **PUBLIC_S3)
FDHSI_PREFIX = "s3://datalake-demo-data/defair-notebook-data/mtg-fci-l1c-fdhsi/"
# A listing can also return a folder marker for the prefix itself and loose chunk files;
# the scenes are the entries that are neither.
available = [
    entry
    for entry in sorted(s3.list(FDHSI_PREFIX))
    if not entry.endswith(".nc") and entry.rstrip("/") != FDHSI_PREFIX.rstrip("/")
]
# Three consecutive repeat cycles, pinned by the end of their scene names so the run
# reads the same scenes every time.
SCENE_SUFFIXES = (
    "_20251215090923_N__O_0055_0000",
    "_20251215091923_N__O_0056_0000",
    "_20251215092923_N__O_0057_0000",
)
scenes = []
for suffix in SCENE_SUFFIXES:
    matches = [entry for entry in available if entry.rstrip("/").endswith(suffix)]
    assert len(matches) == 1, f"scene ending {suffix} not found once under {FDHSI_PREFIX}: {matches}"
    scenes.append(matches[0])
chunks = []
for scene in scenes:
    bodies = sorted(f for f in s3.list(scene) if "CHK-BODY" in f)
    print(f"{scene.rstrip('/').split('/')[-1][-30:]}: {len(bodies)} chunks")
    chunks.extend(bodies)

print(f"\ntotal chunk files: {len(chunks)}")
_20251215090923_N__O_0055_0000: 40 chunks
_20251215091923_N__O_0056_0000: 40 chunks
_20251215092923_N__O_0057_0000: 40 chunks

total chunk files: 120

The lazy read

Building the dataset reads each file’s header, which for a hundred and twenty objects is not free, but it moves no science data. What comes back is a task graph, and the elapsed time below is the cost of describing the work rather than doing it.

It is the larger of the three times printed in this tutorial, which surprises people. The header pass has to open all hundred and twenty objects to read their chunk geometry, coordinates and attributes before it can describe a single array. The two timed passes below then fetch and decode one channel out of files whose layout is already known.

start = time.perf_counter()
scenes_dataset = Dataset.from_source(
    chunks, reader="mtg_fci_l1c_nc", source="s3", source_kwargs=PUBLIC_S3,
    use_channel_names=True, channels=["ir_105"]
)
build_seconds = time.perf_counter() - start

field = scenes_dataset.data["ir_105"]
print(f"building the lazy dataset took {build_seconds:.2f} s")
print(f"dimensions: {dict(scenes_dataset.data.sizes)}")
print(f"still a Dask array: {hasattr(field.data, 'dask')}")
print(f"tasks in the graph: {len(field.data.__dask_graph__())}")
building the lazy dataset took 94.50 s
dimensions: {'time': 3, 'y_2km': 5568, 'x_2km': 5568, 'bnds': 2}
still a Dask array: True
tasks in the graph: 1704

Without parallelism

single-threaded is Dask’s scheduler for exactly this comparison: the same graph, executed one task at a time. The reads happen one file after another.

start = time.perf_counter()
with dask.config.set(scheduler="single-threaded"):
    serial_mean = float(field.mean().compute())
serial_seconds = time.perf_counter() - start
print(f"serial read and mean: {serial_seconds:.1f} s  (mean {serial_mean:.2f})")
serial read and mean: 23.2 s  (mean 75.35)

With parallelism

The default threaded scheduler runs independent tasks at the same time. That can save time when each task spends most of its time waiting for a reply from the object store. It saves little when a single stream already uses the whole link.

start = time.perf_counter()
with dask.config.set(scheduler="threads"):
    parallel_mean = float(field.mean().compute())
parallel_seconds = time.perf_counter() - start
print(f"parallel read and mean: {parallel_seconds:.1f} s  (mean {parallel_mean:.2f})")

assert np.isclose(serial_mean, parallel_mean), "the two schedulers disagreed on the result"
print(f"\nsame answer either way: {serial_mean:.4f}")
print(f"speed-up on this run: {serial_seconds / parallel_seconds:.1f}x")
parallel read and mean: 20.8 s  (mean 75.35)

same answer either way: 75.3453
speed-up on this run: 1.1x

What this does and does not tell you

The two runs computed the same number, which is the first thing to check: parallelism that changes the answer is a bug, not a speed-up.

Read the ratio with what each pass does in mind. Each timed pass fetches its channel from the object store, about 1 GB of transfer for these three scenes, and decodes it. On our test machines a single stream already used most of the link, so fetching many chunks at once saved almost nothing and the ratio came out between 1.0x and 1.1x. It stayed between 1.0x and 1.2x with Dask limited to 1, 2, 4 and 16 cores, and with the process-based scheduler, so the limit was the link and not the processor. On a link where each request waits longer than it transfers, running the fetches at the same time can give a ratio above 1. The ratio above is one measurement on one link to one object store, not a figure to quote.

Two things generalise. Parallel reads can help when the time goes to waiting on many separate requests, and not when one stream fills the link. And any gain comes from the lazy read. DEFAIR built one graph over all the chunks, so the scheduler had something to overlap. A loop that reads and computes each scene in turn loses the overlap between scenes. The forty chunks within one scene still run in parallel, so what it gives up is the cross-scene overlap rather than all of it.

What to do next

See Run on a Dask cluster for choosing a scheduler for larger work, including when to move from threads to processes or to a cluster.

close_dask_client()