Why should Go’s http.Client instances be reused?

1.9k Views Asked by At

The Go documentation says

The Client's Transport typically has internal state (cached TCP connections), so Clients should be reused instead of created as needed. Clients are safe for concurrent use by multiple goroutines.

Why does Client reuse help with preserving the Transport’s internal state, given that I can instantiate a transport and pass it to single-use Client instances like this:

client := &http.Client{Transport: transport}
2

There are 2 best solutions below

5
Jonathan Hall On

Why should Go’s http.Client instances be reused?

There are many reasons. The most universal one is to allow reusing existing HTTP connections. If you use a new http.Client instance for every request, you can never take advantage of existing HTTP connections, which will result in more overhead and slower performance for most common uses.

Another common reason would be to use a cookie jar, if you're calling an HTTP server that uses cookies.

0
sayap On

The consul-k8s project actually does this, by creating many short-lived Client instances, all sharing the same Transport. This was done in https://github.com/hashicorp/consul-k8s/commit/5672d344, perhaps accidentally as the PR just said:

Minor change to how we deal with consul clients in the endpoints controller+tests.

Prior to this minor change, it creates a new Transport every time (and thus leaks plenty of connections):

localConfig := api.DefaultConfig()

After the change, it reuses the same Transport:

localConfig := r.ConsulClientCfg

The leaky version never made it into any actual release, so it is all good.