根本原因是http.DefaultClient默认MaxIdleConnsPerHost=2且resp.Body未读完,导致连接无法复用而频繁新建关闭,每条连接进入TIME_WAIT;须配对调优MaxIdleConnsPerHost、MaxConnsPerHost与IdleConnTimeout,并按域名分client、完整消费响应体。

为什么短连接在Go里会快速堆满TIME_WAIT
根本不是“短连接本身慢”,而是http.DefaultClient默认配置 + resp.Body没读完,这两件事同时发生才让端口几秒内枯竭。默认MaxIdleConnsPerHost = 2,QPS 超过 5 就被迫新建连接;建完立刻关,每条都进TIME_WAIT,本地端口(65535个)和文件描述符很快耗尽,报错如"Too many open files"或"Connection refused"。
怎么确认是连接池没生效而不是网络问题
别急着改代码,先验证是否真复用了连接:
- 用
netstat -an | grep :443 | grep TIME_WAIT | wc -l看本机TIME_WAIT数量,持续上涨就说明复用失败 - 在
http.Client上加Transport的RoundTrip日志(或用httptrace),观察GotConn和ConnectStart是否频繁交替出现 - 检查
resp.Body是否在所有分支(包括if err != nil)都被完整消费:只调defer resp.Body.Close()等于告诉 transport “这连接不能复用”
必须配对设置的三个Transport参数
MaxIdleConnsPerHost、MaxConnsPerHost、IdleConnTimeout不是独立调优项,失配会直接加剧TIME_WAIT:
-
MaxIdleConnsPerHost建议设为预期峰值 QPS 的 1/5~1/3(例如 5000 QPS → 设 100~200) -
MaxConnsPerHost必须 ≥MaxIdleConnsPerHost,否则 goroutine 卡在 waiting for connection -
IdleConnTimeout设 30–60 秒;设太短(如 10s)浪费 fd,太长(如 120s)空闲连接占着不放
不同后端必须分client,不能共用DefaultClient
http.DefaultClient是全局单例,所有域名共享同一套连接池参数。你连localhost:8080和s3.amazonaws.com会互相挤占连接数,导致某一个服务实际可用连接远低于预期。
立即学习“go语言免费学习笔记(深入)”;
正确做法是按后端域名定义独立*http.Client:
var s3Client = &http.Client{Transport: &http.Transport{
MaxIdleConnsPerHost: 100,
MaxConnsPerHost: 100,
IdleConnTimeout: 60 * time.Second,
}}
var apiClient = &http.Client{Transport: &http.Transport{
MaxIdleConnsPerHost: 50,
MaxConnsPerHost: 50,
IdleConnTimeout: 30 * time.Second,
}}最隐蔽的坑在于:错误路径里漏掉io.Copy(io.Discard, resp.Body),一次就多一个TIME_WAIT——这种问题在线上压测时才暴露,但日志里几乎不报错。



















