API Rate Limits and 429 Errors: Retry, Backoff and Batching

Short answer: a 429 means you hit a limit measured in requests per minute, tokens per minute, or concurrency. Read the Retry-After header, retry with exponential backoff plus jitter, and cap retries. Fixing the architecture — batching, caching, queueing — matters more than tuning the retry loop.

What is actually being limited

Providers rarely limit one number. Expect several ceilings at once: requests per minute, input plus output tokens per minute, concurrent requests, and a daily or monthly quota. A burst of small calls can pass the request limit while a single long prompt trips the token limit.

Response headers usually tell you which ceiling you hit and how long to wait. Log the limit headers on every response for a week; the pattern is more useful than any published table.

Retry rules that work

  • Retry only idempotent calls, or make writes idempotent with a request key.
  • Honour Retry-After when present; otherwise use exponential backoff with full jitter.
  • Cap total retries at four or five and set a deadline for the whole operation.
  • Separate retryable errors (429, 500, 502, 503, 504, timeouts) from permanent ones (400, 401, 403, 404, 422).
  • Circuit-break per provider so one failing endpoint does not stall the whole pipeline.
import random, time

def with_backoff(call, retries=5, base=0.5, cap=20):
    for attempt in range(retries):
        try:
            return call()
        except RateLimited as e:
            if attempt == retries - 1:
                raise
            wait = min(cap, base * 2 ** attempt)
            time.sleep(wait * random.uniform(0.5, 1.5))

Reduce the number of calls instead

Pattern Effect
Batch independent prompts into one request Fewer requests, better throughput per token
Cache deterministic answers by prompt hash Removes repeat spend entirely
Queue background work with a worker pool Smooths bursts instead of hammering the limit
Cap output tokens Output tokens dominate rate-limit math
Route cheap tasks to a smaller model Lower cost and lower token pressure

Design for a second provider

Keep model names, base URLs and keys in configuration, and put a thin adapter in front of each provider. When one API returns 429 for minutes, fail over to the fallback model instead of retrying into the wall. The model switching guide covers the adapter pattern; DeepSeek vs Qwen vs Kimi compares cost and context trade-offs.

Monitoring that catches limits early

Track 429 rate, p95 latency, tokens per request and retry count per provider. Alert when the 429 rate crosses a few percent for five minutes; that is usually a traffic-shape problem, not bad luck.

Frequently asked questions

How long should I wait after a 429?

Use Retry-After if the API sends it. Otherwise start around half a second and double each attempt with jitter, capping at 20–30 seconds.

Is a 429 always my fault?

Usually it is your traffic shape, but shared capacity and regional incidents also produce 429s. Compare your error rate with the provider status page before rewriting code.

Should I retry streaming requests?

Retry only if the stream failed before any content was delivered. Once tokens have been streamed, restart with a fresh request and deduplicate on your side.

Share your thoughts

Did this post help you? Leave a comment below — we read every single one and reply to as many as we can.

Comments are moderated and published after a quick review.

¿Te ayudó esta publicación? Deja un comentario abajo: leemos todos y respondemos a la mayoría.

Los comentarios se moderan y se publican tras una revisión rápida.

这篇文章对您有帮助吗?请在下方留言——我们会阅读每一条评论并尽可能回复。

评论需经过审核后才会显示。

Hat dir dieser Beitrag geholfen? Hinterlasse unten einen Kommentar – wir lesen jeden einzelnen und antworten so vielen wie möglich.

Kommentare werden moderiert und nach einer kurzen Prüfung veröffentlicht.

Cet article vous a-t-il aidé ? Laissez un commentaire ci-dessous – nous les lisons tous et répondons au plus grand nombre.

Les commentaires sont modérés et publiés après une vérification rapide.

Este artigo ajudou você? Deixe um comentário abaixo – lemos todos e respondemos à maioria.

Os comentários são moderados e publicados após uma revisão rápida.

Heeft dit bericht je geholpen? Laat hieronder een reactie achter – we lezen ze allemaal en beantwoorden zoveel mogelijk.

Reacties worden gemodereerd en na een korte controle gepubliceerd.

Czy ten post Ci pomógł? Zostaw komentarz poniżej – czytamy każdy i odpowiadamy na tyle, na ile możemy.

Komentarze są moderowane i publikowane po szybkiej weryfikacji.

Эта статья помогла вам? Оставьте комментарий ниже — мы читаем каждый и отвечаем на большинство.

Комментарии модерируются и публикуются после быстрой проверки.

هل ساعدك هذا المقال؟ اترك تعليقًا أدناه — نقرأ كل تعليق ونرد على أكبر عدد ممكن.

تتم مراجعة التعليقات وتنشر بعد التحقق السريع.

この記事は役に立ちましたか?下のコメント欄にぜひ投稿してください。すべて読んで、できる限り返信します。

コメントはモデレーション後に公開されます。

이 글이 도움이 되었나요? 아래에 댓글을 남겨주세요 — 모든 댓글을 읽고 최대한 많이 답변합니다.

댓글은 검토 후 게시됩니다.

บทความนี้ช่วยคุณได้ไหม? แสดงความคิดเห็นด้านล่าง — เราอ่านทุกความเห็นและตอบกลับให้มากที่สุด

ความคิดเห็นจะถูกตรวจสอบและเผยแพร่หลังจากการพิจารณา

האם המאמר עזר לכם? השאירו תגובה למטה — אנחנו קוראים כל תגובה ועונים לרובן.

תגובות עוברות ניהול ומתפרסמות לאחר בדיקה מהירה.

Bài viết này có giúp bạn không? Hãy để lại bình luận bên dưới — chúng tôi đọc từng bình luận và phản hồi nhiều nhất có thể.

Bình luận được kiểm duyệt và xuất hiện sau khi xét duyệt nhanh.

Apakah artikel ini membantu Anda? Tinggalkan komentar di bawah — kami membaca semuanya dan membalas sebanyak mungkin.

Komentar dimoderasi dan dipublikasikan setelah pemeriksaan cepat.

Бұл мақала сізге көмектесті ме? Төменде пікір қалдырыңыз — біз әрқайсысын оқып, мүмкіндігінше көбіне жауап береміз.

Пікірлер модерациядан өтіп, тексерілгеннен кейін жарияланады.

Comments (0)

No comments yet. Be the first to share your thoughts!