Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Why do 121 tiles take 6.4 s, and what gets them to 0.21 s?

GeoStack · background · one worker → many

Abstract

Pictures first, maths folded away. Threads, processes and async are three ways to do more than one thing at a time in Python. Which one helps depends on a single question: is your program waiting, or is it computing? This page answers it for one read, with measured numbers.

The running example

The problem: one thing at a time

Serial: fetch a tile, decode it, then the next

one worker … 117 more

0 ms0\ \mathrm{ms}50 ms50\ \mathrm{ms}100 ms100\ \mathrm{ms}150 ms150\ \mathrm{ms}200 ms200\ \mathrm{ms}

waiting on the network (fetch, 50 ms50\ \mathrm{ms})computing (decode, 2.2 ms2.2\ \mathrm{ms})

Drawn to scale. Four tiles take 209 ms; all 121 take 6.38 s (measured). The worker spends almost all of it idle, waiting.

# Shapes: N = 121 tiles; P = 512 px tile side

# user
def fetch(index: int) -> bytes: ...          # one range request, ~50 ms of waiting
# user
def decode(blob: bytes) -> np.ndarray: ...   # inflate + undo predictor  → (P, P)

# T = N (t_fetch + t_decode)
tiles = [decode(fetch(index)) for index in range(121)]      # → 121 × (P, P)

Two kinds of work

One tile, 52.2 ms52.2\ \mathrm{ms}

waiting: request sent, bytes on their way · 50 ms50\ \mathrm{ms} · 96 %96\ \%

computing: inflate + undo predictor · 2.2 ms2.2\ \mathrm{ms} · 4 %4\ \% →

I/O-bound: the CPU is free during the wait.

CPU-bound: the CPU is busy the whole time.


:::{div}
:class: gs-figcap
The two kinds of work in one tile. Everything on this page follows from which of the two you are trying to shorten.

A program is I/O-bound when its time goes on waiting for something outside it: a network reply, a disk. It is CPU-bound when its time goes on computing. Our read is 96 % waiting, so the first thing to do is stop waiting for one tile before asking for the next.

How much can overlapping the waits buy? (Amdahl’s law)

Let pp be the fraction of the serial time that can be overlapped, and WW how many of those pieces run at once. The speed-up is

S(W)=1(1−p)+p/WS(W) = \frac{1}{(1 - p) + p / W}

Here the waits are the part we overlap, so p=tf/(tf+td)=50/52.17=0.958p = t_f / (t_f + t_d) = 50 / 52.17 = 0.958. With every wait overlapped, W→∞W \to \infty and

Smax⁡=11−p=24.0S_{\max} = \frac{1}{1 - p} = 24.0

The floor is the computing that is left, Ntd=121×2.17 ms=0.26 sN t_d = 121 \times 2.17\ \mathrm{ms} = 0.26\ \mathrm{s}. To go below it, the decodes themselves have to run in parallel.

Concurrency is not parallelism

Concurrency: one worker, overlapping waitsrequest 1request 2request 3one workersendhandle replies
One cook, three pots on the stove.The waits overlap; the work does not.
Parallelism: several workers computing at oncecore 1core 2one coresame work
Two cooks, two chopping boards.The work itself is split.

Concurrency shortens waiting. Parallelism shortens computing. Async gives you only the first; processes give you the second; threads give you the first always and the second sometimes.

Concurrency is dealing with several things in the same period. Parallelism is doing several things at the same instant. A single core can be concurrent; only several cores can be parallel.

Part 1 · The three mechanisms

Async: one thread that never waits idle

Async: one thread, eight requests in flight

request 1

request 8

event loop one thread

0 ms0\ \mathrm{ms}50 ms50\ \mathrm{ms}100 ms100\ \mathrm{ms}150 ms150\ \mathrm{ms}200 ms200\ \mathrm{ms}

waiting on the network (fetch, 50 ms50\ \mathrm{ms})computing (decode, 2.2 ms2.2\ \mathrm{ms})

Eight waits overlap, but the eight decodes queue on the single thread: while the loop decodes, nothing else runs. That queue is async’s floor.

An event loop runs on one thread. Each await is a point where a task says “I am waiting; run someone else”. The loop keeps a list of what is waiting on what, and resumes each task when its reply arrives. No locks are needed, since only one task runs at a time.

import asyncio

async def read_tile(index: int, limit: asyncio.Semaphore) -> np.ndarray:
    async with limit:                        # at most 16 requests in flight
        blob = await afetch(index)           # the loop runs other tiles meanwhile
    return decode(blob)                      # blocks the loop for ~2 ms

async def read_all() -> list[np.ndarray]:
    limit = asyncio.Semaphore(16)
    return await asyncio.gather(*(read_tile(i, limit) for i in range(121)))

tiles = asyncio.run(read_all())                             # → 121 × (P, P)

Measured: 0.67 s with 16 in flight, 0.38 s with 64. The remaining time is mostly the 0.26 s of decoding, queued on the one thread. Moving the decode to a thread removes that queue (0.44 s with 16 in flight):

    # hand the computing to a thread so the loop keeps serving requests
    return await asyncio.to_thread(decode, blob)

Threads: several workers, one shared memory

Threads: four workers, each fetching and decoding

thread 1

thread 2

thread 3

thread 4

0 ms0\ \mathrm{ms}50 ms50\ \mathrm{ms}100 ms100\ \mathrm{ms}150 ms150\ \mathrm{ms}200 ms200\ \mathrm{ms}

waiting on the network (fetch, 50 ms50\ \mathrm{ms})computing (decode, 2.2 ms2.2\ \mathrm{ms})

Sixteen tiles in the time serial code reads four. The decodes overlap here because zlib and NumPy release the GIL; see the next figure for when they cannot.

A thread is a worker inside your process. Threads share all memory, so passing an array between them costs nothing, and the operating system switches between them whenever one waits. Ordinary blocking code works unchanged.

import concurrent.futures

def read_tile(index: int) -> np.ndarray:
    return decode(fetch(index))              # ordinary blocking code

with concurrent.futures.ThreadPoolExecutor(max_workers=16) as pool:
    tiles = list(pool.map(read_tile, range(121)))           # → 121 × (P, P)

Measured: 1.64 s with 4 threads, 0.44 s with 16 (14×), 0.21 s with 64 (30×).

The GIL: why threads sometimes do not compute in parallel

Pure-Python work: threads take turns holding the GIL

thread 1

thread 2

One runs, one waits for the lock.

2 threads: 0.35 s0.35\ \mathrm{s} vs 0.33 s0.33\ \mathrm{s} serial.

Native work: the library releases the GIL

thread 1

thread 2

Both compute at once inside zlib / NumPy.

2 threads: 0.14 s0.14\ \mathrm{s} vs 0.25 s0.25\ \mathrm{s} serial.

Purple: holding the GIL (the interpreter lock). Top: pure Python, so two threads are slower than one. Bottom: decode-only work in zlib and NumPy, which drop the lock while they compute, so two threads give 2×. Measured on this page’s 2-core machine, 121 tiles.

CPython has a global interpreter lock (GIL): only one thread at a time may run Python bytecode. A thread gives it up when it waits on I/O, which is why threads work for fetching. Native libraries also give it up while they compute, which is why NumPy, zlib, zarr codecs and Rust extensions do run in parallel on threads. Pure-Python loops do not.

Decode-only, 121 tiles (measured)Serial2 threads2 processes
Pure-Python loop (holds the GIL)0.33 s0.35 s0.19 s
zlib + NumPy (release the GIL)0.25 s0.14 s0.17 s

Python 3.13 added an optional free-threaded build without the GIL, and 3.14 made it officially supported. On it, pure-Python threads do run in parallel, provided every compiled dependency supports it. The numbers on this page are from the standard build.

Processes: separate interpreters

Processes: separate interpreters, separate memory
parent processtask listresults
worker process 1own interpreter, own GILown copy of the data
worker process 2own interpreter, own GILown copy of the data

Nothing is shared, so nothing needs a lock, and every argument and result is copied. Measured here: 24 ms to start two workers, 0.08 ms to pickle one 512 × 512 tile each way.

A process is a separate running Python with its own memory and its own GIL. Several processes compute in parallel whatever the code is. The price is that they share nothing: every task and result is serialised (pickled), sent, and rebuilt.

import concurrent.futures

# read_tile must be importable (top level of a module), and its
# arguments and results must pickle
if __name__ == "__main__":
    with concurrent.futures.ProcessPoolExecutor(max_workers=2) as pool:
        tiles = list(pool.map(read_tile, range(121), chunksize=8))

Measured on the full read: 3.24 s with 2 processes, 0.56 s with 16. For a job that is 96 % waiting, processes are just expensive threads. They pay off in the pure-Python row of the table above, where threads made things slower.

Part 2 · Below and above

Below: make one worker faster

Scale one tile to reflectance: (DN−1000)/10 000(\mathrm{DN} - 1000) / 10\ 000

Python loop, 262 144 steps

12.0 ms12.0\ \mathrm{ms}

One NumPy expression

0.26 ms0.26\ \mathrm{ms}


:::{div}
:class: gs-figcap
46× on one core, with no threads, processes or event loop. Do this first.
:::
# ρ = (DN − 1000) / 10 000

# Today: one Python step per pixel
reflectance = [[(dn - 1000) / 10000 for dn in row] for row in tile.tolist()]
# After: one array expression
reflectance = (tile.astype(np.float32) - 1000) / 10000      # (P, P) → (P, P)

Vectorising replaces a Python loop with one call that loops in compiled code, often using the CPU’s SIMD instructions (several numbers per instruction). jax.vmap and jax.jit do the same for whole functions, and a GPU does it across thousands of cores. None of this is a thread, a process or an event loop in your code, and it usually comes first.

Above: more machines

Distributed: a scheduler hands tasks to machines
scheduler · task graph
machine 164 threads
machine 264 threads
machine 364 threads
machine 464 threads
Same ideas as processes, plus a network between them and a scheduler above them.

500 scenes is 60 500 tiles. Extrapolated from the one-scene measurements (not measured): serial about 53 min, one machine with 64 threads about 1.8 min, four such machines about 27 s.

A distributed system is processes on several machines with a scheduler that hands out tasks and tracks results. dask does this with a task graph; a batch service does it with one job per scene. The costs of processes return, larger: data crosses a network, so workers should read from object storage themselves and send back small results.

Choosing

Can it be one array operation?
yes
Vectorise: NumPy, JAXbefore anything else
no
Is the slow part waiting (network, disk)?
yes
Threadsor async, if the library is async
no
Does the computing run in native code?
yes
ThreadsNumPy, zlib, Rust release the GIL
no
Is it pure-Python computing?
yes
Processesor free-threaded Python
no
Too big for one machine?
yes
Distributed: dask, batch jobsthe same choices, per machine

Ask in this order. The answers stack: a dask cluster runs threads on each machine, and each thread calls vectorised code.

AsyncThreadsProcesses
Overlaps waitingyesyesyes, at a high cost
Overlaps native computingnoyesyes
Overlaps pure-Python computingnono (GIL build)yes
Memorysharedsharedseparate; data is copied
Cost per workerkilobytesa stack (about a megabyte reserved)an interpreter; 24 ms to start two here
Your code must beasync all the way downthread-safe where state is sharedpicklable and importable
How it goes wrongone blocking call stalls everythingraces on shared state; oversubscriptionpickling errors; memory multiplied by workers
Limit it withasyncio.Semaphoremax_workersmax_workers, chunksize

Whichever you pick, bound it. 60 500 unbounded requests will be throttled by the object store, and 60 500 queued results can exhaust memory. A limit on work in flight (a semaphore, a worker count, a submission window) is part of the design.

The numbers, mechanism by mechanism

Serial

6.38 s6.38\ \mathrm{s}

Async, blocking call inside (the trap)

6.40 s6.40\ \mathrm{s}

2 processes

3.24 s3.24\ \mathrm{s}

4 threads

1.64 s1.64\ \mathrm{s}

Async, 16 in flight

0.67 s0.67\ \mathrm{s}

16 processes

0.56 s0.56\ \mathrm{s}

16 threads

0.44 s0.44\ \mathrm{s}

Async, 16 in flight, decode in threads

0.44 s0.44\ \mathrm{s}

Async, 64 in flight

0.38 s0.38\ \mathrm{s}

64 threads

0.21 s0.21\ \mathrm{s}


:::{div}
:class: gs-figcap
Measured: 121 tiles, 50 ms simulated latency per fetch, real deflate decode, CPython 3.13 with the GIL, 2 cores, best of three runs.
:::

The wall-clock model behind each bar

With NN tiles, fetch time tft_f, decode time tdt_d, WW workers and NcoreN_\text{core} cores:

MechanismModelPredictedMeasured
SerialN(tf+td)N (t_f + t_d)6.31 s6.38 s
16 threads⌈N/W⌉(tf+td)\lceil N / W \rceil (t_f + t_d)0.42 s0.44 s
64 threadsmax⁡(⌈N/W⌉(tf+td), Ntd/Ncore)\max(\lceil N / W \rceil (t_f + t_d),\ N t_d / N_\text{core})0.13 s0.21 s
Async, 64 in flight⌈N/W⌉tf+Ntd\lceil N / W \rceil t_f + N t_d0.36 s0.38 s
2 processesN(tf+td)/WN (t_f + t_d) / W + start-up3.18 s3.24 s

The 64-thread row shows the switch from I/O-bound to CPU-bound: once the waits overlap enough, the decodes on two cores set the pace, and pool overhead accounts for the rest of the gap to the measurement. The async model is an upper bound, since waits continue while the loop decodes.

In your stack

Checked at geotoolz 640670c, pipekit 9e86a56 and zarr 3.4.2. The stack already uses all three mechanisms; the table says where.

WhereMechanismWhat it does
geocloud CogSource, cog_readerasyncCOG reads through async-geotiff on a pooled obstore client (both Rust); the read functions are async def
geocloud aio._run_coroutine_safelyasync → sync bridgeruns a coroutine from blocking code; if a loop is already running (Jupyter), it runs it on a worker thread with its own loop
geocloud files (copy)threadsThreadPoolExecutor, max_concurrency=8
geocatalog formats/raster.pythreadsThreadPoolExecutor(n_workers) for building catalogs and loading rasters
geocatalog storage/streaming.pyprocessesProcessPoolExecutor with spawn and a bounded submission window
geopatcher runnersthreads or processesbackend="thread" | "process", with max_in_flight; also exports to dask delayed and bag
pipekit Mapthreads or processesMap(op, executor="thread", n_workers=…), bounded by max_in_flight
zarr v3async + threadsthe blocking API drives an event loop on a background thread (zarr_io); async.concurrency defaults to 10; codecs decode via asyncio.to_thread
dask (from its docs)threads, processes or distributedthreads by default for arrays, processes for bags, a cluster with distributed
JAXvectorisingvmap and jit compile the loop away; on a GPU the parallelism is in the device

Calling async code from blocking code

The place the mechanisms meet is also where notebooks break. asyncio.run starts a loop, and a thread can run only one:

# In a script: fine
tiles = asyncio.run(read_all())

# In a notebook cell, a FastAPI handler or a pytest-asyncio test:
#   RuntimeError: asyncio.run() cannot be called from a running event loop
# In a notebook, await directly instead:
tiles = await read_all()

Libraries that offer a blocking API over async internals solve this once, with a loop on a background thread. zarr does it with its zarr_io thread, and geocloud with _run_coroutine_safely. That pattern is why xr.open_zarr works in a notebook without an await in sight.

Where this goes next

Idea hereShows up in the design docs as
Overlapping range requestshow a window read fetches its tiles (storage formats) and how virtual chunks are read through Icechunk
A bound on work in flightingest of many scenes into one repository (Level 2 collections, B and E)
Processes share nothingwhy concurrent writers need transactions rather than a shared file (Level 2 collections, B)
Tasks safe to run twiceupserts in the product catalog (F, L)