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
waiting on the network (fetch, )computing (decode, )
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,
computing: inflate + undo predictor · · →
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 be the fraction of the serial time that can be overlapped, and how many of those pieces run at once. The speed-up is
Here the waits are the part we overlap, so . With every wait overlapped, and
The floor is the computing that is left, . To go below it, the decodes themselves have to run in parallel.
Concurrency is not parallelism¶
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
waiting on the network (fetch, )computing (decode, )
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
waiting on the network (fetch, )computing (decode, )
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: vs serial.
Native work: the library releases the GIL
thread 1
thread 2
Both compute at once inside zlib / NumPy.
2 threads: vs 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) | Serial | 2 threads | 2 processes |
|---|---|---|---|
| Pure-Python loop (holds the GIL) | 0.33 s | 0.35 s | 0.19 s |
| zlib + NumPy (release the GIL) | 0.25 s | 0.14 s | 0.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¶
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¶
One NumPy expression
:::{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¶
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¶
Ask in this order. The answers stack: a dask cluster runs threads on each machine, and each thread calls vectorised code.
| Async | Threads | Processes | |
|---|---|---|---|
| Overlaps waiting | yes | yes | yes, at a high cost |
| Overlaps native computing | no | yes | yes |
| Overlaps pure-Python computing | no | no (GIL build) | yes |
| Memory | shared | shared | separate; data is copied |
| Cost per worker | kilobytes | a stack (about a megabyte reserved) | an interpreter; 24 ms to start two here |
| Your code must be | async all the way down | thread-safe where state is shared | picklable and importable |
| How it goes wrong | one blocking call stalls everything | races on shared state; oversubscription | pickling errors; memory multiplied by workers |
| Limit it with | asyncio.Semaphore | max_workers | max_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¶
Async, blocking call inside (the trap)
2 processes
4 threads
Async, 16 in flight
16 processes
16 threads
Async, 16 in flight, decode in threads
Async, 64 in flight
64 threads
:::{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 tiles, fetch time , decode time , workers and cores:
| Mechanism | Model | Predicted | Measured |
|---|---|---|---|
| Serial | 6.31 s | 6.38 s | |
| 16 threads | 0.42 s | 0.44 s | |
| 64 threads | 0.13 s | 0.21 s | |
| Async, 64 in flight | 0.36 s | 0.38 s | |
| 2 processes | + start-up | 3.18 s | 3.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.
| Where | Mechanism | What it does |
|---|---|---|
geocloud CogSource, cog_reader | async | COG reads through async-geotiff on a pooled obstore client (both Rust); the read functions are async def |
geocloud aio._run_coroutine_safely | async → sync bridge | runs 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) | threads | ThreadPoolExecutor, max_concurrency=8 |
geocatalog formats/raster.py | threads | ThreadPoolExecutor(n_workers) for building catalogs and loading rasters |
geocatalog storage/streaming.py | processes | ProcessPoolExecutor with spawn and a bounded submission window |
geopatcher runners | threads or processes | backend="thread" | "process", with max_in_flight; also exports to dask delayed and bag |
pipekit Map | threads or processes | Map(op, executor="thread", n_workers=…), bounded by max_in_flight |
| zarr v3 | async + threads | the 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 distributed | threads by default for arrays, processes for bags, a cluster with distributed |
| JAX | vectorising | vmap 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 here | Shows up in the design docs as |
|---|---|
| Overlapping range requests | how a window read fetches its tiles (storage formats) and how virtual chunks are read through Icechunk |
| A bound on work in flight | ingest of many scenes into one repository (Level 2 collections, B and E) |
| Processes share nothing | why concurrent writers need transactions rather than a shared file (Level 2 collections, B) |
| Tasks safe to run twice | upserts in the product catalog (F, L) |
Sources and status
Sources: the Python documentation for asyncio, concurrent.futures and free threading; PEP 703; the dask scheduling guide; the zarr-python 3.4.2 source; geotoolz at 640670c and pipekit at 9e86a56. Timings: 121 tiles, 50 ms injected latency, real deflate decode, CPython 3.13 (GIL), 2 cores, best of three, from notebooks/background/parallelism.py with the settings in configs/background/parallelism.yaml (recorded output: docs/images/background_parallelism/results.json); the 500-scene figures are extrapolated, not measured.