Articles / Go

  • go
  • timeouts
  • api-design
  • reliability
  • net-http
  • distributed-systems

Your API Request Timed Out. It May Still Have Worked

You send a payment request, wait, and get context deadline exceeded. Did the payment happen? You do not know, and no amount of staring at the error will tell you.

A timeout only tells you how long you were prepared to wait. The server never agreed to that limit, may not have noticed you leaving, and may have committed the transaction while your error was still being logged.

Reproducing it takes about thirty lines

Here is a slow server, and a client that gives up first. The send function comes in a moment, and imports are left out.

func main() {
	var payments atomic.Int32
	finished := make(chan struct{})
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		defer close(finished)
		io.Copy(io.Discard, r.Body)
		time.Sleep(200 * time.Millisecond) // a slow database, say
		payments.Add(1)
		w.WriteHeader(http.StatusCreated)
	}))
	defer srv.Close()

	ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
	defer cancel()
	req, err := http.NewRequestWithContext(ctx, http.MethodPost,
		srv.URL+"/payments", strings.NewReader(`{"pence":500}`))
	if err != nil {
		panic(err)
	}

	outcome, err := send(srv.Client(), req)
	fmt.Println("client:", outcome, err)
	<-finished
	fmt.Println("server payments:", payments.Load())
}

The client reports failure and the server records one payment. Both are behaving correctly.

Go does cancel the server's r.Context() when it notices the client has gone, but cancelling only asks the handler to stop and rolls nothing back. This handler never checks. A handler that does check can still be told a moment after its database commit.

Where it timed out decides what you know

A request can stall at several points, and each leaves you knowing something different:

  • Before you had a connection (DNS, TCP connect, TLS handshake): the request never left. Nothing happened because of this call.
  • While sending: the server might have received all, some or none of it.
  • While waiting for the response: the server may be queueing, working or finished.
  • While reading the response body: you have a status code, but perhaps not the ID of the thing you created.

Only the first is safely a "no". Treat everything after it as unknown, which is a third result alongside success and failure.

Make "unknown" a value your code can return

Go's net/http/httptrace can tell you whether the request ever obtained a connection. If GotConn never fired, there was nowhere to write the request.

type Outcome string

const (
	Done     Outcome = "done"
	Rejected Outcome = "rejected"
	NotSent  Outcome = "not sent"
	Unknown  Outcome = "unknown"
)

func send(client *http.Client, req *http.Request) (Outcome, error) {
	var gotConn atomic.Bool
	trace := &httptrace.ClientTrace{
		GotConn: func(httptrace.GotConnInfo) { gotConn.Store(true) },
	}
	req = req.WithContext(httptrace.WithClientTrace(req.Context(), trace))

	resp, err := client.Do(req)
	if err != nil {
		if !gotConn.Load() {
			return NotSent, err
		}
		return Unknown, err
	}
	defer resp.Body.Close()

	switch resp.StatusCode {
	case http.StatusOK, http.StatusCreated:
		return Done, nil
	case http.StatusBadRequest, http.StatusUnauthorized,
		http.StatusForbidden, http.StatusUnprocessableEntity:
		return Rejected, fmt.Errorf("refused: %s", resp.Status)
	default:
		return Unknown, fmt.Errorf("ambiguous: %s", resp.Status)
	}
}

I ran the reproduction with Go 1.27.4. It prints client: unknown with the deadline error, then server payments: 1. Pointed at a closed port instead, send returns not sent.

The check is deliberately pessimistic. Getting a connection does not prove any bytes arrived, and a redirect or internal retry that fails later still leaves the flag set. Erring towards "unknown" costs you a lookup; erring the other way can cost someone five pounds twice.

The status codes need the same suspicion. A 504 Gateway Timeout means a proxy gave up waiting for the thing behind it, which may still be working. The "rejected" list assumes your API refuses those requests before doing any work, so check that it does.

A rejection also only describes the attempt that received it. If attempt one was unknown and attempt two gets a 401 because your token expired, attempt one is still unknown.

Quick detour: Go may already be retrying for you

This bit is interesting. Go's Transport documentation says it retries some requests after network errors, when a previously used connection fails and the request is idempotent with a replayable body (or none).

"Idempotent" includes GET, HEAD, OPTIONS and TRACE, but also any request carrying an Idempotency-Key or X-Idempotency-Key header. So adding that header is a promise to your own HTTP client, as well as to the server. If the server ignores the header, you have promised something untrue.

This is a separate, quieter mechanism, and it does not retry after your deadline expires. Right, back to the missing payment.

Ask what happened before doing it again

To look something up you need a name for it that you knew before the response arrived. A server-generated ID is no use, since it was in the reply you never got.

So the order of work is:

  1. Generate a unique reference for the operation.
  2. Save it, with the intended action and a pending state, in your own durable storage.
  3. Send the request with that reference.
  4. If the outcome is unknown, query the API by reference, with backoff and an overall limit.
  5. Record the answer, or leave it marked unknown for something else to resolve.

Step two matters because your process can die between sending and receiving, leaving the same ambiguity with no error message at all. On restart, anything still pending needs looking up.

The trap is a lookup that returns "not found", because that only means not found yet. Your original request could still be sitting in a queue, ready to run just after you checked.

Resending is therefore safe only if the server guarantees that the same reference cannot create a second effect. Without that guarantee, check-then-resend merely makes the duplicate rarer and harder to reproduce.

What the retry rules depend on

RFC 9110 says a client should not automatically retry a non-idempotent request unless it knows the operation is really idempotent, or can detect that the original was never applied. In practice:

  • Not sent: retry with backoff.
  • Unknown, and the operation is idempotent: retry with the same inputs, within a limit.
  • Unknown, with a documented idempotency key: retry with the same key and the same body. A fresh key means a fresh operation.
  • Unknown, with only a status lookup: look it up, and do not treat absence as permission to resend.
  • Unknown, with neither: do not retry automatically. Flag it for reconciliation against statements, exports or a human at the other end.

Read the provider's rules on keys, including how long they are remembered. A retry from a queue three days later may be outside that window. The Idempotency-Key header also has no RFC yet; it is still an IETF draft, so do not assume two APIs treat it alike.

If you own the API, give callers a way out

The client cannot solve this alone. A server can help by offering:

  • A client-chosen reference with a uniqueness constraint, scoped to the account.
  • An endpoint that reports an operation's state by that reference.
  • 202 Accepted and a status URL for slow work, instead of holding the connection open. The caller can still lose the 202, so the reference is still needed.
  • Documentation saying how long references are kept and what a repeat returns.

Raising the client timeout is worth doing if it is shorter than the server's normal slow requests, but it only makes the unknown case less frequent. A network can still drop the reply to a request that succeeded in 3 ms.

Finally, tell your users the truth. With "Payment failed, please try again", you are instructing them to create a duplicate. "We are checking whether this went through" is less satisfying and far more accurate.