Survive rate limits, timeouts and a provider that is down
Learn LLMs · Beginner · 18 min · After Call a chat completion API with curl and Go
What should your program do when the API says "too many requests", answers slowly or is down?
Run it against a real free API
The outputs in this lesson are simulated by a local mock server. To get real answers, create a free key at Mistral AI Free Plan and set these variables. Never put the key in your code.
export LLM_BASE_URL=https://api.mistral.ai/v1
export LLM_MODEL=mistral-large-4
export LLM_API_KEY=your-key1Guess
curl -s -o /dev/null -w '%{http_code}\n' "$LLM_BASE_URL/chat/completions" \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $LLM_API_KEY" \ -H "X-Mock-Scenario: rate-limit" \ -d '{"model": "'"$LLM_MODEL"'", "messages": [{"role": "user", "content": "Hello"}]}'2Read
Read the 429
A 429 means you hit a limit, not that your code is broken. The response says when to try again:
Retry-Aftergives seconds to wait, and headers likex-ratelimit-remaining-requestsshow what is left. Wait, then retry. Other 4xx errors, such as 400 or 401, will fail the same way every time: do not retry them. A 5xx or a timeout may pass on the next try. SDKs send a retry counter, for example OpenAI'sx-stainless-retry-count; the mock readsX-Retry-Countthe same way.3Code
See the 429 and its headers
1 / 2curl -si "$LLM_BASE_URL/chat/completions" \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $LLM_API_KEY" \ -H "X-Mock-Scenario: rate-limit" \ -d '{"model": "'"$LLM_MODEL"'", "messages": [{"role": "user", "content": "Hello"}]}' | tr -d '\r' | grep -iE '^(HTTP|retry-after|x-ratelimit)'Read the program. What will it print?
4Code
Retry with a wait
1 / 2package main import ( "bytes" "encoding/json" "fmt" "net/http" "os" "strconv" "time" ) func main() { payload, _ := json.Marshal(map[string]any{ "model": os.Getenv("LLM_MODEL"), "messages": []map[string]string{{"role": "user", "content": "Hello"}}, }) const maxAttempts = 4 for attempt := 0; attempt < maxAttempts; attempt++ { req, _ := http.NewRequest("POST", os.Getenv("LLM_BASE_URL")+"/chat/completions", bytes.NewReader(payload)) req.Header.Set("Content-Type", "application/json") req.Header.Set("Authorization", "Bearer "+os.Getenv("LLM_API_KEY")) req.Header.Set("X-Mock-Scenario", "rate-limit") // mock only: remove for a real provider req.Header.Set("X-Retry-Count", strconv.Itoa(attempt)) res, err := http.DefaultClient.Do(req) if err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } if res.StatusCode == http.StatusOK { var out struct { Choices []struct { Message struct { Content string `json:"content"` } `json:"message"` } `json:"choices"` } json.NewDecoder(res.Body).Decode(&out) res.Body.Close() fmt.Println(out.Choices[0].Message.Content) return } res.Body.Close() wait := 500 * time.Millisecond << attempt if secs, err := strconv.Atoi(res.Header.Get("Retry-After")); err == nil { wait = time.Duration(secs) * time.Second } fmt.Printf("attempt %d: %d, waiting %s\n", attempt+1, res.StatusCode, wait) time.Sleep(wait) } fmt.Fprintln(os.Stderr, "gave up") os.Exit(1) }Read the program. What will it print?
5Fix
package main import ( "bytes" "encoding/json" "fmt" "net/http" "os" "time" ) func main() { // The body has no "messages", so the server answers 400 every time. payload, _ := json.Marshal(map[string]any{"model": os.Getenv("LLM_MODEL")}) var status string for attempt := 1; attempt <= 4; attempt++ { req, _ := http.NewRequest("POST", os.Getenv("LLM_BASE_URL")+"/chat/completions", bytes.NewReader(payload)) req.Header.Set("Content-Type", "application/json") req.Header.Set("Authorization", "Bearer "+os.Getenv("LLM_API_KEY")) res, err := http.DefaultClient.Do(req) if err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } status = res.Status var body struct { Error struct { Message string `json:"message"` } `json:"error"` } json.NewDecoder(res.Body).Decode(&body) res.Body.Close() if res.StatusCode == http.StatusOK { fmt.Println("ok") return } time.Sleep(100 * time.Millisecond) } fmt.Fprintln(os.Stderr, "gave up after 4 attempts:", status) os.Exit(1) }6Read
Timeouts and fallback
A request can also hang. Set
http.Client.Timeoutso your program never waits forever. Keep a list of providers, each with its own base URL, key and model, and move to the next one on a timeout or a 5xx. Free tiers make this worth the effort: limits are low and capacity changes. The page/free-api-creditslists free providers you can put in that list.7Code
Fall back to a second provider
1 / 2package main import ( "bytes" "encoding/json" "errors" "fmt" "net" "net/http" "os" "time" ) type provider struct { baseURL, key, model string headers map[string]string } func ask(client *http.Client, p provider) (string, string) { payload, _ := json.Marshal(map[string]any{ "model": p.model, "messages": []map[string]string{{"role": "user", "content": "Hello"}}, }) req, _ := http.NewRequest("POST", p.baseURL+"/chat/completions", bytes.NewReader(payload)) req.Header.Set("Content-Type", "application/json") req.Header.Set("Authorization", "Bearer "+p.key) for k, v := range p.headers { req.Header.Set(k, v) } res, err := client.Do(req) if err != nil { var netErr net.Error if errors.As(err, &netErr) && netErr.Timeout() { return "", "timeout" } return "", "network error" } defer res.Body.Close() if res.StatusCode >= 500 { return "", res.Status } var out struct { Choices []struct { Message struct { Content string `json:"content"` } `json:"message"` } `json:"choices"` } json.NewDecoder(res.Body).Decode(&out) return out.Choices[0].Message.Content, "" } func main() { providers := []provider{ // mock only: the first provider answers slowly {os.Getenv("LLM_BASE_URL"), os.Getenv("LLM_API_KEY"), os.Getenv("LLM_MODEL"), map[string]string{"X-Mock-Scenario": "slow"}}, {os.Getenv("LLM_BASE_URL"), os.Getenv("LLM_API_KEY"), os.Getenv("LLM_MODEL"), nil}, } client := &http.Client{Timeout: 500 * time.Millisecond} for i, p := range providers { reply, problem := ask(client, p) if problem != "" { fmt.Printf("provider %d: %s, trying next\n", i+1, problem) continue } fmt.Println(reply) return } fmt.Fprintln(os.Stderr, "all providers failed") os.Exit(1) }Read the program. What will it print?
8Say it back
9Mission · 15 min
Use your free key from the offer at the top. Remove the X-Mock-Scenario and X-Retry-Count headers, then send requests in a loop until the free tier answers 429 and watch the retry program wait. The real limits and headers will differ from the simulated ones.
export LLM_BASE_URL=<base URL from the offer page> export LLM_MODEL=<model id from the offer page> export LLM_API_KEY=<your key> go run main.go
Free AI API credits to practise with
- AgentRouter Free Credits
Free AI coding credits: $25 per daily check-in and $50 per invite
No cardVerified
- Google Gemini Developer API Free Tier
Free Gemini API tier with rate-limited access to Flash models and Gemini 2.5 Pro
No cardVerified
Common questions
- What does a 429 error mean?
- It means too many requests: you went over a limit such as requests per minute or tokens per minute. It is not a bug in your code. Wait for the time in the Retry-After header, or back off, and send the request again. If it keeps happening, slow your program down, send fewer tokens, or move to a plan with higher limits.
- Which errors should I retry?
- Retry 429, 5xx errors and timeouts, with a short wait and a small cap on attempts. Do not retry other 4xx errors such as 400, 401 or 404, because the request or the key is wrong and will fail again. Add jitter, a little random delay, when many clients may retry together, so they do not all hit the server at once.
- Why fall back to another provider?
- Free tiers have low limits and can slow down or go offline. With a list of providers your program keeps working: it moves on after a timeout or a 5xx. Keep each provider's base URL, key and model together, because model ids differ, and keep prompts plain so any model in the list can answer them.
Sources
- https://platform.openai.com/docs/guides/rate-limits (read 2026-12-03)
- https://platform.openai.com/docs/guides/error-codes (read 2026-12-03)
- https://github.com/openai/openai-python/blob/main/src/openai/_base_client.py (read 2026-12-03)
- https://pkg.go.dev/net/http (read 2026-12-03)
Simulated responses from a local mock server, not from a real model. Run with local mock server (scripts/course-llm-mock.ts), go1.27.4 darwin/arm64, curl on 2026-12-03
Published Dec 3, 2026 · Updated Dec 3, 2026