By Abhijith N M · Reviewed 24 October 2026 · Editorial standards
Relay's CLI and tests talk to its own API, and that client has the same failure modes as any external dependency: slow responses, transient 5xx errors, malformed JSON and deadlines. This lab builds a fetchStats function that retries transient failures with backoff, decodes strictly, caps the response size and never outlives the caller's context.
The lab's server is a flaky httptest server that fails twice and then succeeds. The point is not to make the server stable; it is to prove the client behaves predictably when it is not. Count the attempts, assert the decoded result and keep the total time under the context deadline.
http.Client with a timeout instead of using the default client.http.NewRequestWithContext so cancellation propagates.package main
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"sync/atomic"
"time"
)
type stats struct {
Service string `json:"service"`
Total int `json:"total"`
}
func fetchStats(ctx context.Context, client *http.Client, url string) (stats, error) {
var lastErr error
backoff := 10 * time.Millisecond
for attempt := 1; attempt <= 3; attempt++ {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return stats{}, err
}
resp, err := client.Do(req)
if err != nil {
lastErr = err
} else {
payload, readErr := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
resp.Body.Close()
switch {
case readErr != nil:
lastErr = readErr
case resp.StatusCode == http.StatusOK:
var result stats
if err := json.Unmarshal(payload, &result); err != nil {
return stats{}, fmt.Errorf("decode stats: %w", err)
}
return result, nil
case resp.StatusCode >= 500:
lastErr = fmt.Errorf("server returned %d", resp.StatusCode)
default:
return stats{}, fmt.Errorf("unexpected status %d", resp.StatusCode)
}
}
if attempt < 3 {
time.Sleep(backoff)
backoff *= 2
}
}
return stats{}, fmt.Errorf("stats unavailable after retries: %w", lastErr)
}
func main() {
var attempts atomic.Int64
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
if attempts.Add(1) < 3 {
w.WriteHeader(http.StatusServiceUnavailable)
return
}
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"service":"api","total":2}`))
}))
defer server.Close()
client := &http.Client{Timeout: 2 * time.Second}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
result, err := fetchStats(ctx, client, server.URL)
fmt.Println("attempts:", attempts.Load())
fmt.Println("result:", result.Service, result.Total)
fmt.Println("error:", err != nil)
}| Client concern | Implementation | Failure it prevents |
|---|---|---|
| No hanging calls | http.Client{Timeout: ...} | A stalled peer pinning a handler |
| Caller cancellation | NewRequestWithContext | Work continuing after the request is gone |
| Transient errors | Retry 5xx with capped backoff | A blip becoming a user-visible error |
| Non-retryable errors | Fail fast on 4xx | Hammering a server that will keep refusing |
| Memory safety | io.LimitReader | A huge response exhausting memory |
| Connection reuse | Close and drain the body | Leaked connections and file descriptors |
Key takeaways
An HTTP client is part of the service and needs timeouts, limits and retry policy.
Use request contexts so caller cancellation propagates to the transport.
Retry transport errors and 5xx only; fail fast on 4xx.
Close bodies, bound reads and decode into typed structs.
Return wrapped, structured errors so callers can decide what to do.
Written and edited by the nexGenCoders team. Spotted a mistake? Tell us and we will fix it.
Don't lose this lesson
Create a free account to save your progress, keep your streak, and work toward a shareable certificate.