Heuristic:869413421 Ai moive studio Retry With Backoff Tip
| Knowledge Sources | |
|---|---|
| Domains | Optimization, Rate_Limiting, AI_Image_Generation |
| Last Updated | 2026-10-23 14:00 GMT |
Overview
Exponential backoff with random jitter to handle HTTP 429 rate-limit errors during batch AI image generation, reducing API failures under load.
Description
When calling external AI generation APIs (image, audio, video) in batch concurrent mode, providers frequently return HTTP 429 (Too Many Requests). The retry_with_backoff function wraps the API call in a retry loop that catches 429 errors, waits with exponential delay plus random jitter, and retries up to 5 times. The base delay doubles each attempt (1s, 2s, 4s, 8s, 16s) capped at 20 seconds, with up to 0.5s random jitter added to avoid thundering herd.
Usage
Use this heuristic when batch-generating images, audio, or video via external AI provider APIs that enforce rate limits. Apply when you see intermittent 429 errors during concurrent asyncio.gather calls. This is standard practice for any batch generation service (ImageService, SceneImageService, VisualIdentityService, TransitionService).
The Insight (Rule of Thumb)
- Action: Wrap each provider API call in retry_with_backoff() with max_retries=5.
- Value: base_delay=1.0s, max_delay=20s, jitter=random()*0.5s, max_retries=5.
- Trade-off: Adds latency on retries but dramatically improves batch success rate under rate limiting.
- Compatibility: Only retries on HTTP 429; all other exceptions propagate immediately. The last attempt re-raises even on 429.
Reasoning
External AI providers enforce rate limits per API key. When asyncio.gather fires 20+ concurrent requests simultaneously, many hit the rate limit simultaneously. Without backoff, all fail permanently. With exponential backoff:
- Failed requests stagger their retries, reducing concurrent load on the provider.
- Random jitter prevents all retries from firing at the same instant (thundering herd).
- The 20-second cap prevents excessive waiting on persistent rate limiting.
- Only 429 errors are retried — genuine failures (400, 500) propagate immediately.
Code Evidence
Retry logic from `image.py:20-37`:
async def retry_with_backoff(task_fn, max_retries=5):
delay = 1.0
for attempt in range(max_retries):
try:
return await task_fn()
except Exception as e:
if getattr(e, 'status_code', None) != 429 or attempt == max_retries - 1:
raise
sleep_time = delay + random.random() * 0.5
print(f"[Retry] 限流,{sleep_time:.2f} 秒后重试 attempt={attempt + 1}/{max_retries}")
await asyncio.sleep(sleep_time)
delay = min(delay * 2, 20)
Usage in process_sentence from `image.py:69-74`:
result = await retry_with_backoff(
lambda: llm_provider.generate_image(
prompt=sentence.image_prompt, model=model,
)
)