How-To

Python Requests: Set Timeouts and Bound Retries

Python Requests needs an explicit timeout if a job shouldn't wait indefinitely. A retry policy is a separate choice: decide which failures are safe to repeat and how many additional requests the service permits.

Set a timeout for each request

Requests accepts connect and read timeouts. Its timeout guidance explains that these aren't a total wall-clock deadline for the entire operation. Set values appropriate to the service, and add an outer job deadline where the workflow requires one. Handle timeout exceptions as failures your caller can see.

Choose retry conditions deliberately

A Session can mount an HTTPAdapter configured with urllib3's Retry object. The Requests example and urllib3 reference describe the configuration. Check your installed versions before copying an example: options and defaults can vary.

Set a bounded total and consider which methods and status codes your application can repeat safely. A failed connection and an HTTP error aren't the same event. Repeating a request after an ambiguous write failure may duplicate a side effect, so only retry writes under the service's documented idempotency rules. Do not retry a 403 or a challenge to evade access restrictions.

Respect the service's budget

A retry is another request. Account for it when a provider sets a per-minute or daily allowance, and honor Retry-After where applicable. Add an upper bound on waits and an overall deadline so a job doesn't remain stuck indefinitely. Consult the 403 and 429 guide for the distinction between denial and throttling.

Test a retry policy against an owned fixture that returns the failure and recovery sequence you expect. Count requests and verify the final result rather than judging success from a log line. This article describes the configuration choices; it doesn't claim a policy has been tested against your provider.

Example: retry selected read requests

from requests import Session
from requests.adapters import HTTPAdapter
from urllib3.util import Retry

retry = Retry(total=2, backoff_factor=0.5,
              status_forcelist=[429, 502, 503, 504],
              allowed_methods={"GET", "HEAD"},
              respect_retry_after_header=True)
with Session() as session:
    session.mount("https://", HTTPAdapter(max_retries=retry))
    response = session.get("https://example.com/data", timeout=(3.05, 10))
    response.raise_for_status()

The endpoint and values are illustrative. This policy permits up to two retries, restricts status retries to the listed read methods, and uses separate connect and read timeouts. It does not impose an overall wall-clock deadline or cover HTTP URLs with the HTTPS mount. Test the failure sequence with a local server and adapt the provider’s documented rate limits before use.

If you need help planning an authorized automation workflow, ask for a scoped assessment. Share the documented limits and a redacted example, without credentials or private data.