google-api-python-client icon indicating copy to clipboard operation
google-api-python-client copied to clipboard

HTTP 400 / preconditionFailed should be retried

Open ttung opened this issue 9 months ago • 1 comments

Environment details

  • OS type and version: MacOS 26
  • Python version: Python 3.12.11
  • pip version: uv
  • google-api-python-client version: n/a

Steps to reproduce

Intermittent HTTP 400 / preconditionFailed on Gmail API. A casual web search suggests that other Google APIs also issue preconditionFailed. At least in my use case, retrying with exponential backoff always works. I cannot assert that in all use cases that this is the correct behavior.

Code example

N/A

Stack trace

ttung avatar Feb 28 '26 18:02 ttung

Image

I have investigated and implemented a fix for this issue.

Root Cause: The _should_retry_response function in googleapiclient/http.py relied on HTTP response codes to trigger retries but previously only parsed the JSON error details for 403 Forbidden statuses (specifically looking for userRateLimitExceeded and rateLimitExceeded). It did not extend this logic to 400 Bad Request errors.

Solution: I updated _should_retry_response to parse the JSON content for both 403 and 400 status codes. If the API returns a 400 Bad Request, the client will examine the JSON error response block, and if the "reason" is either "failedPrecondition" or "preconditionFailed", the response is now flagged to be retried with exponential backoff.

Changes made:

  • googleapiclient/http.py: Refactored the JSON parsing block in _should_retry_response to apply to http_client.BAD_REQUEST as well. Added a condition to return True for retrying when encountering a failedPrecondition reason.
  • tests/test_http.py: Added a test_retry_400_failed_precondition mock test to verify the client correctly enters the sleep/retry loop rather than failing fast when a 400 preconditions error is received.

It handles the issue perfectly using the project's existing error-parsing conventions. Let me know if you need anything else!

codeXsidd avatar Mar 21 '26 04:03 codeXsidd