Skip to content

How do I implement retry logic and exponential backoff best practices for Amazon Bedrock API calls?

6 minute read
2

I want to implement retry logic and exponential backoff best practices in Amazon Bedrock API operations to handle throttling errors, service unavailability, and transient failures.

Short description

When you make API operations to Amazon Bedrock, you might encounter the following errors:

  • "ThrottlingException: The request was denied because you exceeded your Amazon Bedrock account quotas"
  • "ServiceUnavailableException: The service temporarily can't handle the request"
  • "InternalFailure - The request failed to process because of a server error"
  • Network timeouts or connection errors.

To resolve the preceding errors and improve application reliability, implement retry logic with exponential backoff.

Resolution

Implement retry logic and exponential backoff best practices

Implement the following best practices for retry logic and exponential backoff:

  • Use retry logic and exponential backoff for transient errors, such as "ThrottlingException", "ModelTimeoutException", "ServiceUnavailableException", "InternalServerException", and network-related errors.
  • Don't use retry logic and exponential backoff for client errors, such as "ValidationException" and "AccessDeniedException".
  • Use exponential backoff to reduce your service load and increase request success. For more information, see Retry with backoff pattern.
  • Add jitter to your logic so that multiple clients don't simultaneously retry and overwhelm the service. For more information, see Exponential backoff and jitter.

Note: AWS SDKs include built-in retry logic with exponential backoff, but you might need to customize the configuration based on your use case.

Configure AWS SDK retry behavior

To configure the retry mode when you create your Amazon Bedrock client, use the Config object from the botocore.config file:

import boto3
from botocore.config import Config

# Configure retry settings
retry_config = Config(
    retries={
        'max_attempts': 10,
        'mode': 'standard'  # Options: 'legacy', 'standard', 'adaptive'
    }
)

# Create Bedrock client with retry configuration
bedrock_runtime = boto3.client(
    'bedrock-runtime',
    config=retry_config,
    region_name='us-east-1'
)

Note: Replace us-east-1 with your AWS Region and standard with the retry mode that you want to configure. For information about retry modes, see Retry behavior.

Implement custom retry logic with exponential backoff and jitter

To implement custom retry logic with exponential backoff and jitter, complete the following steps:

  1. Use the following code to create a custom retry decorator function:

    import time
    import random
    from functools import wraps
    from botocore.exceptions import ClientError
    
    def retry_with_exponential_backoff(
        max_retries=5,
        base_delay=1,
        max_delay=60,
        exponential_base=2,
        jitter=True
    ):
        """
        Decorator for retrying function calls with exponential backoff.
        """
        def decorator(func):
            @wraps(func)
            def wrapper(*args, **kwargs):
                retries = 0
                while retries < max_retries:
                    try:
                        return func(*args, **kwargs)
                    except ClientError as e:
                        error_code = e.response['Error']['Code']
                        
                        # Determine if error is retryable
                        retryable_errors = [
                            'ThrottlingException',
                            'ModelTimeoutException',
                            'ServiceUnavailableException',
                            'InternalServerException'
                        ]
                        
                        if error_code not in retryable_errors:
                            # Don't retry non-transient errors
                            raise
                        
                        retries += 1
                        if retries >= max_retries:
                            raise
                        
                        # Calculate backoff delay
                        delay = min(base_delay * (exponential_base ** retries), max_delay)
                        
                        # Add jitter to prevent thundering herd
                        if jitter:
                            delay = delay * (0.5 + random.random())
                        
                        print(f"Retry {retries}/{max_retries} after {delay:.2f}s due to {error_code}")
                        time.sleep(delay)
                        
                return None
            return wrapper
        return decorator
  2. Apply the retry decorator to your Amazon Bedrock API operations:

    @retry_with_exponential_backoff(max_retries=5, base_delay=1)
    def invoke_bedrock_model(bedrock_runtime, model_id, prompt):
        """
        Invoke a Bedrock model with automatic retry logic.
        """
        response = bedrock_runtime.invoke_model(
            modelId=model_id,
            contentType="application/json",
            accept="application/json",
            body=json.dumps(
                {
                    "anthropic_version": "bedrock-2023-05-31",
                    "max_tokens": 500,
                    "messages": [
                        {
                            "role": "user",
                            "content": prompt
                        }
                    ]
                }
            )
        )
        return response
    
    # Usage example
    try:
        result = invoke_bedrock_model(
            bedrock_runtime,
            "us.anthropic.claude-sonnet-4-5-20250929-v1:0",
            "Hello, world!",
        )
        print("Success:", result)
    except Exception as e:
        print(f"Failed after all retries: {e}")

    Note: Replace us.anthropic.claude-sonnet-4-5-20250929-v1:0 with your model ID and adjust the body payload based on your model requirements. The preceding decorator automatically handles retriable errors. You can apply the decorator to functions that call Amazon Bedrock API operations.

Implement a circuit breaker pattern for production workloads

A circuit braker pattern improves system resiliency and prevents resource exhaustion so that no API operations are repeated to a failing service.

To implement a circuit breaker pattern use the following code:

import time
from enum import Enum
from threading import Lock

class CircuitState(Enum):
    CLOSED = "closed"
    OPEN = "open"
    HALF_OPEN = "half_open"
    
class CircuitBreaker:
    def __init__(self, failure_threshold=5, timeout=60, half_open_attempts=1):
        self.failure_threshold = failure_threshold
        self.timeout = timeout
        self.half_open_attempts = half_open_attempts
        self.failure_count = 0
        self.last_failure_time = None
        self.state = CircuitState.CLOSED
        self.lock = Lock()
    
    def call(self, func, *args, **kwargs):
        with self.lock:
            if self.state == CircuitState.OPEN:
                if time.time() - self.last_failure_time >= self.timeout:
                    self.state = CircuitState.HALF_OPEN
                    print("Circuit breaker entering HALF_OPEN state")
                else:
                    raise Exception("Circuit breaker is OPEN - failing fast")
        
        try:
            result = func(*args, **kwargs)
            self._on_success()
            return result
        except Exception as e:
            self._on_failure()
            raise
    
    def _on_success(self):
        with self.lock:
            self.failure_count = 0
            if self.state == CircuitState.HALF_OPEN:
                self.state = CircuitState.CLOSED
                print("Circuit breaker now CLOSED")
    
    def _on_failure(self):
        with self.lock:
            self.failure_count += 1
            self.last_failure_time = time.time()
            
            if self.failure_count >= self.failure_threshold:
                self.state = CircuitState.OPEN
                print(f"Circuit breaker now OPEN after {self.failure_count} failures")

# Usage with Bedrock
circuit_breaker = CircuitBreaker(failure_threshold=3, timeout=30)

@retry_with_exponential_backoff(max_retries=3)
def invoke_with_circuit_breaker(bedrock_runtime, model_id, prompt):
    return circuit_breaker.call(
        bedrock_runtime.invoke_model,
        modelId=model_id,
        contentType="application/json",
        accept="application/json",
        body=prompt
    )

Monitor and optimize retry behavior

To monitor and optimize retry behavior, complete the following steps:

  1. To track retry attempts and success rates, add logging and metrics to your Amazon Bedrock operations:

    import logging
    from datetime import datetime
    from functools import wraps
    from botocore.exceptions import ClientError
    
    logging.basicConfig(level=logging.INFO)
    logger = logging.getLogger(__name__)
    
    def retry_with_monitoring(max_retries=5, base_delay=1, max_delay=60, exponential_base=2, jitter=True):
        def decorator(func):
            @wraps(func)
            def wrapper(*args, **kwargs):
                start_time = datetime.now()
                retries = 0
                
                while retries < max_retries:
                    try:
                        result = func(*args, **kwargs)
                        duration = (datetime.now() - start_time).total_seconds()
                        
                        logger.info(f"Success after {retries} retries in {duration:.2f}s")
                        
                        # Send metrics to CloudWatch
                        publish_retry_metrics(retries, True, duration)  # Defined in Step 2 below
                        
                        return result
                    except ClientError as e:
                        error_code = e.response['Error']['Code']
                        
                        # Determine if error is retryable
                        retryable_errors = [
                            'ThrottlingException',
                            'ModelTimeoutException',
                            'ServiceUnavailableException',
                            'InternalServerException'
                        ]
                        
                        if error_code not in retryable_errors:
                            # Don't retry non-transient errors
                            raise
                        
                        retries += 1
                        logger.warning(f"Attempt {retries}/{max_retries} failed: {error_code}")
                        
                        if retries >= max_retries:
                            duration = (datetime.now() - start_time).total_seconds()
                            logger.error(f"All retries exhausted after {duration:.2f}s")
                            
                            # Send failure metrics to CloudWatch
                            publish_retry_metrics(retries, False, duration)  # Defined in Step 2 below
                            raise
                        
                        # Calculate backoff delay
                        delay = min(base_delay * (exponential_base ** retries), max_delay)
                        
                        # Add jitter to prevent thundering herd
                        if jitter:
                            delay = delay * (0.5 + random.random())
                        
                        logger.info(f"Retry {retries}/{max_retries} after {delay:.2f}s due to {error_code}")
                        time.sleep(delay)
                        
            return wrapper
        return decorator
  2. Publish your customer metrics to Amazon CloudWatch:

    import boto3
    
    cloudwatch = boto3.client('cloudwatch')
    
    def publish_retry_metrics(retries, success, duration):
        cloudwatch.put_metric_data(
            Namespace='BedrockAPIMetrics',
            MetricData=[
                {
                    'MetricName': 'RetryCount',
                    'Value': retries,
                    'Unit': 'Count'
                },
                {
                    'MetricName': 'APICallDuration',
                    'Value': duration,
                    'Unit': 'Seconds'
                },
                {
                    'MetricName': 'SuccessRate',
                    'Value': 1 if success else 0,
                    'Unit': 'Count'
                }
            ]
        )

To optimize your configurations, implement the following best practices:

Review your Amazon Bedrock quotas on the Service Quotas console. If you consistently exceed throttling quotas after you implement retry logic, then request a quota increase.

Related information

Retries

AWS Well-Architected

AWS OFFICIALUpdated 8 months ago