Granule searches send more CMR requests than they need

Open
#331 0 comments 0 reactions 0 assignees View on GitHub

Maintainers usually reply within 1 day

Nobody has claimed this yet.

Assessment

Difficulty
3/5
Estimated time
1-2 days
Newbie friendliness
68/100
Issue type
Refactor
Clarity
Clearly specified
Activity status
Active
Tech stack
python
Domain
backend

Research direction

Start in get_granules in titiler/cmr/query.py: the page size is set to 20 near line 197, and the loop after it follows CMR-Search-After until a response lacks that header. Change the first page to 100, size later pages to the remaining limit (max 2,000), and stop once the count reaches the CMR-Hits header. The benchmark script in the issue, search_requests.py, reproduces the request counts. Done when its request lists match the proposed column, and the exitwhenfull coverage behavior still passes the existing tests.

Written by the indexing model from the issue text.

Description

A granule search sends CMR more requests than it needs, one after another, so titiler-cmr waits on CMR longer than it has to before it reads any data. A search for the 83 ESI granules in a box over Texas on 2023-10-02 sends 6 requests and takes 2.2s, and the search proposed here sends 1 request and takes 0.5s.

Before titiler-cmr reads data, it asks CMR for the granules in the request's area and time range. Every endpoint that reads granules searches this way: tiles, /statistics, /bbox, /point, and each step of the timeseries endpoints. CMR returns up to page_size granules per request, and each request after the first needs the CMR-Search-After header of the response before it, so the requests run one after another (query.py). get_granules sends more of them than it needs in two ways:

  • It asks for 20 granules per request (query.py). A search that uses 83 granules sends 5 requests for them, and one that uses 446 sends 23. Searches over busy areas use that many, and so do requests that set a large items_limit so that a read covers every granule in its area.
  • It sends one more request after the last granule. CMR includes CMR-Search-After in the last page of results too, and get_granules stops only when a response does not include it, so a search that reads every granule it finds ends with a request that returns none. A tile whose granules do not cover it ends this way: tile 7/29/53 finds 11 ESI granules on 2024-07-01 and sends 2 requests.

Proposal: get_granules will stop once it has as many granules as CMR reports in the CMR-Hits header. Its first request will ask for up to 100 granules, the default limit, and each request after that will ask for all the granules left under its limit, up to CMR's maximum of 2,000 per request. A search with the default limit will send one request, and a search with a larger items_limit will send one more request for each 2,000 granules after its first 100. CMR returns only the granules that match, so the larger requests cost extra only when a search stops before it reaches the last granule that CMR matched, as exitwhenfull does once the granules cover the area. Such a search can fetch the records of granules that it does not use, up to its items_limit. Issue #330 asks for larger items_limit values, and this keeps those searches to a few requests.

Searches timed on 2026-11-25 with the script below, one run each. CMR's speed varies from run to run, so the request counts are the steadier comparison. Each list gives the granules that each CMR request returned. The Texas box is -106.65,25.84,-93.51,36.5, and the contiguous US is -125,24.5,-66.9,49.4.

Search Today Proposed
ESI, Texas box, 2023-10-02 6 requests [20, 20, 20, 20, 3, 0], 2.2s 1 request [83], 0.5s
ESI, tile 7/29/53, 2024-07-01 2 requests [11, 0], 0.9s 1 request [11], 0.7s
HLSL30, tile 7/29/53, 2024-07-01 to 2024-07-30 6 requests [20, 20, 20, 20, 9, 0], 3.2s 1 request [89], 0.6s
ESI, contiguous US, 2024-07-01, items_limit=1000 11 requests, 7.2s 2 requests [100, 93], 2.4s
ESI, contiguous US, 2024-07-31, items_limit=1000 24 requests, 14.1s 2 requests [100, 346], 2.6s
ESI, contiguous US, July 2024, items_limit=2000 100 requests, 60.2s 2 requests [100, 1900], 18.2s
Script behind the table

Save it as search_requests.py and run uv run python search_requests.py from the repository root.

"""Compare get_granules with a search that asks for 100, then the rest, and stops at CMR-Hits.

Both run with exitwhenfull and the rasterio backend's coverage tolerance, as
a tile or statistics read does, and print the granules that each CMR request
returned. Run from the repository root: uv run python search_requests.py
"""

import time

import httpx
import morecantile
import shapely
from geojson_pydantic import Polygon

from titiler.cmr.models import GranuleSearch
from titiler.cmr.query import (
    CMR_GRANULE_SEARCH_API,
    GranuleSearchResponse,
    _build_granule_params,
    _is_fully_covered,
    _parse_cmr_response,
    _send_cmr_search,
    get_granules,
)

ESI = "C2076104650-LPCLOUD"
HLSL30 = "C2021957657-LPCLOUD"
TEXAS = (-106.65, 25.84, -93.51, 36.5)
CONUS = (-125, 24.5, -66.9, 49.4)
TILE = tuple(morecantile.tms.get("WebMercatorQuad").bounds(morecantile.Tile(29, 53, 7)))
CASES = [
    ("ESI, Texas box, 2023-10-02", ESI, TEXAS, "2023-10-02", "2023-10-02", 100),
    ("ESI, tile 7/29/53, 2024-07-01", ESI, TILE, "2024-07-01", "2024-07-01", 100),
    ("HLSL30, tile 7/29/53, 2024-07-01 to 07-30", HLSL30, TILE, "2024-07-01", "2024-07-30", 100),
    ("ESI, CONUS, 2024-07-01, limit 1000", ESI, CONUS, "2024-07-01", "2024-07-01", 1000),
    ("ESI, CONUS, 2024-07-31, limit 1000", ESI, CONUS, "2024-07-31", "2024-07-31", 1000),
    ("ESI, CONUS, July 2024, limit 2000", ESI, CONUS, "2024-07-01", "2024-07-31", 2000),
]


def today(client, search, geometry, limit):
    """Run get_granules as titiler-cmr does."""
    sizes = []
    client.event_hooks["response"] = [lambda r: (r.read(), sizes.append(len(r.json()["items"])))]
    t0 = time.monotonic()
    used = sum(
        1
        for _ in get_granules(
            search, client, geometry=geometry, limit=limit, exitwhenfull=True, coverage_tolerance=1e-2
        )
    )
    client.event_hooks["response"] = []
    return used, sizes, time.monotonic() - t0


def proposed(client, search, geometry, limit):
    """Run get_granules with only its page sizes and its stopping rule changed."""
    sizes, used, t0 = [], 0, time.monotonic()
    params = _build_granule_params(search, geometry, min(100, limit))
    shape = shapely.geometry.shape(geometry.model_dump())
    covered, headers = shapely.GeometryCollection(), {}
    while used < limit:
        request = client.build_request("GET", "granules.umm_json", params=params, headers=headers)
        response = _send_cmr_search(client, request)
        items = _parse_cmr_response(response, GranuleSearchResponse).items
        sizes.append(len(items))
        for granule in items:
            used += 1
            done, covered = _is_fully_covered(granule, shape, covered, 1e-2)
            if used >= limit or done:
                return used, sizes, time.monotonic() - t0
        if used >= int(response.headers["cmr-hits"]):
            break
        headers["cmr-search-after"] = response.headers["cmr-search-after"]
        params["page_size"] = min(limit - used, 2000)
    return used, sizes, time.monotonic() - t0


if __name__ == "__main__":
    with httpx.Client(base_url=CMR_GRANULE_SEARCH_API, timeout=60) as client:
        for label, cid, bounds, start, end, limit in CASES:
            search = GranuleSearch(collection_concept_id=cid, temporal=f"{start}T00:00:00Z/{end}T23:59:59Z")
            geometry = Polygon.from_bounds(*bounds)
            for name, fn in (("today", today), ("proposed", proposed)):
                used, sizes, seconds = fn(client, search, geometry, limit)
                print(f"{label} | {name}: {used} granules, {len(sizes)} requests {sizes}, {seconds:.1f}s")
ESI, Texas box, 2023-10-02 | today: 83 granules, 6 requests [20, 20, 20, 20, 3, 0], 2.2s
ESI, Texas box, 2023-10-02 | proposed: 83 granules, 1 requests [83], 0.5s
ESI, tile 7/29/53, 2024-07-01 | today: 11 granules, 2 requests [11, 0], 0.9s
ESI, tile 7/29/53, 2024-07-01 | proposed: 11 granules, 1 requests [11], 0.7s
HLSL30, tile 7/29/53, 2024-07-01 to 07-30 | today: 89 granules, 6 requests [20, 20, 20, 20, 9, 0], 3.2s
HLSL30, tile 7/29/53, 2024-07-01 to 07-30 | proposed: 89 granules, 1 requests [89], 0.6s
ESI, CONUS, 2024-07-01, limit 1000 | today: 193 granules, 11 requests [20, 20, 20, 20, 20, 20, 20, 20, 20, 13, 0], 7.2s
ESI, CONUS, 2024-07-01, limit 1000 | proposed: 193 granules, 2 requests [100, 93], 2.4s
ESI, CONUS, 2024-07-31, limit 1000 | today: 446 granules, 24 requests [20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 6, 0], 14.1s
ESI, CONUS, 2024-07-31, limit 1000 | proposed: 446 granules, 2 requests [100, 346], 2.6s
ESI, CONUS, July 2024, limit 2000 | today: 2000 granules, 100 requests [20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20], 60.2s
ESI, CONUS, July 2024, limit 2000 | proposed: 2000 granules, 2 requests [100, 1900], 18.2s
Dominant language
Python
Stars
26
Forks
12
Avg merge
1d 45m
Merged PRs (30d)
28

Getting set up

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from developmentseed/titiler-cmr

All issues in developmentseed/titiler-cmr

Similar issues

More Python issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.