Errors, rate limits, timeouts and retries

Study time
≈ 3.5 h (estimate)
Needs
L1-M03-L02
Updated
2026-11-06

Progress is saved in this browser only. No account, nothing is sent to a server.

Draft · reviewed by AI, not yet by a person. Content may change. English translation: AI-assisted, not human-reviewed.
On this page

Module: L1-M03 · Duration: ~210 min (estimate, including the independent exercise) · Previous: L02 · Next: L04 - Streaming and latency (TTFT)

1. Introduction

A model provider's API will fail: overloaded at peak times, quota used up, a slow network, a revoked key. The question is not "will there be errors" but "what does your product do when an error happens".

Errors are very hard to reproduce with the real API. You cannot ask the provider to return a 529 error exactly when you run your tests. A fake API can. This lesson teaches you to test the whole error path: classification, retry, telling the user, and recording it for investigation.

2. Learning objectives

  1. Classify the Claude API's HTTP error codes into errors caused by our own request and transient errors on the provider's side.
  2. Verify with tests how many times the SDK retries for each kind of error, and that the SDK respects retry-after.
  3. Detect the difference between a rate limit and the spend cap, and handle them differently.
  4. Verify the behaviour on a timeout, including the number of requests actually sent.
  5. Evaluate the error message shown to the user: safe, useful, not revealing internal details.

3. Prerequisites and tools

  • L01, L02: the fake API and ask().
  • The idea of HTTP status codes (2xx, 4xx, 5xx) from traditional API testing.

4. Concepts

4.1 The main error codes

According to Anthropic's Errors page [R1]:

Code Type (error.type) Meaning Whose fault?
400 invalid_request_error The request has a wrong format or content; also used when the spending limit you set yourself is reached Ours
401 authentication_error The key is wrong, revoked or expired Ours
402 billing_error A payment problem Ours (the account)
403 permission_error The key has no permission for the resource Ours
404 not_found_error The resource was not found Ours
413 request_too_large The request is too large Ours
429 rate_limit_error A rate limit was reached, or the tier's monthly spend cap was reached Transient, or quota used up
500 api_error An internal error on the provider's side Transient
504 timeout_error The request took too long to process Transient
529 overloaded_error The API is temporarily overloaded Transient

Every error returns JSON with error.type, error.message and request_id [R1].

Everyday example. Calling a bank's hotline. "The account number is wrong" is your fault (4xx): calling again with the same details gives the same answer, you have to fix the details. "All lines are busy, please call back later" is temporary (429, 5xx, 529): calling back after a while usually works.

Good vs bad. Same situation: the fake returns 529 three times.

Weak test Good test
assert not ask(client, "hi").ok Asserts reason == "overloaded", len(api.requests) == 3, and that the text is the friendly sentence, without overloaded_error

The weak test still passes when 529 is misclassified as client_error, exactly the defect the first version of the lab had (section 5.1). An error handled "the wrong way" is still ok=False.

4.2 The SDK's retries

The documentation says that the official SDKs automatically retry transient errors (connection errors, rate limits, 5xx errors) with exponential backoff, twice by default, and respect the retry-after header when it is present [R1]. Exponential backoff means each retry waits longer than the previous one.

The lab tried this out with anthropic 2.3.0 (2026-10-31) and observed:

Situation Requests actually sent
429, 500 or 529 repeatedly 3 (1 first attempt + 2 retries)
400, 401, 403, 404, 413 1 (no retry)
408, 409 3: the SDK does retry these two 4xx codes
Timeout with max_retries=1 2
max_retries=0 1
429 with retry-after: 1 The SDK waits at least 1 second before retrying

Retry on retry is a common defect: the product's code adds its own retry loop outside the SDK. With 3 attempts at each layer, one 429 error becomes 3 × 3 = 9 requests, which makes the overload worse and costs more.

Everyday example. Booking a ride on a rainy evening: the app searches for a driver again twice if nobody accepts (the SDK's retries). If you also press "book again" two more times yourself, each press makes the app search three times: nine searches for one ride, exactly when the system is most congested.

Worked example (real run). The same error on every attempt, with max_retries from 0 to 2. Run it from the lab folder:

python - <<'EOF'
import os
os.environ["ANTHROPIC_API_KEY"] = "sk-test-fake-key-0000"
from lab.fake_api import FakeClaudeAPI, Reply, error_body
from lab.tutor_client import ask, make_client

NOW = {"retry-after-ms": "10"}
with FakeClaudeAPI() as api:
    for max_retries in (0, 1, 2):
        client = make_client(base_url=api.base_url, max_retries=max_retries)
        row = []
        for status, kind in [(429, "rate_limit_error"), (529, "overloaded_error"), (408, "invalid_request_error"), (400, "invalid_request_error")]:
            api.requests.clear()
            api.replies.clear()
            api.queue(*[Reply(status, error_body(kind, "x"), NOW)] * 5)
            r = ask(client, "hi")
            row.append(f"{status}:{len(api.requests)} ({r.reason})")
        print(f"max_retries={max_retries} -> " + "  ".join(row))
EOF

Output (2026-11-06, Linux; Python 3.14.6 and 3.12.3 give identical results):

max_retries=0 -> 429:1 (rate_limited)  529:1 (overloaded)  408:1 (client_error)  400:1 (client_error)
max_retries=1 -> 429:2 (rate_limited)  529:2 (overloaded)  408:2 (client_error)  400:1 (client_error)
max_retries=2 -> 429:3 (rate_limited)  529:3 (overloaded)  408:3 (client_error)  400:1 (client_error)

Read it by column: 429, 529 and 408 send max_retries + 1 requests; 400 always sends 1. One detail worth putting in the risk table: the SDK does retry 408, but ask() still reports client_error (the message "The technical team has been notified"), because 408 matches no other exception group in ask(). That is a decision the product owner should confirm.

4.3 Rate limit and spend cap: the same 429, different meanings

According to the Rate limits page [R2]:

  • Rate limits are measured in requests per minute (RPM), input tokens per minute (ITPM) and output tokens per minute (OTPM). When one is exceeded, the API returns 429. If there is a retry-after header, wait exactly that many seconds.
  • The tier's spend cap: also a 429 rate_limit_error, but without retry-after, and error.details.error_code is enforced_spend_limit_reached. Retrying, including the SDK's automatic retries, will keep failing until access is restored.

That is why the code must read error_code to know whether this is "try again in a few minutes" or "the service is paused".

Everyday example. A busy noodle stall puts up a sign "about a 10-minute wait" (a rate limit, with retry-after): waiting makes sense. Another stall puts up "sold out for today" (the spend cap): waiting at the door all afternoon will not get you a bowl, and the owner needs to know so they can restock.

4.4 Timeout

By default, the SDK sets a request timeout of 10 minutes (the lab observed that DEFAULT_TIMEOUT has read = 600 seconds in anthropic 2.3.0). In a chat application, users do not wait 10 minutes. Set a timeout that suits the product, and remember that timeouts are retried too: the total waiting time can be timeout × (max_retries + 1).

For long requests, the documentation recommends streaming or the Message Batches API instead of an ordinary request [R1]. Lesson L04 covers streaming.

Worked example. The lab's make_client() sets timeout=30.0 and max_retries=2. If the model does not answer:

  1. The first attempt waits 30 seconds, then times out.
  2. The SDK retries: another 30 seconds, plus a short backoff.
  3. The second retry: 30 more seconds.
  4. Total: 30 × (2 + 1) = 90 seconds, plus backoff, before the learner sees "the system is responding too slowly".

With the SDK's default timeout of 600 seconds, that number is 30 minutes. The test test_timeout_is_retried_then_reported checks this multiplication in about a second: a 0.3-second timeout, max_retries=1, a fake that answers after 1 second, and exactly 2 requests sent.

5. Technical deep dive

5.1 Typed exceptions and the order of except

The Python you need for this section: every exception is a class. A class can inherit from another class: RateLimitError inherits from APIStatusError, meaning a RateLimitError also is an APIStatusError. When an error occurs, Python tries the except blocks from top to bottom and stops at the first block that matches. So the specific class must come before the general class: if except APIStatusError comes first, it catches every HTTP error, and the blocks below it never run.

The SDK raises its own exception class for each kind of error: RateLimitError (429), InternalServerError (>= 500), APITimeoutError, APIConnectionError... The documentation recommends catching the specific classes first and the general class last, instead of comparing error message strings [R1].

Everyday example. Sorting mail at a post office: the "registered mail" basket must come before the "ordinary mail" basket. If "ordinary mail" comes first, every letter, registered ones included, lands in it.

Good vs bad. The wrong order, shortened:

try:
    msg = client.messages.create(**params)
except anthropic.APIStatusError:            # general class first: catches every HTTP error
    return "client_error"
except anthropic.RateLimitError:            # never reached
    return "rate_limited"

A 429 here is reported as client_error: the user is not told to try again later, and operations never see the rate limit. The right order is the order of ask() just below: specific classes first, APIStatusError last.

A finding of the lab (observed with anthropic 2.3.0): a 529 error raises anthropic.OverloadedError, and this class inherits directly from APIStatusError, not from InternalServerError. Code that only catches InternalServerError to handle "server-side errors" will put 529 into the "our request is wrong" group. The first version of tutor_client.py had exactly this defect. A test with the fake API found it, and the code has been fixed:

except anthropic.APITimeoutError:
    ...                                   # reason "timeout"
except anthropic.APIConnectionError:
    ...                                   # reason "connection_error": no response at all
except anthropic.OverloadedError as e:
    # 529 is its own class in the SDK, not a subclass of InternalServerError.
    return TutorResult(False, "Hệ thống đang quá tải, vui lòng thử lại sau.", "overloaded", e.request_id)
except anthropic.InternalServerError as e:
    ...                                   # reason "server_error"
except anthropic.BadRequestError as e:
    ...                                   # reason "spend_limit" for the self-set limit, else "client_error"
except anthropic.APIStatusError as e:
    # Other 4xx: our request is wrong. Do not show provider details to the learner.
    ...

In English, the Vietnamese message reads: "The system is overloaded, please try again later."

5.2 Simulating errors with the fake API

api.queue(*[Reply(529, error_body("overloaded_error", "x"), NOW)] * 3)

This line queues three 529 replies, enough for the first attempt and the two retries. On the syntax: [x] * 3 creates a list of 3 identical elements, and the * before the list spreads it into 3 separate arguments for queue(). NOW = {"retry-after-ms": "10"} tells the SDK to wait 10 ms between retries so the tests run fast. Without this header, the SDK uses its own backoff (about 0.5 seconds and then 1 second, observed in the lab). The demo lab/demo.py calls the same dict FAST; two names, one value.

Good vs bad. Queue one 529 reply instead of three: the first attempt gets 529, the retry gets the default (successful) reply. The lab gives reason=complete with 2 requests (run 2026-11-06, Linux, both Pythons), so a "529 is reported as overloaded" test fails for the wrong reason, or worse, a "529 then recovery" test passes when you meant to check a persistent 529. Always queue enough replies for max_retries + 1 attempts.

6. The QA perspective

  • What to test: each group of errors in table 4.1; the number of requests actually sent for each error; telling a rate limit apart from the spend cap; timeouts; the message shown to the user.
  • Why: errors happen exactly at high load, that is, when there are the most users. Handling them wrongly amplifies the incident.
  • What can go wrong: retry on retry; retrying a 400 error (useless); ignoring retry-after; showing an internal message to the user; classifying 529 as a client error; a timeout that is too long.
  • Expected behaviour (an example to agree on): transient errors are retried by the SDK and then reported as "try again later"; request errors are not retried, a generic error is reported and the technical team is alerted; the spend cap is reported as "paused" and raises an alarm immediately.
  • How to detect it: a fake API that returns each error code; counting len(api.requests).
  • How to report it: the error code, error.type, request_id, the number of requests sent, the configuration (max_retries, timeout), the SDK version.

7. Real-world scenarios

Scenario 1 - Exam rush hour (fictional). An English exam-preparation app gets 529 errors on the evening before an exam. The code classifies 529 as a "request error" and shows "Something went wrong". Learners think their account is broken and send hundreds of support tickets. A test that could catch this: the fake returns 529 and you check the message together with the classification.

Scenario 2 - A customer-service chatbot stops working (fictional). A business reaches its monthly spend cap. The code treats it as an ordinary rate limit and shows "try again in a few minutes" all day, while nobody on the team knows. Test: the fake returns a 429 with enforced_spend_limit_reached, and you check that the product reports "paused" (and, in a real system, sends an alert to the operations team).

8. Hands-on tutorial

8.1 Running the demo

python -m lab.demo l03

Actual output (2026-10-31):

429 x3        -> reason=rate_limited requests sent=3  shown: Hệ thống đang bận, vui lòng thử lại sau ít phút.
429 then 200  -> reason=complete     requests sent=2  shown: Hello!
spend cap     -> reason=spend_cap    requests sent=3  shown: Dịch vụ tạm dừng. Vui lòng thử lại sau.
500 x3        -> reason=server_error requests sent=3  shown: Hệ thống đang gặp sự cố, vui lòng thử lại sau.
529 x3        -> reason=overloaded   requests sent=3  shown: Hệ thống đang quá tải, vui lòng thử lại sau.
400           -> reason=client_error requests sent=1  shown: Đã có lỗi xảy ra. Đội kỹ thuật đã được thông báo.

In English, the messages shown read, in order: "The system is busy, please try again in a few minutes."; "Service paused. Please try again later."; "The system is having a problem, please try again later."; "The system is overloaded, please try again later."; "Something went wrong. The technical team has been notified."

Reading the result:

  • 429, 500 and 529 all send 3 requests: the SDK retried twice.
  • The spend cap also sends 3 requests with the fake API: the SDK still retries, even though the documentation says retries will keep failing. ask() still classifies it correctly as spend_cap. Note: the SDK also follows the x-should-retry header if the server sends it. The fake does not send this header, and the lab has not verified whether the real API sends it for the spend-cap error. The figure of 3 requests is the fake's, not necessarily the real API's.
  • 400 sends only 1 request, and the message for the learner does not contain the provider's error content.

8.2 Running the tests

python -m pytest tests/test_l03_errors.py -v

Expected result: 16 passed (a few seconds, because one test waits for retry-after: 1). These include characterization tests for the behaviour of SDK 2.3.0: 529 is not an InternalServerError, 408 and 409 are retried, retry-after-ms is respected.

8.3 Troubleshooting

Symptom Cause Fix
Error tests take a few seconds There is no retry-after-ms header, so the SDK uses its default backoff Use NOW in the fake reply
len(api.requests) is larger than expected Fewer error replies were queued than attempts, so the default (successful) reply is returned Queue enough replies for every attempt
The timeout test fails intermittently A slow machine Increase the gap between delay and timeout

9. Independent exercise

Problem: The test suite does not yet cover 403 and 404.

Tasks:

  1. Copy exercises/test_l03_more_errors.py into tests/. Add 403 permission_error and 404 not_found_error.
  2. Assert the reason and the number of requests for each error.
  3. Write 3-5 sentences: when can a 404 happen with an LLM API? (Hint: L02, the model parameter.) Does the operations team need to be alerted?

Test data: the two error codes above, with error_body(...).

Deliverable: the test file and the comment.

Acceptance criteria: the test passes; both errors send only 1 request; the comment links 404 to a specific cause.

Hint: delete test_cases_were_added once you have added the cases to the parametrize list.

9.1 Extra exercise: how many requests does one error cost?

Problem (about 25 minutes): operations need to know, for each error code, how many requests to the provider one learner question produces. You answer with a prediction function, and the test compares it with the real SDK.

Tasks:

  1. Copy exercises/test_l03_extra_retry_count.py into tests/.
  2. Write expected_requests(status, max_retries) from the table in section 4.2 and the worked example right after it.
  3. Run python -m pytest tests/test_l03_extra_retry_count.py. The test runs 10 error codes × 3 values of max_retries.

Acceptance criteria: untouched, 30 failed with a TODO message; when done, 30 passed.

Hint: two shortcuts fail: "no 4xx code is retried" and "it is always 3 requests". Write the function as a rule (which codes are retried), do not copy 30 numbers.

9.2 Real-world scenario: three hours of "try again in a few minutes"

Context (fictional): on a Friday evening, a retail chain's customer-service chatbot shows "The system is busy, please try again in a few minutes" for three hours. The backend logs show:

  • every response from the provider is a 429 rate_limit_error, without a retry-after header, and with error.details.error_code = "enforced_spend_limit_reached";
  • a sample request ID: req_fake_err;
  • the number of requests sent to the provider is 9 times the number of customer questions;
  • nobody on the team was alerted until customers called the hotline.

Your task: write a bug report (one or more defects) with: title, environment, steps to reproduce with the fake API, expected, actual, evidence, severity, and the regression test you will add.

A good answer has:

  • two separate defects: the spend cap is reported as a rate limit, and retry on retry (9 = 3 × 3);
  • steps to reproduce with the fake: a 429 with enforced_spend_limit_reached, counting len(api.requests);
  • a clear expected result: a "paused" message for customers, an alert for operations, no more than 3 requests;
  • the request ID and the configuration (max_retries, SDK version) in the evidence;
  • a severity with a reason (customers affected, nobody alerted), and no sensitive data pasted.

10. Knowledge check

0/18 done · Results are kept in this browser only.

P02 · True or false

Every 429 error can be resolved by waiting and then retrying.

P03 · Short answer

(Calculation) The SDK retries 2 times. The product's code wraps the call in its own retry loop of 3 attempts. How many requests does a persistent 429 error create?

P04 · Short answer

Why should code not determine the kind of error by searching for a string in the error message?

P05 · Short answer

(Scenario) The timeout is set to 60 seconds, max_retries=2. Users complain that "sometimes it takes 3 minutes before the error appears". Explain the cause and propose a change.

P06 · Match

Using the table in §4.1, match each error code with its error.type.

P07 · Fill in the blank

According to §5.2, NOW = {"retry-after-ms": "10"} tells the SDK to wait ___ ms between retries. Without this header, the SDK uses its own backoff: about ___ seconds and then 1 second.

P08 · Multiple choice

Using the table in §4.2, a client with timeout=0.3 and max_retries=1 calls a fake API that waits 1 second before each reply. How many requests are sent?

P09 · Spot the bug

The except chain below is condensed from ask() (the bodies of the blocks are omitted) but has one defect. Find it.

try:
    msg = client.messages.create(**params)
except anthropic.APIStatusError as e:
    return TutorResult(False, "Đã có lỗi xảy ra. Đội kỹ thuật đã được thông báo.", "client_error", e.request_id)
except anthropic.RateLimitError as e:
    ...                                   # reason "spend_cap" or "rate_limited"
except anthropic.APITimeoutError:
    ...                                   # reason "timeout"
except anthropic.APIConnectionError:
    ...                                   # reason "connection_error"
except anthropic.OverloadedError as e:
    ...                                   # reason "overloaded"
except anthropic.InternalServerError as e:
    ...                                   # reason "server_error"
except anthropic.BadRequestError as e:
    ...                                   # reason "spend_limit" or "client_error"

P10 · Select all that apply

According to "How to report it" in §6, what does a bug report about an API error need? Select every correct option.

P11 · Recall

Lesson: L1-M03-L02

Lesson L02: the demo calls client.messages.create(..., temperature=0.2) and gets a TypeError. How many requests does that call send to the fake API?

P13 · Multiple choice

In the output of the worked example in §4.2, with max_retries=1, how many requests does a 408 error send, and what reason does ask() report?

P14 · Fill in the blank

From the worked example of §4.4: with timeout=30.0 and max_retries=2, the learner waits about ___ seconds (not counting backoff) before seeing the timeout message. With the SDK's default timeout of 600 seconds, that number is ___ minutes.

P15 · True or false

In the good vs bad example of §5.1, if except anthropic.APIStatusError comes before except anthropic.RateLimitError, a 429 error is still reported as rate_limited.

P16 · True or false

Queueing one 529 reply for a client with max_retries=2 makes ask() report complete after 2 requests.

P17 · Apply now

In code-labs/l1-m03, run the code from the worked example of §4.2. Then replace the list of errors with [(500, "api_error"), (401, "authentication_error")] and run it again.

Checklist

P18 · Apply now

In code-labs/l1-m03, do the extra exercise in §9.1: copy exercises/test_l03_extra_retry_count.py into tests/ and run python -m pytest tests/test_l03_extra_retry_count.py.

Checklist

11. Summary

  • Concepts: our errors (4xx) and transient errors (429, 5xx, 529); the SDK's default retries; retry-after; a rate limit is different from the spend cap; timeouts are retried too; 529 is its own class in the SDK.
  • Skills: simulating errors with a fake API; counting the requests actually sent; testing error messages.
  • Traps: retry on retry; retrying 4xx; comparing error message strings; the default 10-minute timeout for chat.
  • You can now: design and run a test suite for the error paths of an LLM integration.

12. References

ID Title Publisher URL Accessed Relevance
R1 Claude API errors Anthropic https://platform.claude.com/docs/en/api/errors 2026-10-31 Error code table; error structure; default of 2 retries, respects retry-after; typed exceptions; long requests
R2 Rate limits Anthropic https://platform.claude.com/docs/en/api/rate-limits 2026-10-31 RPM/ITPM/OTPM; retry-after; the spend cap and enforced_spend_limit_reached

Version note: the number of retries, the backoff and the exception classes were observed with anthropic 2.3.0 on 2026-10-31. Other SDK releases may differ. The tests in the lab will flag it when that happens.

Key terms (English ↔ Vietnamese)

English Tiếng Việt
Retry Thử lại
Exponential backoff Chờ lâu dần giữa các lần thử lại
Rate limit Giới hạn số request hoặc token trong một khoảng thời gian
Spend cap Trần chi tiêu
Timeout Hết thời gian chờ
Typed exception Exception có class riêng cho từng loại lỗi
Transient error Lỗi tạm thời