Skip to content

Connection Pool and Proxy

Connection Pool Configuration

Connection pools are a key factor in HTTP client performance. HTTPC uses ConnectionConfig to manage connection pools.

go
cfg := httpc.DefaultConfig()

// Connection pool parameters
cfg.Connection.MaxIdleConns = 100         // Global max idle connections
cfg.Connection.MaxConnsPerHost = 20       // Max connections per host
cfg.Timeouts.IdleConn = 120 * time.Second // Idle connection keep-alive

Parameter Description

ParameterDefaultDescription
MaxIdleConns50Global max idle connections
MaxConnsPerHost10Max connections per host (including active + idle)
IdleConn90sIdle connection timeout; closed after expiry
Dial10sConnection establishment timeout
TLSHandshake10sTLS handshake timeout
ResponseHeader0Disabled (uses Request timeout)

Scenario Recommendations

ScenarioMaxIdleConnsMaxConnsPerHostIdleConn
High-concurrency API10020120s
General service501090s
Low-frequency requests10230s
Internal microservices501060s

TIP

MaxConnsPerHost includes both active and idle connections. New requests exceeding this limit queue until a connection is released.

Proxy Configuration

Manual Proxy

go
cfg := httpc.DefaultConfig()
cfg.Connection.ProxyURL = "http://proxy.example.com:8080"

client, _ := httpc.New(cfg)

Proxy with Authentication

go
cfg := httpc.DefaultConfig()
cfg.Connection.ProxyURL = "http://user:[email protected]:8080"

TIP

Config.String() automatically masks the username and password in proxy URLs.

SOCKS5 Proxy

go
cfg := httpc.DefaultConfig()
cfg.Connection.ProxyURL = "socks5://proxy.example.com:1080"

System Proxy Auto-Detection

go
cfg := httpc.DefaultConfig()
cfg.Connection.EnableSystemProxy = true

// Auto-detects:
// - Windows: Registry Internet Settings
// - macOS: System Preferences Network Proxy
// - Linux: Environment variables HTTP_PROXY / HTTPS_PROXY

Proxy priority:

  1. ProxyURL (manually specified, highest priority)
  2. EnableSystemProxy (system proxy detection)
  3. Direct connection (no proxy)

DNS-over-HTTPS

Enable DoH to reduce DNS resolution latency and prevent DNS hijacking:

go
cfg := httpc.DefaultConfig()
cfg.Connection.EnableDoH = true
cfg.Connection.DoHCacheTTL = 5 * time.Minute

Default DoH providers (in priority order):

ProviderAddressDescription
Cloudflare1.1.1.1/dns-queryFastest, privacy-first
Googledns.google/resolveGlobal coverage
AliDNSdns.alidns.com/resolveOptimized for China region

TIP

When DoH is enabled, DNS resolution results are cached for DoHCacheTTL duration. If all DoH providers are unavailable, it falls back to system DNS.

HTTP/2

HTTP/2 is enabled by default (requires TLS):

go
cfg := httpc.DefaultConfig()
cfg.Connection.EnableHTTP2 = false // Disable HTTP/2

HTTP/2 features:

  • Multiplexing: Single connection handles multiple concurrent requests
  • Header compression: Reduces repeated header transmission
  • Server push

Object Pool Reuse

Internally, HTTPC reuses engine response objects and string builders via sync.Pool to reduce GC pressure; Result itself is created fresh per request and reclaimed by GC.

go
result, err := client.Get(url)
if err != nil {
    return err
}
// Result is created fresh per request, reclaimed by GC, no manual release needed

In high-concurrency scenarios, internal object pool reuse significantly reduces GC pressure.

Concurrent Request Pattern

go
func fetchAll(ctx context.Context, urls []string) ([]*httpc.Result, error) {
    results := make([]*httpc.Result, len(urls))
    errs := make([]error, len(urls))

    var wg sync.WaitGroup
    for i, url := range urls {
        wg.Add(1)
        go func(idx int, u string) {
            defer wg.Done()
            result, err := client.Request(ctx, "GET", u)
            results[idx] = result
            errs[idx] = err
        }(i, url)
    }
    wg.Wait()

    for _, err := range errs {
        if err != nil {
            return nil, err
        }
    }
    return results, nil
}

Connection Pool Common Issues

ProblemCauseSolution
Many TIME_WAITIdle connection timeout too shortIncrease IdleConn timeout
Connection refusedInsufficient connections per hostIncrease MaxConnsPerHost
Requests queuingConnection pool too smallIncrease MaxIdleConns

For complete performance anti-patterns and optimization recommendations, see Performance Optimization.

Next Steps