Skip to content

Request exceeded the maximum allowed time #240

Closed

Description

@Ahleroy

I have the following error with the python API :

pystac_client.exceptions.APIError: The request exceeded the maximum allowed time, please try again. If the issue persists, please contact planetarycomputer@microsoft.com.

Debug information for support: 20230716T154532Z-gdnzeuggn13zxf7nb0uwnmpz6c000000009000000001842g

Here is the subset of the code :

from pystac.extensions.eo import EOExtension as eo
import pystac_client
import planetary_computer
import time
import numpy as np
import rasterio
from rasterio import windows
from rasterio import features
from rasterio import warp
from PIL import Image

catalog = pystac_client.Client.open(
    "https://planetarycomputer.microsoft.com/api/stac/v1",
    modifier=planetary_computer.sign_inplace,
)

bounds = [-1.2867714015983258, 51.731613269987214,   -1.2148366398698462, 51.792129505211044]
lat1, lon1, lat2, lon2 = bounds

area_of_interest = {
    "type": "Polygon",
    "coordinates": [
        [
            [lat1, lon1],
            [lat2,lon1],
            [lat2, lon2],
            [lat1, lon2],
            [lat1, lon1],
        ]
    ],
}

date1 = "2022-09-01"
date2 = "2022-09-30"

time_of_interest = date1 + "/" + date2

t0 = time.time()
search = catalog.search(
    collections=["sentinel-2-l2a"],
    intersects=area_of_interest,
    datetime=time_of_interest,
)
t1 = time.time()
print(f"Search took {t1-t0} seconds")

items = search.item_collection()
print(f"Returned {len(items)} Items")

least_cloudy_item = min(items, key=lambda item: eo.ext(item).cloud_cover)

asset_href_visual = least_cloudy_item.assets["visual"].href
print(least_cloudy_item.id)

complete_asset = catalog.get_item(least_cloudy_item.id)

print("Start download")
t2 = time.time()
with rasterio.open(asset_href_visual) as ds:
    aoi_bounds = features.bounds(area_of_interest)
    warped_aoi_bounds = warp.transform_bounds("epsg:4326", ds.crs, *aoi_bounds)
    aoi_window = windows.from_bounds(transform=ds.transform, *warped_aoi_bounds)
    band_data_visual = ds.read(window=aoi_window)

print("End download")
img = Image.fromarray(np.transpose(band_data_visual, axes=[1, 2, 0]))
img.save("image_test.png")

Activity

  1. TomAugspurger commented on Jul 17, 2023

    @TomAugspurger

    Thanks for the report. Here's a slightly simpler reproducer:

    import time
    
    from pystac_client import Client
    
    
    catalog = Client.open(
        "https://planetarycomputer.microsoft.com/api/stac/v1",
    )
    
    
    def search():
        t0 = time.time()
        search = catalog.search(
            collections=["sentinel-2-l2a"],
            intersects={
                "type": "Point",
                "coordinates": [-1.28, 51.70],
            },
            datetime=["2022-09-01", "2022-09-30"],
        )
    
        items = search.item_collection()
        t1 = time.time()
        print(f"Search took {t1-t0} seconds")
        print(f"Returned {len(items)} Items")
    
    
    for i in range(100):
        search()

    We're looking into it and will post updates here.

  2. TomAugspurger commented on Jul 17, 2023

    @TomAugspurger

    One quick note: We do generally recommend adding retries to your HTTP requests.

    https://pystac-client.readthedocs.io/en/stable/usage.html#configuring-retry-behavior has documentation on how to do that with pystac-client (though that doesn't currently retry POST requests, which is what's failing. See stac-utils/pystac-client#561).

  3. mhelleis commented on Jul 17, 2023

    @mhelleis

    FYI I'm having the same problem (also using Sentinel-2 L2A data and intersects in combination with a Point). Most of the requests fail suddenly (but not all).

  4. ZirconCode commented on Jul 17, 2023

    @ZirconCode

    We have the same problem since today, never before. We do retry. Sentinel-2-L2A as well, and SAR. It seems to be working intermittently?

  5. ZirconCode commented on Jul 17, 2023

    @ZirconCode

    Seems to be working again, thanks Tom Augspurger (@TomAugspurger) and Matt McFarland (@mmcfarland) !

  6. TomAugspurger commented on Jul 17, 2023

    @TomAugspurger

    Matt McFarland (@mmcfarland) deployed a change that seems to have resolved things. We'll keep monitoring it, but do let us know if you continue to see these errors.

  7. KBodolai commented on May 8, 2024

    @KBodolai

    I've stumbled upon the same issue when trying to fetch some landsat time series:

    import pystac_client
    import planetary_computer
    
    client = pystac_client.Client.open( "https://planetarycomputer.microsoft.com/api/stac/v1", 
                                         modifier=planetary_computer.sign_inplace)
    search = client.search(collections='landsat-c2-l2', datetime='2014-01-01/2024-01-01', 
                               query = {'landsat:wrs_path': {'eq':166},
                                        'landsat:wrs_row': {'eq':68},
                                        'eo:cloud_cover': {'lte':20},
                                                        },)
    
    search.item_collection()

    Which gives the error below:

    Details
    ---------------------------------------------------------------------------
    APIError                                  Traceback (most recent call last)
    Cell In[29], line 11
          4 client = pystac_client.Client.open( "https://planetarycomputer.microsoft.com/api/stac/v1", modifier=planetary_computer.sign_inplace)
          5 search = client.search(collections='landsat-c2-l2', datetime='2014-01-01/2024-01-01', 
          6                            query = {'landsat:wrs_path': {'eq':166},
          7                                     'landsat:wrs_row': {'eq':68},
          8                                     'eo:cloud_cover': {'lte':20},
          9                                                     },)
    ---> 11 search.item_collection()
    
    File [/srv/conda/envs/notebook/lib/python3.11/site-packages/pystac_client/item_search.py:764](https://pccompute.westeurope.cloudapp.azure.com/srv/conda/envs/notebook/lib/python3.11/site-packages/pystac_client/item_search.py#line=763), in ItemSearch.item_collection(self)
        756 """
        757 Get the matching items as a :py:class:`pystac.ItemCollection`.
        758 
        759 Return:
        760     ItemCollection: The item collection
        761 """
        762 # Bypass the cache here, so that we can pass __preserve_dict__
        763 # without mutating what's in the cache.
    --> 764 feature_collection = self.item_collection_as_dict.__wrapped__(self)
        765 # already signed in item_collection_as_dict
        766 return ItemCollection.from_dict(
        767     feature_collection, preserve_dict=False, root=self.client
        768 )
    
    File [/srv/conda/envs/notebook/lib/python3.11/site-packages/pystac_client/item_search.py:785](https://pccompute.westeurope.cloudapp.azure.com/srv/conda/envs/notebook/lib/python3.11/site-packages/pystac_client/item_search.py#line=784), in ItemSearch.item_collection_as_dict(self)
        772 """
        773 Get the matching items as an item-collection-like dict.
        774 
       (...)
        782     Dict : A GeoJSON FeatureCollection
        783 """
        784 features = []
    --> 785 for page in self.pages_as_dicts():
        786     for feature in page["features"]:
        787         features.append(feature)
    
    File [/srv/conda/envs/notebook/lib/python3.11/site-packages/pystac_client/item_search.py:735](https://pccompute.westeurope.cloudapp.azure.com/srv/conda/envs/notebook/lib/python3.11/site-packages/pystac_client/item_search.py#line=734), in ItemSearch.pages_as_dicts(self)
        733 if isinstance(self._stac_io, StacApiIO):
        734     num_items = 0
    --> 735     for page in self._stac_io.get_pages(
        736         self.url, self.method, self.get_parameters()
        737     ):
        738         call_modifier(self.modifier, page)
        739         features = page.get("features", [])
    
    File [/srv/conda/envs/notebook/lib/python3.11/site-packages/pystac_client/stac_api_io.py:294](https://pccompute.westeurope.cloudapp.azure.com/srv/conda/envs/notebook/lib/python3.11/site-packages/pystac_client/stac_api_io.py#line=293), in StacApiIO.get_pages(self, url, method, parameters)
        282 def get_pages(
        283     self,
        284     url: str,
        285     method: Optional[str] = None,
        286     parameters: Optional[Dict[str, Any]] = None,
        287 ) -> Iterator[Dict[str, Any]]:
        288     """Iterator that yields dictionaries for each page at a STAC paging
        289     endpoint, e.g., [/collections](https://pccompute.westeurope.cloudapp.azure.com/collections), [/search](https://pccompute.westeurope.cloudapp.azure.com/search)
        290 
        291     Return:
        292         Dict[str, Any] : JSON content from a single page
        293     """
    --> 294     page = self.read_json(url, method=method, parameters=parameters)
        295     if not (page.get("features") or page.get("collections")):
        296         return None
    
    File [/srv/conda/envs/notebook/lib/python3.11/site-packages/pystac/stac_io.py:205](https://pccompute.westeurope.cloudapp.azure.com/srv/conda/envs/notebook/lib/python3.11/site-packages/pystac/stac_io.py#line=204), in StacIO.read_json(self, source, *args, **kwargs)
        188 def read_json(self, source: HREF, *args: Any, **kwargs: Any) -> dict[str, Any]:
        189     """Read a dict from the given source.
        190 
        191     See :func:`StacIO.read_text <pystac.StacIO.read_text>` for usage of
       (...)
        203         given source.
        204     """
    --> 205     txt = self.read_text(source, *args, **kwargs)
        206     return self.json_loads(txt)
    
    File [/srv/conda/envs/notebook/lib/python3.11/site-packages/pystac_client/stac_api_io.py:168](https://pccompute.westeurope.cloudapp.azure.com/srv/conda/envs/notebook/lib/python3.11/site-packages/pystac_client/stac_api_io.py#line=167), in StacApiIO.read_text(self, source, *args, **kwargs)
        166 href = str(source)
        167 if _is_url(href):
    --> 168     return self.request(href, *args, **kwargs)
        169 else:
        170     with open(href) as f:
    
    File [/srv/conda/envs/notebook/lib/python3.11/site-packages/pystac_client/stac_api_io.py:217](https://pccompute.westeurope.cloudapp.azure.com/srv/conda/envs/notebook/lib/python3.11/site-packages/pystac_client/stac_api_io.py#line=216), in StacApiIO.request(self, href, method, headers, parameters)
        215     raise APIError(str(err))
        216 if resp.status_code != 200:
    --> 217     raise APIError.from_response(resp)
        218 try:
        219     return resp.content.decode("utf-8")
    
    APIError: The request exceeded the maximum allowed time, please try again. If the issue persists, please contact planetarycomputer@microsoft.com.
    
    Debug information for support: 20240508T150210Z-ier1cf88fd6qd4qwkx5psugpwg00000002vg00000000sace

    The error goes away if I try some other paths/rows (e.g. changing the path to 168) or if I do a much shorter time period (e.g. 2023-01-01/2024-01-01).

  8. TomAugspurger commented on May 8, 2024

    @TomAugspurger

    A couple quick notes:

    1. Using landsat:wrs_path and landsat:wrs_row as a query condition is helpful, but not enough. We need to add an index on those in the database, which should speed things up a lot (Antimeridian-crossing Items and Searching For Them #296).
    2. As you say, a shorter time period helps, because we have to scan less data. You might be able to make multiple queries (each of which completes within 30s) and then concatenate them together later.
    3. The bulk item access documented in https://planetarycomputer.microsoft.com/docs/quickstarts/stac-geoparquet/ might work for you, if you're expecting to get back many items.
  9. KBodolai commented on May 17, 2024

    @KBodolai

    Thanks Tom, very informative as always!

    I used to have a spatial search with a bounding box in that snippet that failed as well, very interesting about your first point!

    I hadn't come across the bulk item access, I'll play around with that now :)

  10. Ethan-Chen421 commented on Oct 18, 2024

    @Ethan-Chen421

    @mmcfarland部署了一个似乎已解决问题的变更。我们会继续监控,但如果您继续看到这些错误,请告诉我们。

    @mmcfarland部署了一个似乎已解决问题的变更。我们会继续监控,但如果您继续看到这些错误,请告诉我们。

    @mmcfarland deployed a change that seems to have resolved things. We'll keep monitoring it, but do let us know if you continue to see these errors.

    import json
    import pystac_client
    import planetary_computer
    from pystac_client import Client, Modifiable
    from django.views.decorators.csrf import csrf_exempt
    from django.views.decorators.http import require_POST
    from django.http import JsonResponse
    from urllib.parse import urlparse
    @csrf_exempt # 使得视图可以跳过CSRF验证,对于接收外部API请求时有用
    @require_POST
    def search_NDVI(request):
    if request.method == 'POST':
    start_date = request.POST.get('start_date')
    end_date = request.POST.get('end_date')
    cloud_cover = request.POST.get('cloud_cover')
    time_of_interest = f'{start_date}/{end_date}'
    geojson_str = request.POST.get('geojson')

        if not geojson_str or not start_date or not end_date:
            return JsonResponse({'error': '边界无效或者没有填写开始和结束日期'}, status=400)
    
        try:
            geojson = json.loads(geojson_str)
        except json.JSONDecodeError:
            return JsonResponse({'error': '无效的geojson格式'}, status=400)
    
        # 获取 GeoJSON 文件中的第一个 Feature 的几何对象
        if 'features' not in geojson or not geojson['features']:
            return JsonResponse({'error': 'GeoJSON不包含有效的features'}, status=400)
    
        area_of_interest = geojson['features'][0]['geometry']
    
        # 打开 Planetary Computer 的 STAC 客户端
        catalog = pystac_client.Client.open(
            "https://planetarycomputer.microsoft.com/api/stac/v1",
            modifier=planetary_computer.sign_inplace,
        )  # pystac_client.
    
    
        # 搜索符合条件的数据集合
        search = catalog.search(
            collections=["sentinel-2-l2a"],
            intersects=area_of_interest,
            datetime=time_of_interest,
            query={"eo:cloud_cover": {"lt": cloud_cover}},
        )
    
        # 获取所有影像的信息
        items = list(search.get_items())
        if not items:
            return JsonResponse({'message': '没有找到符合条件的影像数据'}, status=200)
    
        # 收集所有影像的产品参数、拍摄日期和云量信息
        item_details = []
        for item in items:
            # 获取 Item 的链接
            item_link = item.assets["visual"].href
    
            # 从链接中解析文件名
            parsed_url = urlparse(item_link)
            filename = parsed_url.path.split('/')[-1]
            filename_without_ext = filename.split('.')[0]
    
            # 从 Item 属性中获取云量信息
            cloud_cover = item.properties['eo:cloud_cover']
    
            # 添加格式化信息到列表
            item_details.append({
                'Image ID':item.id, #影像ID,唯一标识符
                'Product parameters': filename_without_ext, #产品信息
                'Shooting date': str(item.datetime.date()), #拍摄日期
                'Cloud cover': cloud_cover, #云量
            })
    
    
        return JsonResponse({'message': 'successful', 'Data information': item_details})
    
    # 如果不是POST请求,返回错误
    return JsonResponse({'error': '只接受POST请求'}, status=405)
    

    @mmcfarland deployed a change that seems to have resolved things. We'll keep monitoring it, but do let us know if you continue to see these errors.

    import json
    import pystac_client
    import planetary_computer
    from pystac_client import Client, Modifiable
    from django.views.decorators.csrf import csrf_exempt
    from django.views.decorators.http import require_POST
    from django.http import JsonResponse
    from urllib.parse import urlparse
    @csrf_exempt
    @require_POST
    def search_NDVI(request):
    if request.method == 'POST':
    start_date = request.POST.get('start_date')
    end_date = request.POST.get('end_date')
    cloud_cover = request.POST.get('cloud_cover')
    time_of_interest = f'{start_date}/{end_date}'
    geojson_str = request.POST.get('geojson')

        if not geojson_str or not start_date or not end_date:
            return JsonResponse(status=400)
    
        try:
            geojson = json.loads(geojson_str)
        except json.JSONDecodeError:
            return JsonResponse({'error': 'geosonerror'}, status=400)
    
        
        if 'features' not in geojson or not geojson['features']:
            return JsonResponse({'error': 'GeoJSONerror'}, status=400)
    
        area_of_interest = geojson['features'][0]['geometry']
    
        catalog = pystac_client.Client.open(
            "https://planetarycomputer.microsoft.com/api/stac/v1",
            modifier=planetary_computer.sign_inplace,
        )  
    
        search = catalog.search(
            collections=["sentinel-2-l2a"],
            intersects=area_of_interest,
            datetime=time_of_interest,
            query={"eo:cloud_cover": {"lt": cloud_cover}},
        )
    
        items = list(search.get_items())
        if not items:
            return JsonResponse({'message': 'no image'}, status=200)
    
        item_details = []
        for item in items:
    
            item_link = item.assets["visual"].href
    
            parsed_url = urlparse(item_link)
            filename = parsed_url.path.split('/')[-1]
            filename_without_ext = filename.split('.')[0]
    
            cloud_cover = item.properties['eo:cloud_cover']
    
            item_details.append({
                'Image ID':item.id, 
                'Product parameters': filename_without_ext, 
                'Shooting date': str(item.datetime.date()), 
                'Cloud cover': cloud_cover, 
            })
    
    
        return JsonResponse({'message': 'successful', 'Data information': item_details})
    
    return JsonResponse({'error': 'POST'}, status=405)
    

    I also encountered the same problem when I integrated the functionality into Django

    Wrong content:pystac_client.exceptions.apierror: the request exceeded the maximum allowed time, please try again. if the issue persists, please contact planetarycomputer@microsoft.com.

  11. Pistonamey commented on Jan 23, 2026

    @Pistonamey

    Getting the same issue for:
    def load_terraclimate_dataset():
    """
    Load TerraClimate dataset from Microsoft Planetary Computer.
    """
    catalog = pystac_client.Client.open(
    "https://planetarycomputer.microsoft.com/api/stac/v1",
    modifier=pc.sign_inplace,
    )
    collection = catalog.get_collection("terraclimate")
    asset = collection.assets["zarr-abfs"]

    if "xarray:storage_options" in asset.extra_fields:
        ds = xr.open_zarr(
            asset.href,
            storage_options=asset.extra_fields["xarray:storage_options"],
            consolidated=True,
        )
    else:
        ds = xr.open_dataset(
            asset.href,
            **asset.extra_fields["xarray:open_kwargs"],
        )
    
    return ds
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions