1. retry を許可できる場面: idempotency とリクエストの意味
retry が開発者の頭に浮かぶのは、ネットワークがネットワークらしく振る舞う瞬間です。つまり、ときどき「くしゃみ」をし、ときどき少し「もたつき」、ときにはサーバーが 1 秒だけ過負荷になる。そこで「じゃあ繰り返せば通るかも」と考えたくなります。もっともらしく聞こえますが、再試行には暗い側面があります。小さな障害を大量のリクエストに変え、慎重なビジネス操作を重複、あるいは三重の重複にしてしまうのです。
単純化すると、retry とは一時的な問題(transient failure)を 自動的に「直そう」とする試みで、再度リクエストを送ります。ただし「一時的」であることが重要です。問題が一時的でない場合、たとえば URL を間違えた、トークンを忘れた、誤った JSON を送っている、といったケースでは、再試行は待ち時間を伸ばすだけで、診断も難しくなります。ユーザーはより長く待たされ、あなたの手元には同じエラーが山積みになります。
さらに重要なのは、retry は クライアントの挙動を変える ことだという点です。つまり「サーバーにもう 1 回リクエストを投げてよいかどうかは、私が決める」と言っているのと同じです。そしてサーバーはそれを歓迎しないかもしれません。
Idempotency: 最重要ルール
「idempotent」という言葉は魔法の呪文のように聞こえますが、意味は単純です。idempotent な操作とは、何度続けて実行しても、最終状態が「増殖」しない操作のことです。
HTTP には昔からの目安があります。GET, HEAD, PUT, DELETE はプロトコル上の意味として idempotent とされ、POST は通常そうではありません。ただし、これは自然法則ではなく慣例です。個別の API には独自の仕様がありえます。
初心者向けの「どう考えるか」簡易表です:
| Method | Usually idempotent? | Default retry? | Why be careful |
|---|---|---|---|
|
yes | sometimes yes | you can hammer the server and create load by yourself |
|
yes | sometimes yes | if you are updating a resource, a repeat is usually safe, but you still need to understand the contract |
|
yes | sometimes yes | a repeated DELETE often returns 404/204 — depends on the API |
|
no | almost never | risk of creating “two identical orders” / “two tasks” |
|
depends | very rarely | often this is a “partial update”; repeating it can be dangerous |
And here is the important psychological trap: a beginner thinks retry means “make it more reliable.” In reality, retry always trades one risk for another: you reduce the chance of failure during a short network glitch, but increase the risk of duplicates, overload, and difficult debugging.
3. Retry limiters: budget, count, delays
Retry budget: total timeout matters more than “smart backoff”
There is a whole zoo of backoff strategies: fixed delay, exponential, with jitter, with a maximum cap, with separate budgets by phase (DNS/TLS/…).
But at our level, the important thing now is not the “smartest strategy,” but the time boundary. A good retry always has a budget: “we are ready to spend no more than N seconds on this operation.” And the easiest way to express that is through context.WithTimeout, because then any code inside the request gets a single cancellation signal.
This pairs nicely with the basic idea of net/http: the request is created with a context (NewRequestWithContext), and Client.Do respects that context for the lifetime of the request.
Mini example: “one budget for everything, including retries”:
package main
import (
"context"
"time"
)
func withRetryBudget(parent context.Context) (context.Context, context.CancelFunc) {
return context.WithTimeout(parent, 1200*time.Millisecond)
}
The idea is simple: no matter how many times you try again, when the budget is gone, that’s it — we close the shop.
Attempt limit: no infinite retries
If retry has no limit on the number of attempts, you get an infinite loop that “sometimes” ends. That is very romantic, but in production it usually ends with someone running out of memory, patience, or API gateway request quota.
We need at least a fixed number of attempts. For a beginner, this is usually 2–3. Not 10 and not “until it works.”
Short skeleton:
package main
func attempts() int {
return 3
}
Yes, it looks funny, but this is exactly the right way to think: retries are a small number, not “let’s keep hammering until the server gives up.”
4. What to retry: transport vs non-2xx
It is very important to distinguish two classes of problems.
Transport errors are when the request was not actually completed properly at all: connection failed, connection broke, DNS, timeout, and so on. It is like “I couldn’t get through by phone.” In Go, this usually appears as err != nil from client.Do(req).
Contract errors are when you did get a response, but it says: “no,” “validation error,” “not found,” “internal server error.” This is not transport. This is a semantic branch: resp != nil, err == nil, but resp.StatusCode is not 2xx.
In previous topics we mentioned that some network errors in Go can carry additional signals (for example, Timeout()/Temporary() on net.Error), and clients sometimes decide to “sleep and retry” if the error is temporary. That is exactly transport-level behavior.
But for non-2xx, retries should be enabled only if you have a clear agreement with the API. For example, a 503 may sometimes mean “try again later,” but that is the policy of a specific service. If you simply start retrying all 500s, you risk hammering the server even harder.
The most expensive mistake: forgetting to close resp.Body
This section is like the reminder “fasten your seat belt,” only in the world of HTTP.
If client.Do(req) returned resp and err == nil, then resp.Body must be closed always, even if StatusCode is bad. And it is especially important to close Body if you decide to retry based on status, because otherwise you create connection leaks and mysterious “everything froze after 5 minutes.”
The right mental model: each attempt has its own resp, and its body must be closed if you are not returning that resp to the caller.
Mini template:
package main
import "net/http"
func closeBody(resp *http.Response) {
if resp != nil && resp.Body != nil {
resp.Body.Close()
}
}
5. Retry loop diagram
When code starts “jumping” between errors, pauses, and context exits, it is easy to get lost. So it helps to keep one simple algorithm in mind:
flowchart TD
A[Start] --> B[Check ctx.Err]
B -->|canceled/deadline| Z[Return ctx error]
B --> C[Build request]
C --> D[Do request]
D -->|err != nil| E[Retry? transport]
D -->|err == nil| F[Check StatusCode]
F -->|2xx| Y[Success: return resp]
F -->|non-2xx| G[Retry? contract]
E -->|no| X[Return error]
G -->|no| X2[Return status error]
E -->|yes| H[Sleep/backoff]
G -->|yes| H
H --> B
This is not the “only correct” version, but as a reference map for a beginner it is excellent.
6. Example: a retry helper for GET in a training task client
Let’s imagine we have a training application: a CLI/client that reads tasks from a server via GET /api/v1/tasks. We want retries only for GET, and only for transport errors (no status-based retries, so we do not hide server problems).
Mini client: base URL and http.Client
First, let’s make a small client with a base URL and http.Client.
package main
import "net/http"
type TaskClient struct {
BaseURL string
HTTP *http.Client
}
One request attempt
Now a function that makes one request attempt. We intentionally keep it small: it creates a request with a context, calls Do, and returns resp as-is (the outer code will decide what to do next and close it).
package main
import (
"context"
"net/http"
)
func (c *TaskClient) doGet(ctx context.Context, url string) (*http.Response, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return nil, err
}
req.Header.Set("Accept", "application/json")
return c.HTTP.Do(req)
}
Retry parameters: attempts and delay
Let’s add the retry loop itself. Pay attention to the discipline: we always check ctx.Err() before a new attempt, always limit the number of attempts, and add a small delay.
package main
import (
"context"
"time"
)
func retryDelay(attempt int) time.Duration {
return 200 * time.Millisecond // fixed, no “smart tricks”
}
func retryAttempts() int {
return 3
}
Main loop
It is a bit longer than 10 lines, but we will try to keep it as straightforward as possible so it reads like a story, not a puzzle.
package main
import (
"context"
"fmt"
"net/http"
"time"
)
func (c *TaskClient) GetWithRetry(ctx context.Context, url string) (*http.Response, error) {
var lastErr error
for attempt := 1; attempt <= retryAttempts(); attempt++ {
if err := ctx.Err(); err != nil {
return nil, err
}
resp, err := c.doGet(ctx, url)
if err == nil {
return resp, nil // caller must Close()
}
lastErr = err
time.Sleep(retryDelay(attempt))
}
return nil, fmt.Errorf("get failed after retries: %w", lastErr)
}
Here we wrapped the error with %w to preserve the original cause (for example, context.DeadlineExceeded or a network error) and give the caller a chance to check it via errors.Is. The %w format itself is the standard Go way to wrap errors.
Important: we do not retry POST /api/v1/tasks (task creation). Why? Because creation is almost always non-idempotent: you risk creating two identical tasks. Yes, sometimes this is solved with idempotency keys, but that is a separate topic and a separate API contract, not something “by default in the client.”
7. How to tell whether an error can be retried
Retrying everything is a bad idea. But forbidding retries entirely is also often an overreach. So we need a simple filter. At our level we will do this conservatively: retry only transport errors, and only those that look “temporary.”
In Go there is a historically important idea: some network errors implement the net.Error interface with the Timeout() and Temporary() methods, and a client can use type assertion to determine whether the error is temporary.
Mini check:
package main
import "net"
func isTemporary(err error) bool {
nerr, ok := err.(net.Error)
return ok && (nerr.Timeout() || nerr.Temporary())
}
And this is where real engineering begins: not every error will be a net.Error, and Temporary() in real life does not always mean “you can safely hammer again.” So the practical rule for a beginner is: if you are not sure, do not retry automatically. Better to return the error to the user/upstream than to create a request storm.
8. Retry and timeout: who wins
When we have both time.Sleep between attempts and a shared context.WithTimeout, the situation can arise where we are “sleeping” while the context has already ended. In the code above we check ctx.Err() at the beginning of the loop — that is good, but if time.Sleep is long, we will still “sleep through” part of the time after cancellation.
In practice, for cleanliness, people often use waiting that respects context instead of time.Sleep (via time.NewTimer and select), but we do not want to go deep into concurrency here. So for now we keep a simple discipline: delays should be short, attempts should be few, and a total timeout is mandatory.
If you want to make it “a little better” while still keeping it simple, you can at least cap the delay by the remaining budget. That would already look more complex, so for a basic course the rules above are enough.
9. Typical mistakes
Mistake #1: retrying POST “because the network is unreliable.”
In practice, this is one of the most dangerous bugs: you can create duplicate entities (two tasks, two orders, two payments). If you cannot formally prove the operation is idempotent according to the API contract, it is better not to implement automatic retry for POST at all.
Mistake #2: retries without a shared timeout.
This creates a situation where “each attempt waits 2 seconds,” and there are 5 attempts, so the user waits 10 seconds. It is much clearer to have one context.WithTimeout for the whole operation so the behavior is predictable.
Mistake #3: infinite attempts or too high a limit.
If your code tries to “push through” the network at any cost, you risk hanging forever or causing a DoS against yourself. For a beginner, a safe default is 2–3 attempts. Anything above that should be justified by measurements and an understanding of the load.
Mistake #4: not closing resp.Body before the next attempt.
If you decide to retry based on status (or even just on an error, but resp is not nil), and you do not close the body, you get resource leaks and strange hangs caused by exhausting connections. As soon as resp is obtained, Body.Close() must be either in defer (when you return resp to the caller) or called manually before retry.
Mistake #5: retrying contract errors that retries cannot fix.
401/403/400 will not become better because of repeats. This is not a “temporary network glitch,” but a request or authorization error. Repeating only increases latency and pollutes logs.
GO TO FULL VERSION