Skip to content
TheChatArchiveThe Chat Archive
GPT 5.1 Codex Max· openaiHugging Face Frontier Reasoning Traces

Implement a Python script for calling an unstable API with exponential backoff and…

  1. User

    Implement a Python script for calling an unstable API with exponential backoff and jitter. On 429 or 503 responses, wait base * 2^retries + random_ms, stop after 5 retries, and raise a custom MaxRetriesExceeded exception that preserves the original error context.

  2. Assistant

    Implementing Python retry script

    The script defines a MaxRetriesExceeded exception preserving the original error context, calls an unstable API with exponential backoff plus random millisecond jitter on 429/503 responses, retries up to 5 times, and raises the custom exception if exhausted.

    import time
    import random
    import requests
    
    class MaxRetriesExceeded(Exception):
        """Custom exception raised when maximum retries are exceeded."""
    
        def __init__(self, message, original_exception=None):
            super().__init__(message)
            # Keep a reference to the original exception
            self.original_exception = original_exception
            # Preserve original context for tracebacks
            if original_exception is not None:
                self.__cause__ = original_exception
    
    
    def call_unstable_api(
        url: str,
        base_delay_ms: int = 500,  # base in milliseconds
        max_retries: int = 5,
        timeout: int = 5,
    ):
        """
        Call an unstable API endpoint with exponential backoff and jitter.
    
        On 429 or 503, wait (base * 2^retries + random_ms) milliseconds before retrying.
        Raises MaxRetriesExceeded after max_retries attempts, preserving original context.
        """
        last_error = None
    
        for attempt in range(max_retries + 1):
            try:
                response = requests.get(url, timeout=timeout)
    
                # If we got a retry-able HTTP code, force an exception to trigger retry
                if response.status_code in (429, 503):
                    raise requests.exceptions.HTTPError(
                        f"Retryable status {response.status_code}", response=response
                    )
    
                # Raise for any other HTTP errors
                response.raise_for_status()
                return response.json()  # or response.text, etc. as needed
    
            except requests.exceptions.HTTPError as http_err:
                last_error = http_err
    
                # Retry only if status code is in (429, 503)
                resp = getattr(http_err, "response", None)
                status = getattr(resp, "status_code", None)
                if status not in (429, 503):
                    # Non-retryable HTTP error, re-raise immediately
                    raise
    
                # If we've exhausted retries, break and raise later
                if attempt == max_retries:
                    break
    
                # Exponential backoff with jitter
                jitter_ms = random.randint(0, 1000)  # 0–1000 ms jitter
                sleep_seconds = (base_delay_ms * (2 ** attempt) + jitter_ms) / 1000.0
                time.sleep(sleep_seconds)
    
            except Exception as err:
                # Any other transient error: retry until we exhaust attempts
                last_error = err
                if attempt == max_retries:
                    break
                jitter_ms = random.randint(0, 1000)
                sleep_seconds = (base_delay_ms * (2 ** attempt) + jitter_ms) / 1000.0
                time.sleep(sleep_seconds)
    
        # If we get here, retries are exhausted
        raise MaxRetriesExceeded(
            f"Failed after {max_retries} retries", original_exception=last_error
        )
    
    
    if __name__ == "__main__":
        # Example usage
        api_url = "https://example.com/unstable-endpoint"
        try:
            result = call_unstable_api(api_url)
            print("Success:", result)
        except MaxRetriesExceeded as e:
            print("Max retries exceeded.")
            if e.original_exception:
                print("Original error:", e.original_exception)
            # Handle or log as needed
    

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.