
مش كل error في Claude API يستاهل retry: الفرق بين 400 و429 و529
- كاتب موثّق
- Claude API
محتويات المقال
while True اللي في الـ worker حوّل bug كان المفروض يبان من أول call لتلات أيام سكوت.
الفكرة الغلط الشائعة
الشبكات بتقطع والـ services بتتعب، و"اعمل retry مع " نصيحة معروفة. فيه errors مؤقتة فعلًا، والـ docs نفسها بتقولك تعيد الـ 500 مع exponential backoff. وإنت بتطوّر، كل اللي بتقابله timeouts وrate limits، والـ retry بيحلهم. والـ loop اللي مبيستسلمش شكله متين: مفيش حاجة بتقع ومحدش بيصحى على page.
اللي بيحصل فعلًا
الـ status code بيقولك مين عليه الدور
error object جواه type وmessage، ومعاهم request_id. والـ docs بتعدّ الأكواد، ولو رتبتها على حسب مين المفروض يتحرك هتلاقيها مجموعتين:
error.type | |||
|---|---|---|---|
invalid_request_error | |||
authentication_error / permission_error | |||
request_too_large | |||
rate_limit_error | retry-after | ||
api_error | |||
overloaded_error |
billing_error والـ 404 not_found_error من مجموعة "صلّحها". وفيه كودين محتاجين حركة معيّنة بدل retry أعمى: مع الـ 409 conflict_error الـ docs بتقولك حل الـ conflict وبعدين اعمل retry، ومع الـ 504 timeout_error بتوجهك للـ streaming في الـ requests الطويلة. وقيم الـ type ممكن تزيد مع الوقت، فأي mapping للأنواع لازم يبقى فيه default branch.
الـ SDK بيعمل retry بالنيابة عنك
retry-after header when present". وفي Python ده بيشمل الـ connection errors والـ 408 والـ 409 والـ 429 وأي status من 500 وطالع، والـ max_retries على الـ client بيغيّر العدد.
RateLimitError يوصل للكود بتاعك، تبقى دي تالت محاولة فاشلة أصلًا. ولو لفّيته في loop بتاعك خمس مرات، دقيقة وحشة واحدة هتبقى 15 request، أغلبهم بـ sleep ثابت بيتجاهل المدة اللي الـ API طلبها. أما الـ errors اللي مينفعش تتعاد فبتوصلك على طول كـ typed exceptions: BadRequestError وAuthenticationError وPermissionDeniedError وNotFoundError. ونصيحة الـ docs إنك تمسكها "rather than string-matching error messages, handling the most specific classes first".
مش كل 429 تبقى rate limit
retry-after هو "the number of seconds to wait until you can retry the request. Earlier retries will fail". وأي قفزة مفاجئة في الترافيك ممكن تجيب 429 من الـ acceleration limits، فالـ docs بتنصحك تزوّد الحمل بالتدريج.
rate_limit_error، بس من غير retry-after، والاستخدام بيقف لحد 00:00 UTC في أول يوم من الشهر اللي بعده. والـ docs واضحة: "Retrying, including the SDK's automatic retries, fails until access resumes". والـ body فيه كود تقدر تختبره:
{ "type": "error", "error": { "type": "rate_limit_error", "message": "You have reached your API usage limits: ...", "details": { "error_code": "enforced_spend_limit_reached" } }, "request_id": "req_018EeWyXxfu5pfWkrYcMdjWG"}invalid_request_error برسالة بتبدأ بـ "You have reached your specified API usage limits".
الـ 529 مش عنك
overloaded_error فمعناها "the API is temporarily overloaded"، والـ docs بتضيف إنها "can occur when the API experiences high traffic across all users". الاتنين يستاهلوا backoff، بس الـ rate-limit headers بتاعتك مش هتفسر الـ 529، والضرب المستمر في API مضغوط بيوحّشها على الكل، وإنت منهم. ومع الـ streaming، نفس الـ error ممكن ييجي بعد 200 كـ event من نوع error.
نصلّح الـ worker
import timeimport anthropicclient = anthropic.Anthropic()def tag(ticket: str): while True: # "the API is flaky, retry until it works" try: return client.messages.create( model="claude-opus-5-5", max_tokens=1024, messages=[ {"role": "user", "content": f"Tags for:\n{ticket}"}, {"role": "assistant", "content": "Tags:"}, # prefill ], ) except Exception as err: # a 400 loops here forever print(f"retrying in 1s: {err}") time.sleep(1)tag("Customer reports a double charge on order 1042")import anthropicSPEND_CAP = "enforced_spend_limit_reached"client = anthropic.Anthropic() # retries 408/409/429/5xx twice, with backoffdef tag(ticket: str): try: return client.messages.create( model="claude-opus-5-5", max_tokens=1024, messages=[{"role": "user", "content": f"Tags for:\n{ticket}"}], ) except anthropic.RateLimitError as err: # still 429 after the SDK's retries error = err.response.json()["error"] if error.get("details", {}).get("error_code") == SPEND_CAP: raise SpendCapReached(error["message"]) from err # page a human wait = int(err.response.headers.get("retry-after", 60)) requeue(ticket, delay=wait) except anthropic.InternalServerError: # 500 or 529 after the retries requeue(ticket, delay=300) # 400, 401, 403, 404 aren't caught: retrying can't fix themtag("Customer reports a double charge on order 1042")BadRequestError من أول call، برسالة بتسمّي المشكلة. والـ docs بتقترح structured outputs أو تعليمات في الـ system prompt بدل الـ prefill. والدقيقة الزحمة بترجع للـ queue بالتأخير اللي الـ API طلبه، والـ spend cap بيوصل لبني آدم مش لـ loop.
تطبقها إزاي في مشروعك
دوّر على الـ retry wrappers بتاعتك دوّر على except Exceptionحوالينmessages.createوعلى أي retry decorators، وشيل اللي بيكرر شغل الـ SDK.امسك الـ typed exceptions، الأدق الأول اتعامل مع RateLimitErrorوInternalServerErrorبشكل صريح، وسيب errors الـ request زيBadRequestErrorتوصل للـ error tracker ومعاها الـ request ID.اقرا الـ 429 قبل ما تستنى استخدم retry-afterلو موجود. ولو مش موجود، شوفerror.details.error_codeعشان الـ spend cap، ونبّه حد بدل ما تعيد.اعمل الـ retry في المستوى الصح في request فيه يوزر مستني، خلّي الـ retries قصيرة وافشل بسرعة. وفي background worker، رجّع الـ job للـ queue بتأخير بدل الـ sleep جوه الـ handler. زوّد الترافيك بالتدريج وراقب المساحة علّي الحجم بالراحة عشان الـ acceleration limits، وراقب الـ headers anthropic-ratelimit-*-remainingأو charts الـ rate limits في الـ Console قبل ما تخبط في الحيطة.
الخلاصة
الـ status code بيقولك تصلّح الـ request ولا تستنى: أغلب الـ 4xx مش هتتغير مع الـ retry. الـ 429 والـ 500 والـ 529 يستاهلوا retry مع backoff، والـ SDK الرسمي بيعيدهم مرتين افتراضيًا أصلًا. الـ 429 اللي فيها enforced_spend_limit_reachedومن غيرretry-afterمش هتتحل بالـ retry: نبّه حد، متعملش loop.الـ 529 معناها إن الـ API مضغوط على الكل؛ والـ 429 معناها إن الـ organization بتاعتك وصلت لـ limit. امسك الـ typed exceptions بتاعة الـ SDK وسجّل الـ request ID، عشان الـ bugs تفشل بسرعة والأعطال يبقى ليها أثر.
التعليقات (0)