RUNLOCALAIv38
->Will it run?Best GPUCompareTroubleshootStartLearnPulseModelsHardwareToolsBench
Run check
RUNLOCALAI

Independently operated catalog for local-AI hardware and software. Hand-written verdicts. Source-cited claims. Reproducible commands when we have them.

OP·Eruo Fredoline
DIR
  • Models
  • Hardware
  • Tools
  • Benchmarks
TOOLS
  • Will it run?
  • Compare hardware
  • Cost vs cloud
  • Choose my GPU
  • Prompting kits
  • Quick answers
REF
  • All buyer guides
  • Learn local AI
  • Methodology
  • Glossary
  • Errors KB
  • Trust
EDITOR
  • About
  • Author
  • How we make money
  • Editorial policy
  • Contact
LEGAL
  • Privacy
  • Terms
  • Sitemap
MAIL · MONTHLY DIGEST
Get monthly local AI changes
Monthly recap. No spam.
DISCLOSURE

Some links on this site are affiliate links (Amazon Associates and other first-class retailers). When you buy through them, we earn a small commission at no extra cost to you. Affiliate links do not influence our verdicts — there are cards we rate highly that we don't have affiliate relationships with, and cards that sell well that we refuse to recommend. Read more →

© 2026 runlocalai.coIndependently operated
RUNLOCALAI · v38
  1. >
  2. Home
  3. /Learn
  4. /Courses
  5. /Python for AI — Zero to Useful
  6. /Ch. 17
Python for AI — Zero to Useful

17. Rate Limiting and Retries

Chapter 17 of 36 · 15 min
KEY INSIGHT

Rate limits are normal, not exceptional. Build retry logic with exponential backoff from the start. Use `time.sleep()` to pause between attempts. Check `Retry-After` header for server-specified delays.

Why Rate Limits Exist

AI APIs limit requests per minute to prevent abuse and ensure fair access. Exceeding limits returns 429 responses. Your code must handle this gracefully.

Detecting Rate Limits

import requests

response = requests.post(url, headers=headers, json=payload)

if response.status_code == 429:
    print("Rate limited")
    retry_after = response.headers.get("Retry-After", 60)
    print(f"Wait {retry_after} seconds")

Manual Retry Logic

import time
import requests

def call_with_retry(url, headers, payload, max_retries=3, base_delay=1):
    for attempt in range(max_retries):
        response = requests.post(url, headers=headers, json=payload)
        
        if response.status_code == 200:
            return response.json()
        
        if response.status_code == 429:
            delay = int(response.headers.get("Retry-After", base_delay * 2 ** attempt))
            print(f"Rate limited. Waiting {delay}s (attempt {attempt + 1}/{max_retries})")
            time.sleep(delay)
        else:
            response.raise_for_status()
    
    raise Exception(f"Failed after {max_retries} attempts")

Exponential Backoff

Wait longer between each retry:

def call_with_backoff(url, headers, payload, max_retries=5):
    for attempt in range(max_retries):
        try:
            response = requests.post(url, headers=headers, json=payload, timeout=30)
            response.raise_for_status()
            return response.json()
        except (requests.exceptions.HTTPError, requests.exceptions.Timeout) as e:
            if attempt == max_retries - 1:
                raise
            wait = 2 ** attempt  # 1, 2, 4, 8, 16 seconds
            print(f"Attempt {attempt + 1} failed: {e}. Retrying in {wait}s")
            time.sleep(wait)

Local verification checkpoint

Run the smallest example from this chapter in a local workspace and record the package version, runtime, data path, and observed output. If the result depends on model size, vector count, CPU/GPU backend, or available memory, note that constraint beside the exercise so the lesson remains reproducible.

Local verification checkpoint

Run the smallest example from this chapter in a local workspace and record the package version, runtime, data path, and observed output. If the result depends on model size, vector count, CPU/GPU backend, or available memory, note that constraint beside the exercise so the lesson remains reproducible.

EXERCISE

Write a function that simulates an API call (use a counter to make it fail twice then succeed). Implement exponential backoff with increasing delays. Time the total execution.

← Chapter 16
Working with APIs
Chapter 18 →
Reading API Responses