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¶
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.
| Request | Means | Safe to repeat? | In the demo |
|---|---|---|---|
GET /products?bbox=…&start=… | list the products that match | yes: reads change nothing | 2.3 ms |
GET /products/{id} | one product’s record | yes | 200, or 404 |
POST /jobs | create a run | only if you make it so | 202, then 200 for the same request |
GET /jobs/{id} | how is the run going | yes | queued → running → done |
PUT, DELETE | replace, remove | yes by definition | not used |
| Status | Says |
|---|---|
| 200 OK | here is what you asked for |
| 202 Accepted | I have taken the request; the work is not done yet |
| 404 Not Found | no such resource |
| 422 Unprocessable | the request is well-formed but its contents are wrong (FastAPI’s validation answer) |
| 5xx | the 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 write commit 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 STAC | Product database | Product catalog | |
|---|---|---|---|
| What it lists | a provider’s scenes (Sentinel-2, Landsat, EMIT) | what our pipelines produced | the same products, as STAC |
| Who owns it | the provider | us | us |
| Who writes it | the provider | the pipeline’s publish stage, and nothing else | a sync from the product database |
| Shape | STAC items | our own table: the core fields plus whatever we need (recipe, snapshot, quality flags, job) | STAC items: the core fields under agreed names |
| We are | a client | the only writer | the server |
| Reached by | pystac-client, geocatalog’s from_stac_search | SQL, from our services | a STAC API (stac-fastapi over pgstac), by anyone we allow |
| Pipeline stage | 1 · search | 10 · publish | after publish |
| Status in the stack | ships | proposed (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 start_job FastAPI, from the type hints
parse JSON text Python values FastAPI, from the type hints
validate values RunRequest, or 422 FastAPI, from the type hints
your function start_job(request) Job you write this
serialise Job JSON text FastAPI, from the type hints
document all of it /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¶
| Kind | Does | Takes | Ready-made | On this page |
|---|---|---|---|---|
| Search | which products match a place and time | milliseconds | stac-fastapi over pgstac | GET /products, built small |
| Read | pixels for a window or a map tile | tens of milliseconds, mostly waiting on storage | TiTiler | named, not built |
| Run | start a pipeline | seconds to hours | none: this is yours | POST /jobs, built |
| Predict | a model on one patch | milliseconds on a GPU, batched | LitServe | explained, 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… ·
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¶
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¶
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.
| Piece | Role in a backend | Status |
|---|---|---|
geocatalog from_stac_search, STACSource | the upstream client: turns a provider’s STAC answer into a catalog | ships |
GeoSlice | the request, once validated: bounds × time × resolution × CRS | ships |
pipekit dumps, loads, loads_sandboxed | a recipe as JSON in a request body, loaded safely | ships |
pipekit_ops.pipeline_hash | half of the idempotency key, and the recipe’s id on the record | ships |
| geocloud’s loop-aware coroutine runner | lets blocking handlers call async readers | ships |
ProductCatalog, PostGISCatalog | the product database behind publish | proposed · geotoolz#671, #672 |
PgstacCatalog, StacApiCatalog, sync_to_pgstac | the product catalog and the mirror into it | proposed · #673, #674 |
| stac-fastapi, TiTiler, LitServe | ready-made search, read and predict services | outside 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 here | Shows up as |
|---|---|
| Product database and product catalog | the product catalog design: one record with three encodings (K), the adapters (F), the sync into pgstac (L) |
| A job ends in commit and publish | stages 9 and 10 of the geo pipeline |
| The idempotency key | recipe stamps and hashes (recipe registries, G); upserts (databases and catalogs) |
| Plain def against async def | parallelism: the event loop and the thread pool |
Sources and status
Sources: the FastAPI documentation; LitServe’s repository page (read 13 November 2026) for its quick-start, feature list and throughput claim; the STAC specification, and the stac-fastapi, pgstac and TiTiler projects as I know them, not re-checked online for this page. The service is notebooks/background/backends_service.py (304 lines) and the client that measures it is notebooks/background/backends.py; the recorded output is docs/images/background_backends/results.json. It was run as shown with FastAPI 0.162, uvicorn 0.54 and pydantic 2.13 over geotoolz at 640670c, on one 2-core machine; SQLite stands in for the product database, the job worker is a thread in the web process, and the 200 ms read is an injected delay. The Earth Search address in the client sketch is illustrative and was not called.