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.

How does a request from outside become a product?

GeoStack · background · request → response

Abstract

Pictures first. A backend is the part of a system other programs talk to. This page covers the conventions it speaks (HTTP and REST), the Python library most geo services are written in (FastAPI), the model-serving layer built on it (LitServe), and where each meets the stack. It builds one small service on the NDVI pipeline of the last page and measures it. One distinction runs through it: the catalogs we query are not the catalog we serve.

The running example

HTTP and REST

One request, one response
requestPOST /jobsContent-Type: application/json{"bounds": [723000, 4375000,        728000, 4379000], "start": "2026-06-01", "end": "2026-06-30", "recipe": "ndvi"}
response202 AcceptedContent-Type: application/json{"id": "35d3ee9cf866", "status": "queued", "product_id": null}
method and path: what to do, to what · headers: how the body is written · body: the details status: how it went · the server keeps no memory of the conversation

The actual first exchange with the page’s service. Everything a web API does is this, repeated: text in, text out, one status number.

HTTP is the request-and-response exchange above. REST is a set of habits for using it: every thing the service knows about (a product, a job) is a resource with an address, and the HTTP verbs say what to do with it. You met the same verbs on the object storage page; a bucket is a REST service.

RequestMeansSafe to repeat?In the demo
GET /products?bbox=…&start=…list the products that matchyes: reads change nothing2.3 ms
GET /products/{id}one product’s recordyes200, or 404
POST /jobscreate a runonly if you make it so202, then 200 for the same request
GET /jobs/{id}how is the run goingyesqueued → running → done
PUT, DELETEreplace, removeyes by definitionnot used
StatusSays
200 OKhere is what you asked for
202 AcceptedI have taken the request; the work is not done yet
404 Not Foundno such resource
422 Unprocessablethe request is well-formed but its contents are wrong (FastAPI’s validation answer)
5xxthe server failed; a client may retry, which is why repeating must be safe

Two properties matter more than the rest. A service is stateless when each request carries everything needed to answer it. A request is idempotent when sending it twice has the same effect as sending it once. Both come back below.

Two STACs: the one we query and the one we serve

Upstream: catalogs we query Downstream: what we serve

Their STAC API Earth Search, Planetary Computer, CMR

their scenes, in their buckets

we are the client

Our pipeline search →\to …\ldots →\to write →\to commit →\to publish

Our STAC API others are the clients

Product catalog the same products, as STAC items, read-only

mirror

Product database our table; only the pipeline writes it

products in Icechunk, named by snapshot

publish

Two different STACs. Blue boxes speak the STAC protocol: on the left someone else’s server and we call it; on the right our server and others call it. Orange is what we own and write. The pipeline in the middle is a client on one side and the only writer on the other.

STAC is a vocabulary and a REST API for catalogs of geospatial data (see databases and catalogs). The word appears on both sides of the stack, and they are different things with different owners.

Upstream STACProduct databaseProduct catalog
What it listsa provider’s scenes (Sentinel-2, Landsat, EMIT)what our pipelines producedthe same products, as STAC
Who owns itthe providerusus
Who writes itthe providerthe pipeline’s publish stage, and nothing elsea sync from the product database
ShapeSTAC itemsour own table: the core fields plus whatever we need (recipe, snapshot, quality flags, job)STAC items: the core fields under agreed names
We area clientthe only writerthe server
Reached bypystac-client, geocatalog’s from_stac_searchSQL, from our servicesa STAC API (stac-fastapi over pgstac), by anyone we allow
Pipeline stage1 · search10 · publishafter publish
Status in the stackshipsproposed (K, F)proposed (F, L)
import geocatalog as gc
import pystac_client

# someone else's catalog: we send a search, they answer with STAC items
client = pystac_client.Client.open("https://earth-search.aws.element84.com/v1")
# today* (geocatalog)
scenes = gc.sources.from_stac_search(                 # → a GeoCatalog of their scenes
    client, collections=["sentinel-2-l2a"], bounds=site.bounds,
    datetime="2026-06-01/2026-06-30", asset_key="B04",
)

Why two stores downstream and not one? The product database is ours to shape: it changes with our pipelines and holds things no outside client needs. The product catalog is a promise to others: standard names, read-only, searchable by any STAC tool. Keeping the database as the source of truth and mirroring it outward means the public face can be rebuilt at any time and never has to be written by hand. In code, the product catalog design puts one interface over both, so publish does not care which it is talking to.

FastAPI: a typed function becomes an endpoint

route POST /jobs →\to start_job FastAPI, from the type hints

parse JSON text →\to Python values FastAPI, from the type hints

validate values →\to RunRequest, or 422 FastAPI, from the type hints

your function start_job(request) →\to Job you write this

serialise Job →\to JSON text FastAPI, from the type hints

document all of it →\to /openapi.json, /docs FastAPI, from the type hints

You write one typed function. The five steps around it come from its signature, which is why a wrong request is refused before your code runs. The demo service has 8 paths and 3 data models, all documented without a line of documentation code.

The types are pydantic models: classes whose fields are declared with types and checked when an instance is built. They are the service’s seams, in the sense of the pipeline page: a RunRequest is a GeoSlice that arrived as JSON; a Product is a product record on its way out.

class RunRequest(pydantic.BaseModel):
    """What a client sends to start a job: a site, a period and a recipe."""

    bounds: tuple[float, float, float, float]
    start: datetime.date
    end: datetime.date
    recipe: Literal["ndvi"] = "ndvi"

class Product(pydantic.BaseModel):
    """One row of our product database, as the API returns it."""

    id: str
    start_time: datetime.date
    end_time: datetime.date
    bbox: tuple[float, float, float, float]
    href: str
    snapshot_id: str
    recipe_hash: str

class Job(pydantic.BaseModel):
    """A run in progress or finished; product_id is set once it is done."""

    id: str
    status: Literal["queued", "running", "done", "failed"]
    product_id: str | None = None
@app.get("/products")
def search_products(
    bbox: str | None = None, start: datetime.date | None = None,
    end: datetime.date | None = None,
) -> list[Product]:
    """Our products that touch a box and a period: a query on our own table."""
    clauses, values = ["1 = 1"], []
    if bbox is not None:
        x0, y0, x1, y1 = (float(part) for part in bbox.split(","))
        clauses.append("x0 <= ? AND x1 >= ? AND y0 <= ? AND y1 >= ?")
        values += [x1, x0, y1, y0]
    if start is not None:
        clauses.append("end_time >= ?")
        values.append(str(start))
    if end is not None:
        clauses.append("start_time <= ?")
        values.append(str(end))
    query = f"SELECT * FROM products WHERE {' AND '.join(clauses)} ORDER BY id"
    with database() as db:
        return [product_from_row(row) for row in db.execute(query, values)]

@app.get("/products/{product_id}")
def get_product(product_id: str) -> Product:
    with database() as db:
        row = db.execute("SELECT * FROM products WHERE id = ?", (product_id,)).fetchone()
    if row is None:
        raise fastapi.HTTPException(status_code=404, detail="no such product")
    return product_from_row(row)

The record that comes back is the one the pipeline published:

{
  "id": "ndvi_35d3ee9cf866",
  "start_time": "2026-06-01",
  "end_time": "2026-06-30",
  "bbox": [
    723000.0,
    4375000.0,
    728000.0,
    4379000.0
  ],
  "href": "products.icechunk#ndvi_35d3ee9cf866",
  "snapshot_id": "ZEEMGHXMGC446YN0A2G0",
  "recipe_hash": "4b8c154a8762594f\u2026"
}

Four kinds of endpoint

KindDoesTakesReady-madeOn this page
Searchwhich products match a place and timemillisecondsstac-fastapi over pgstacGET /products, built small
Readpixels for a window or a map tiletens of milliseconds, mostly waiting on storageTiTilernamed, not built
Runstart a pipelineseconds to hoursnone: this is yoursPOST /jobs, built
Predicta model on one patchmilliseconds on a GPU, batchedLitServeexplained, not built

They differ in how long they take and what they wait on, so they should not share a design. Search and read answer inside the request. Run cannot. Predict needs hardware the others do not.

Long work is a job

client

API

worker

ten stages commit publish

POST /jobs

202 · job 35d3ee… · 7 ms7\ \mathrm{ms}

GET /jobs/{id}

200 · running

GET /jobs/{id}

200 · done · product id

GET /products/{id}

200 · the record

queue the run

job row: done

Measured: the POST answered in 7 ms; the job finished 247 ms after it was sent, 5 polls later. Sending the same POST again returned the same job with status 200, and started nothing.

@app.post("/jobs", status_code=202)
def start_job(
    request: RunRequest, http: fastapi.Request, response: fastapi.Response
) -> Job:
    """Accept a run and answer at once; the same request always gives the same job."""
    # job id = SHA-256(request ‖ recipe hash): a retry cannot start a second run
    payload = request.model_dump_json() + RECIPE_HASH
    job_id = hashlib.sha256(payload.encode()).hexdigest()[:12]
    with database() as db:
        # one statement decides who starts the job: a new id is inserted, a failed job
        # is queued again, anything else is left alone; concurrent retries cannot both win
        claimed = db.execute(
            "INSERT INTO jobs VALUES (?, 'queued', NULL) ON CONFLICT (id) DO UPDATE"
            " SET status = 'queued' WHERE jobs.status = 'failed'",
            (job_id,),
        )
        started = claimed.rowcount == 1
        row = db.execute("SELECT * FROM jobs WHERE id = ?", (job_id,)).fetchone()
    if not started:
        response.status_code = 200
        return job_from_row(row)
    # only the request that claimed the row queues the work
    http.app.state.workers.submit(run_recipe, job_id, request, http.app.state.catalog)
    return job_from_row(row)

@app.get("/jobs/{job_id}")
def get_job(job_id: str) -> Job:
    with database() as db:
        row = db.execute("SELECT * FROM jobs WHERE id = ?", (job_id,)).fetchone()
    if row is None:
        raise fastapi.HTTPException(status_code=404, detail="no such job")
    return job_from_row(row)

Three things make this safe. The response returns before the work starts, so no connection is held open. The job id is a hash of the request and the recipe (the idempotency key), and one INSERT … ON CONFLICT statement decides who starts the job: only the request whose statement changes a row queues the work, so a retry, or 12 copies sent at once, finds the existing job instead of starting another. Sent together here, the 12 got 1 × 202 and 11 × 200, one job id and one product. A check followed by an insert would let two of them through. A run that raises is recorded as failed, so a client that polls always gets an end state, and the same statement lets the next identical request queue it again (here: failed, then 202 on the retry). And the worker ends with commit and publish, so a finished job is an ordinary product record: nothing about the result lives in the web service.

The blocking trap, measured

20 requests at once, each a 200 ms200\ \mathrm{ms} blocking read

async def + blocking call

4.03 s4.03\ \mathrm{s}

async def + to_thread

0.82 s0.82\ \mathrm{s}

plain def

0.23 s0.23\ \mathrm{s}

…and how long a /health check sent during the burst had to wait

async def + blocking call

3981 ms3981\ \mathrm{ms}

async def + to_thread

3.0 ms3.0\ \mathrm{ms}

plain def

2.8 ms2.8\ \mathrm{ms}

Measured on the demo service. The first endpoint is not slow, it is serial: one blocking call holds the event loop, so 20 requests queue and an unrelated health check waits behind them all.

def read_window() -> dict[str, float]:
    """Stand-in for a 200 ms blocking read (GDAL, NumPy, a database driver)."""
    time.sleep(0.2)
    return {"mean": 0.41}

@app.get("/read/blocking")
async def read_blocking() -> dict[str, float]:
    # async def + a blocking call: the event loop stops for every client
    return read_window()

@app.get("/read/plain")
def read_plain() -> dict[str, float]:
    # plain def: FastAPI runs it on a worker thread
    return read_window()

@app.get("/read/offloaded")
async def read_offloaded() -> dict[str, float]:
    # async def that hands the blocking call to a thread
    return await asyncio.to_thread(read_window)

FastAPI runs on an event loop (see parallelism). An async def endpoint runs on that loop, so anything in it that blocks stops every other request. A plain def endpoint is run on a worker thread for you, which is why it is the fastest here. The middle bar is slower only because asyncio.to_thread uses a smaller pool (6 threads on this 2-core machine) than the one FastAPI uses for plain functions (40 by default).

Stateless services

The service holds nothing, so there can be many of it clients
API copy 1API copy 2API copy 3
product databaserecords, jobsIcechunkthe productsa queueruns waiting

Any copy can answer any request, because everything that must be remembered lives below the line. The demo cuts one corner: its worker is a thread inside the web process, so a restart loses queued runs. A real service puts the queue outside.

LitServe: FastAPI for models

Serving a model has needs a plain endpoint does not: the weights must load once and stay loaded, requests that arrive together should run as one batch, and work should spread over the GPUs or processes available. LitServe, from Lightning AI, is a server built on FastAPI that provides those. You write a class with two required parts, setup (run once per worker) and predict (run per request or per batch), and it supplies the endpoint, the batching queue, the workers and streaming. Its own page reports at least twice the throughput of plain FastAPI on its benchmarks.

import litserve as ls

# not pinned (litserve)
class PlumeDetector(ls.LitAPI):
    def setup(self, device):
        # once per worker: load the weights onto the device
        self.model = load_model(device)

    def predict(self, request):
        # per request, or per batch when batching is on
        patch = decode(request["patch"])              # → (band, h, w)
        return {"mask": encode(self.model(patch))}    # → (h, w)

# not pinned (litserve)
server = ls.LitServer(PlumeDetector(max_batch_size=16), accelerator="auto")
server.run(port=8000)

In your stack

An API is orchestration: it sits above the role ladder and runs recipes without changing them. Checked at geotoolz 640670c and pipekit 9e86a56.

PieceRole in a backendStatus
geocatalog from_stac_search, STACSourcethe upstream client: turns a provider’s STAC answer into a catalogships
GeoSlicethe request, once validated: bounds × time × resolution × CRSships
pipekit dumps, loads, loads_sandboxeda recipe as JSON in a request body, loaded safelyships
pipekit_ops.pipeline_hashhalf of the idempotency key, and the recipe’s id on the recordships
geocloud’s loop-aware coroutine runnerlets blocking handlers call async readersships
ProductCatalog, PostGISCatalogthe product database behind publishproposed · geotoolz#671, #672
PgstacCatalog, StacApiCatalog, sync_to_pgstacthe product catalog and the mirror into itproposed · #673, #674
stac-fastapi, TiTiler, LitServeready-made search, read and predict servicesoutside the stack; none is a dependency today

Left for later

Each of these matters in production and gets a line here: authentication (who is asking: API keys or tokens, checked before the function runs), rate limits (how much one client may ask), versioning (a /v1 prefix, so the shape of a response can change without breaking clients), a real queue for jobs, and deployment (containers, several copies, a load balancer).

Where this goes next

Idea hereShows up as
Product database and product catalogthe product catalog design: one record with three encodings (K), the adapters (F), the sync into pgstac (L)
A job ends in commit and publishstages 9 and 10 of the geo pipeline
The idempotency keyrecipe stamps and hashes (recipe registries, G); upserts (databases and catalogs)
Plain def against async defparallelism: the event loop and the thread pool