Skip to content

Timeouts

Every external call needs a deadline. Default HTTP clients in Go and Rust ship without one.

External I/O (HTTP requests, database queries, DNS lookups) can block indefinitely if the remote end is slow, hung, or gone. Without a timeout, a caller that never returns holds a goroutine (or an OS thread), a connection from the pool, and anything waiting on it. Under load this cascades: a single slow downstream turns into a wall of stalled requests and an OOM kill.

The fix is mechanical. Set a deadline on every outbound call. The hard part is remembering to do it at all, because the defaults in both languages are wrong.

Go

The http.DefaultClient problem

http.DefaultClient has a Timeout of zero, which means no timeout. A GET to a host that accepts the TCP connection but never sends a response will hang forever:

// Hangs indefinitely if the server stops sending bytes.
resp, err := http.Get("https://example.com/slow-endpoint")

Same applies to any code that uses the package-level helpers (http.Get, http.Post, http.Head); they all delegate to http.DefaultClient.

Building a client with a timeout

Create your own http.Client and keep it as a long-lived value (it manages a connection pool; creating one per request is wasteful):

var httpClient = &http.Client{
    Timeout: 10 * time.Second,
}

Timeout is the total time from sending the request to finishing the response body read. It is the single most important knob because it caps the worst-case wall time regardless of what the server does.

Transport-level knobs

http.Client.Timeout is coarse. For more control, set individual deadlines on the Transport:

var httpClient = &http.Client{
    Timeout: 30 * time.Second,
    Transport: &http.Transport{
        DialContext: (&net.Dialer{
            Timeout:   5 * time.Second, // TCP connection establishment
            KeepAlive: 30 * time.Second,
        }).DialContext,
        TLSHandshakeTimeout:   5 * time.Second,
        ResponseHeaderTimeout: 10 * time.Second, // time to receive first response byte
        IdleConnTimeout:       90 * time.Second,
        MaxIdleConns:          100,
        MaxIdleConnsPerHost:   10,
    },
}
Field What it covers
Dialer.Timeout TCP handshake (not yet talking to the application)
TLSHandshakeTimeout TLS negotiation on top of the TCP connection
ResponseHeaderTimeout Time from sending the request to reading headers
IdleConnTimeout How long an idle connection stays in the pool
Client.Timeout Total end-to-end deadline including the body read

Set Client.Timeout to the highest value you’re willing to wait end-to-end, then use the transport fields to bound individual phases. A request that stalls during the TLS handshake should not burn the full 30-second client timeout.

Context-based timeouts

context.WithTimeout attaches a deadline to a context and cancels it when the deadline passes. Use it when the timeout must be shorter than the client-level default. An API handler with an SLA has less budget than the client was configured with:

func fetchUser(ctx context.Context, id string) (*User, error) {
    ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
    defer cancel() // always cancel to release the timer

    req, err := http.NewRequestWithContext(ctx, http.MethodGet,
        "https://users.internal/users/"+id, nil)
    if err != nil {
        return nil, err
    }

    resp, err := httpClient.Do(req)
    if err != nil {
        return nil, err
    }
    defer resp.Body.Close()
    // ...
}

http.NewRequestWithContext wires the context into the request. When the context deadline fires, the in-flight request is cancelled and Do returns an error immediately. The pattern works for any downstream call that accepts a context.Context: database drivers, gRPC stubs, cloud SDK clients.

Checking for timeout errors

resp, err := httpClient.Do(req)
if err != nil {
    if errors.Is(err, context.DeadlineExceeded) {
        // context deadline fired
    }
    // Also check for url.Error wrapping the context error:
    var urlErr *url.Error
    if errors.As(err, &urlErr) && urlErr.Timeout() {
        // client-level Timeout fired
    }
    return nil, err
}

Both context.DeadlineExceeded and a wrapped url.Error with Timeout() == true can appear depending on which deadline fires first. Handle both, or treat any error from Do as fatal and let the caller decide.


Rust (tokio)

tokio::time::timeout

The standard building block. It wraps any future with a deadline and returns Err(Elapsed) if the future doesn’t complete in time:

use std::time::Duration;
use tokio::time::timeout;

async fn fetch_data(url: &str) -> anyhow::Result<String> {
    let result = timeout(Duration::from_secs(10), do_fetch(url)).await;

    match result {
        Ok(Ok(body)) => Ok(body),
        Ok(Err(e)) => Err(e),           // the future itself failed
        Err(_elapsed) => Err(anyhow::anyhow!("request timed out after 10s")),
    }
}

timeout composes with any async call: HTTP requests, database queries, channel receives, file reads. It is the primitive everything else is built on.

reqwest with per-client and per-request timeouts

reqwest ships with no default timeout. Like Go’s http.DefaultClient, a Client::new() will wait forever:

// No timeout: hangs if the server stalls.
let body = reqwest::get("https://example.com/slow").await?;

Build a client with explicit limits and reuse it for the lifetime of the program:

use std::time::Duration;
use reqwest::Client;

fn build_client() -> Client {
    Client::builder()
        .timeout(Duration::from_secs(30))         // total request + body read
        .connect_timeout(Duration::from_secs(5))  // TCP + TLS handshake
        .build()
        .expect("failed to build HTTP client")
}

For a tighter deadline on a specific call, wrap it with tokio::time::timeout or use reqwest’s per-request override:

use std::time::Duration;

let response = client
    .get("https://users.internal/users/42")
    .timeout(Duration::from_secs(5))  // overrides the client-level default
    .send()
    .await?;

Propagating cancellation with CancellationToken

When you have structured concurrency (e.g., an axum handler that should stop work when the client disconnects), propagate a CancellationToken rather than relying solely on wall-clock timeouts:

use tokio_util::sync::CancellationToken;
use tokio::time::{timeout, Duration};

async fn handler(token: CancellationToken) -> anyhow::Result<String> {
    tokio::select! {
        result = timeout(Duration::from_secs(5), do_work()) => {
            result?.map_err(Into::into)
        }
        _ = token.cancelled() => {
            Err(anyhow::anyhow!("cancelled by caller"))
        }
    }
}

select! races the timeout future against the cancellation signal. Whichever fires first wins; the other branch is dropped and its resources freed.


Beyond HTTP

The same discipline applies to every blocking call that crosses a process or machine boundary.

I/O type Go Rust (tokio)
HTTP http.Client{Timeout: …} + ctx Client::builder().timeout(…)
SQL (stdlib / sqlx) db.QueryContext(ctx, …) timeout(dur, query).await
gRPC ctx with deadline passed to stub timeout on the tonic future
Redis / cache client.Do(ctx, …) timeout wrapping the command future
DNS net.Resolver{…} with DialContext Handled by the async runtime resolver

The pattern is always the same: establish a deadline before the call, not after it hangs.

A fired timeout is one category of error worth retrying. See Retries for the backoff strategy and which errors are safe to retry.

Type to search…

↑↓ navigate↵ selectEsc close