← Building with AI

Rate limits and retries

When the service says slow down, wait a bit longer each time.

Start this lesson

APIs limit how many requests you can make per minute. If you go over, you get a rate-limit error (HTTP status 429). Also, servers are sometimes briefly overloaded. The polite fix is exponential backoff: wait 1 second and try again, then 2, then 4, and give up after a few tries. Waiting longer each time gives the service room to recover.

# To run on your own computer with an API key (it cannot run in this browser).
# First: pip install anthropic, and set the ANTHROPIC_API_KEY environment variable.
import time, anthropic
client = anthropic.Anthropic(max_retries=3)   # the SDK already retries some errors for you

def ask_with_backoff(messages, tries=4):
    delay = 1
    for attempt in range(tries):
        try:
            return client.messages.create(model="claude-sonnet-5-5", max_tokens=300, messages=messages)
        except anthropic.RateLimitError:
            if attempt == tries - 1:
                raise
            time.sleep(delay)
            delay *= 2

Many SDKs retry automatically; knowing the pattern helps you set it up, and you'll use it for other APIs too.

In the exercise, wait(seconds) is a pretend sleep: it just records the wait, so the exercise runs instantly.

If you hit limits often, slow down on purpose: process items in smaller batches, or cache answers you have already got.