Error Handling and Retry Logic
Checking status codes and implementing retries
Error Handling and Retry Logic is a free Go Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Go Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
HTTP errors are not Go errors
An HTTP 404 or 500 status is not a Go error — http.Client.Do returns nil error for any valid HTTP response. Check resp.StatusCode explicitly.
Wrapping errors
Wrap errors with context using fmt.Errorf("operation: %w", err) so callers can inspect the cause with errors.Is / errors.As.
if err != nil {
return fmt.Errorf("fetch users: %w", err)
}Retryable vs non-retryable errors
Retry: network timeouts, 429 Too Many Requests, 503 Service Unavailable. Do not retry: 400 Bad Request, 401 Unauthorized, 404 Not Found — retrying won't help.
Exponential back-off
Wait longer between each retry to reduce load on a struggling server. A simple implementation:
for i := 0; i < maxRetries; i++ {
resp, err := client.Do(req)
if err == nil && resp.StatusCode < 500 { break }
time.Sleep(time.Duration(math.Pow(2, float64(i))) * time.Second)
}Jitter
Add random jitter to back-off to prevent multiple clients from retrying simultaneously (thundering herd).
wait := time.Duration(math.Pow(2, float64(i)))*time.Second + time.Duration(rand.Intn(1000))*time.MillisecondRetry-After header
The 429 response often includes a Retry-After header. Parse and respect it instead of using a fixed back-off.
retryAfter := resp.Header.Get("Retry-After")
if secs, err := strconv.Atoi(retryAfter); err == nil {
time.Sleep(time.Duration(secs) * time.Second)
}Context-aware retries
Check the context before each retry attempt to stop retrying if the request was cancelled.
for i := 0; i < maxRetries; i++ {
if ctx.Err() != nil { return nil, ctx.Err() }
// attempt
}Custom error types
Define typed HTTP errors to carry the status code and body, enabling callers to make fine-grained retry decisions.
type HTTPError struct {
Status int
Body string
}
func (e *HTTPError) Error() string { return fmt.Sprintf("HTTP %d: %s", e.Status, e.Body) }Library options
Consider hashicorp/go-retryablehttp or cenkalti/backoff for production retry logic with configurable back-off policies, max retries, and context support.
Idempotency keys
For retried POST requests, include an idempotency key (UUID) header so the server deduplicates retries and returns the same result without creating duplicate resources.
Circuit breaker
A circuit breaker tracks failure rates and stops sending requests to a failing service for a cooldown period. Libraries like sony/gobreaker implement this pattern.
Quick Check
Why should you add jitter to exponential back-off?
Recap: Error Handling and Retry
Key points:
- Check resp.StatusCode — HTTP errors are not Go errors
- Retry on 429, 503 and network timeouts; not on 4xx client errors
- Exponential back-off + jitter prevents thundering herd
- Always check context before retrying
Frequently asked questions
Is the “Error Handling and Retry Logic” lesson free?
Yes — the full text of “Error Handling and Retry Logic” is free to read here on the web, and the Go Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Go Academy course, upgrade to CoddyKit PRO.
What will I learn in “Error Handling and Retry Logic”?
Checking status codes and implementing retries You practise Go Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Go Academy?
No prior experience is required. Go Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Error Handling and Retry Logic” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Go Academy lesson?
Yes. Every Go Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Making HTTP Requests
- Setting Timeouts and Headers
- Decoding JSON Responses
- Error Handling and Retry Logic