---
title: "Survive rate limits, timeouts and a provider that is down"
slug: "errors-and-rate-limits"
description: "Read a 429 and its headers, retry with a wait, stop on errors that will not fix themselves, and fall back to another provider on a timeout."
published: "2026-12-03"
updated: "2026-12-03"
canonical: "https://aifree.dev/courses/learn-llm/errors-and-rate-limits"
---

# Survive rate limits, timeouts and a provider that is down

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.

```sh
export LLM_BASE_URL=https://api.mistral.ai/v1
export LLM_MODEL=mistral-large-4
export LLM_API_KEY=your-key
```

[Mistral AI Free Plan: what is free and how to get a key](https://aifree.dev/offer/mistral-ai-free-plan)

## Predict

```sh
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"}]}'
```

A free tier allows two requests a minute and you send a third. Which HTTP status do you get?

- 401
- 429
- 500

Answer: 429 — 429 Too Many Requests is the status for a limit you hit, and it is the one to expect on a free tier.

Output:

```
429
```

_Simulated response (local mock server), 2026-12-03._

The header `X-Mock-Scenario` exists only on the mock server, which answers 429 on request. Remove it when you call a real provider.

## Read the 429

A 429 means you hit a limit, not that your code is broken. The response says when to try again: `Retry-After` gives seconds to wait, and headers like `x-ratelimit-remaining-requests` show 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's `x-stainless-retry-count`; the mock reads `X-Retry-Count` the same way.

## See the 429 and its headers

```sh
curl -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)'
```

Output:

```
HTTP/1.1 429 Too Many Requests
retry-after: 1
x-ratelimit-limit-requests: 2
x-ratelimit-remaining-requests: 0
```

_Simulated response (local mock server), 2026-12-03._

The mock sends these headers on purpose. Real providers use similar names, but check the documentation of yours.

## Retry with a wait

```go
package 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)
}
```

Output:

```
attempt 1: 429, waiting 1s
attempt 2: 429, waiting 1s
Hello! How can I help you today?
```

_Simulated response (local mock server), 2026-12-03._

The loop makes at most four attempts. It waits what `Retry-After` says, and falls back to exponential backoff when the header is missing. It takes about two seconds to run.

## Fix it

```go
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)
}
```

The program sends the same request four times and gives up. What is wrong?

- It retries a 400, which can never succeed
- It waits too little between attempts
- It should try five times, not four

Answer: It retries a 400, which can never succeed — A 400 means the request itself is wrong. Sending it again wastes calls and your allowance.

Error message:

```
gave up after 4 attempts: 400 Bad Request
```

Fixed:

```go
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
		}
		if res.StatusCode >= 400 && res.StatusCode < 500 && res.StatusCode != http.StatusTooManyRequests {
			fmt.Printf("not retrying: %s: %s\n", status, body.Error.Message)
			return
		}
		time.Sleep(100 * time.Millisecond)
	}
	fmt.Fprintln(os.Stderr, "gave up after 4 attempts:", status)
	os.Exit(1)
}
```

Output:

```
not retrying: 400 Bad Request: messages is required
```

_Simulated response (local mock server), 2026-12-03._

## Timeouts and fallback

A request can also hang. Set `http.Client.Timeout` so 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-credits` lists free providers you can put in that list.

## Fall back to a second provider

```go
package 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)
}
```

Output:

```
provider 1: timeout, trying next
Hello! How can I help you today?
```

_Simulated response (local mock server), 2026-12-03._

Both entries here use the same environment variables, and the first is slowed on purpose. In real use they point to two different providers.

## Say it back

In your own words: which errors do you retry, how long do you wait, and when do you switch provider?

Our sentence: I retry a 429, a 5xx and a timeout, a few times at most, waiting what Retry-After says or backing off. I do not retry other 4xx errors, because the request is wrong. After a timeout or a 5xx I move to the next provider on my list.

## Mission (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.

```sh
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
```

## 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.
