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-key

Mistral AI Free Plan: what is free and how to get a key

  1. 1Guess

    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?
  2. 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-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.

  3. 3Code

    See the 429 and its headers

    1 / 2
    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)'
    

    Read the program. What will it print?

  4. 4Code

    Retry with a wait

    1 / 2
    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)
    }
    

    Read the program. What will it print?

  5. 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)
    }
    
    The program sends the same request four times and gives up. What is wrong?
  6. 6Read

    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.

  7. 7Code

    Fall back to a second provider

    1 / 2
    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)
    }
    

    Read the program. What will it print?

  8. 8Say it back

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

  1. AgentRouter Free Credits

    Free AI coding credits: $25 per daily check-in and $50 per invite

    No cardVerified

  2. Google Gemini Developer API Free Tier

    Free Gemini API tier with rate-limited access to Flash models and Gemini 2.5 Pro

    No cardVerified

  3. Groq Free Tier

    Free rate-limited Groq API access to hosted open models, no card

    No cardVerified

All free ai api credits →

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

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

Never miss new offers and news

New tools, credits, and AI news are added regularly. Pick how you want to hear about them.

Telegram channel

Join @aifree_dev and get new free AI offers and news right in your Telegram feed.

Browser notifications

Turn on push notifications and get an alert on this device whenever something new is posted. No account needed.

Email newsletter

A weekly digest of new, changed and expiring free AI offers. Double opt-in, one-click unsubscribe. See the latest issue.

Unsubscribe anytime. Privacy

Frequently asked questions

What is aifree.dev?

aifree.dev helps everyone access AI through a curated directory of free AI tools, API credits, free tiers, and startup programs for coding, image, voice, video, and students - verified regularly.

How are offers presented?

Each offer includes its access details, free models when available, and expiration information when provided. Limited-time deals stay visible so they are easy to compare.

Do education and startup programs need verification?

Yes. Providers usually ask students to verify their status with a school email, student ID, or a program like the GitHub Student Pack, and ask startups to verify company details such as age, funding, or website. Check each offer’s claim page for the exact requirements.

What kinds of free AI offers are listed?

Free tiers and free trials from AI providers, free API credits, startup and student programs, and free tools for coding, image generation, voice, and video.

How can I suggest a tool or report a broken link?

Use the submit form: paste the offer page URL and a short note. A person checks every submission before anything is listed. Broken links and changed terms go through the same form.

Know a good one?

Tell us about an AI tool worth knowing. Found a broken link? We want to hear that too.

Submit an offer