> ## Content Index
> Fetch the complete content index at: https://zyx322.xyz/llms.txt
> Use this file to discover other available public pages before exploring further.

# 一次 HTTP 请求的耗时拆在哪：DNS、TCP、TLS 与首字节
- URL: https://zyx322.xyz/csdn-2026-10-14-20ba9c2b6bda/
- Published: 2026-10-14T04:00:00.000Z
- Updated: 2026-11-26T07:02:15.000Z
- Author: ZYX
- Tags: 网络与运维

### 一、用 curl 把耗时拆开

`curl` 自带的 `-w` 能把一次请求拆成 6 段，这是排查"接口慢"最快的一招：

```bash
curl -w "
DNS解析:   %{time_namelookup} s
TCP连接:   %{time_connect} s
TLS握手:   %{time_appconnect} s
开始传输:  %{time_pretransfer} s
首字节:    %{time_starttransfer} s
总耗时:    %{time_total} s
" -o /dev/null -s https://api.example.com/healthz

```

输出示例：

```text
DNS解析:   0.005 s
TCP连接:   0.048 s
TLS握手:   0.132 s
开始传输:  0.132 s
首字节:    0.310 s
总耗时:    0.315 s

```

**注意这些是累计值，不是各段独立耗时。** 差值才是每段的真实耗时：

| 段      | 计算                                      | 上例耗时      |
| ------ | --------------------------------------- | --------- |
| DNS 解析 | time\_namelookup                        | 5ms       |
| TCP 握手 | time\_connect - time\_namelookup        | **43ms**  |
| TLS 握手 | time\_appconnect - time\_connect        | **84ms**  |
| 服务端处理  | time\_starttransfer - time\_pretransfer | **178ms** |
| 内容传输   | time\_total - time\_starttransfer       | 5ms       |

一眼看出：**大头是服务端处理 178ms，其次是 TLS 84ms。**

### 二、每一段慢意味着什么

#### DNS 慢（`time_namelookup` 大）

- 没有本地缓存，每次都走网络往返；
- `resolv.conf` 里有不可达的 nameserver；
- K8s 里 `ndots` 导致查询放大。

**这一段应该是几毫秒**。超过 50ms 就值得查，超过 200ms 必有问题。

详见 DNS 解析慢那篇。

#### TCP 握手慢（`connect - namelookup` 大）

这段是**一个 RTT**（三次握手）。所以：

```text
同城机房：<1ms
跨城（比如上海↔北京）：20~40ms
跨运营商：可能 50~100ms

```

**如果这段比理论 RTT 大很多**，说明：

- **网络丢包**（丢包会导致重传，`tcp_syn_retries` 退避让耗时翻倍）；
- **服务端 backlog 满了**（握手排队）；
- 服务端 CPU 打满，来不及响应 SYN。

```bash
# 测纯网络 RTT 做对比
ping -c 10 <host>

# 看有没有重传
ss -ti | grep -i retrans

```

**关键判据**：`time_connect` 明显大于 ping 的 RTT → 有丢包或排队。

#### TLS 握手慢（`appconnect - connect` 大）

这段也是**约 2 个 RTT**（TLS 1.2）或 **1 个 RTT**（TLS 1.3）。

```text
TLS 1.2：2-RTT（ClientHello → ServerHello → 密钥交换 → 完成）
TLS 1.3：1-RTT（大部分情况）

```

所以 **TLS 1.3 比 1.2 少一个 RTT**，跨城场景下能省 20\~40ms。

```bash
# 看用了哪个版本
curl -w "%{ssl_verify_result} %{http_version}\n" -o /dev/null -s https://...
openssl s_client -connect api.example.com:443 -servername api.example.com 2>/dev/null | grep -i "protocol\|cipher"

```

如果这段异常大，常见原因：

- 服务端证书链配置有问题（缺中间证书，客户端要额外去拉取）；
- 用了性能差的密钥交换算法；
- 服务端 TLS 握手消耗 CPU 过高（可以做 TLS 卸载）。

#### 服务端处理慢（`starttransfer - pretransfer` 大）

这段是 **TTFB（Time To First Byte）**，包含：

```text
请求发送到服务端 + 服务端处理 + 服务端发出第一个响应字节

```

**这段才是"服务端真的慢"**，前面几段都是网络开销。

排查要到服务端：看应用的慢日志、数据库慢查询、下游依赖耗时。

```bash
# 在服务端本机测，排除网络因素
curl -w "ttfb=%{time_starttransfer}\n" -o /dev/null -s http://127.0.0.1:8080/healthz

```

**如果服务端本机很快、但客户端测很慢** → 问题在网络链路（代理、LB、防火墙）。

#### 内容传输慢（`total - starttransfer` 大）

响应体大 + 带宽小。

```bash
# 看响应大小和下载速度
curl -w "size=%{size_download} speed=%{speed_download}\n" -o /dev/null -s https://...

```

### 三、做成可复用的脚本

把这段封装一下，排查时直接用：

```bash
#!/bin/bash
# http-timing.sh <url>
curl -w '{
  "dns":       %{time_namelookup},
  "tcp":       %{time_connect},
  "tls":       %{time_appconnect},
  "ttfb":      %{time_starttransfer},
  "total":     %{time_total},
  "code":      %{http_code},
  "size":      %{size_download},
  "remote_ip": "%{remote_ip}",
  "remote_port": %{remote_port}
}' -o /dev/null -s "$1" | \
python3 -c "
import json,sys
d=json.load(sys.stdin)
seg = {
  'DNS解析':   d['dns'],
  'TCP握手':   d['tcp'] - d['dns'],
  'TLS握手':   d['tls'] - d['tcp'],
  '服务端处理': d['ttfb'] - d['tls'],
  '内容传输':   d['total'] - d['ttfb'],
}
print(f\"HTTP {d['code']}  {d['remote_ip']}:{d['remote_port']}  总计 {d['total']*1000:.0f}ms\")
for k,v in seg.items():
    bar = '█' * max(1, int(v/d['total']*40)) if d['total']>0 else ''
    print(f'  {k:10s} {v*1000:7.1f}ms  {bar}')
"

```

跑一下：

```bash
$ ./http-timing.sh https://api.example.com/healthz
HTTP 200  10.0.1.20:443  总计 315ms
  DNS解析       5.0ms  █
  TCP握手      43.0ms  █████
  TLS握手      84.0ms  ██████████
 服务端处理    178.0ms  ██████████████████████
 内容传输       5.0ms  █

```

**这个柱状图能让你一眼看出瓶颈在哪一段。**

### 四、Go 里的对应优化

拆出瓶颈之后，对应的优化手段：

| 慢的段    | Go 侧优化                              |
| ------ | ----------------------------------- |
| DNS    | 用长连接（连接池），减少解析次数；或 net.Resolver 加缓存 |
| TCP 握手 | **连接池**（复用连接，省掉握手）                  |
| TLS 握手 | **连接池**（复用 TLS 会话）；升级 TLS 1.3       |
| 服务端处理  | 查慢查询、加缓存、异步化                        |
| 内容传输   | 开启 gzip、分页、减少冗余字段                   |

**连接池是最大的杠杆**，它同时省掉 DNS、TCP、TLS 三段：

```go
tr := &http.Transport{
    MaxIdleConns:        1000,
    MaxIdleConnsPerHost: 100,            // 默认 2！高并发下会疯狂建新连接
    IdleConnTimeout:     90 * time.Second,
    TLSHandshakeTimeout: 5 * time.Second,
    ForceAttemptHTTP2:   true,           // HTTP/2 多路复用
}
client := &http.Client{Transport: tr, Timeout: 10 * time.Second}

```

**`MaxIdleConnsPerHost` 默认是 2**，这是 Go 服务最常见的性能坑：100 并发打同一个域名，只有 2 条连接被复用，剩下 98 个都在新建连接（DNS + TCP + TLS 全走一遍）。

### 五、持续监控比单次排查更有用

单次 curl 只能看当下。生产上应该持续采集：

```promql
# 用 blackbox_exporter 采集，然后按段拆分
probe_dns_lookup_time_seconds
probe_tls_handshake_duration_seconds
probe_http_first_byte_duration_seconds

```

或者直接看应用层指标：把 Go 的 `httptrace` 打点暴露出来：

```go
import "net/http/httptrace"

trace := &httptrace.ClientTrace{
    DNSStart: func(i httptrace.DNSStartInfo) { dnsStart = time.Now() },
    DNSDone:  func(i httptrace.DNSDoneInfo)  { dnsCost = time.Since(dnsStart) },
    ConnectStart: func(_, _ string) { connStart = time.Now() },
    ConnectDone:  func(_, _ string, _ error) { tcpCost = time.Since(connStart) },
    TLSHandshakeStart: func() { tlsStart = time.Now() },
    TLSHandshakeDone:  func(_ tls.ConnectionState, _ error) { tlsCost = time.Since(tlsStart) },
    GotFirstResponseByte: func() { ttfb = time.Since(reqStart) },
}
req = req.WithContext(httptrace.WithClientTrace(ctx, trace))

```

### 六、带走物

一条排查路径：

```text
1. curl -w 拆出 5 段耗时（注意是累计值，要算差值）
2. 对比理论值：
   ├─ DNS     ：应该 <10ms，大就是没缓存或 nameserver 有问题
   ├─ TCP     ：约 1 个 RTT，明显大于 ping 就是丢包/排队
   ├─ TLS     ：TLS1.2 约 2 个 RTT，TLS1.3 约 1 个 RTT
   ├─ 服务端  ：TTFB，真慢在这里才去查应用
   └─ 传输    ：看响应体大小
3. 在服务端本机再测一次，区分"应用慢"和"网络慢"
4. 优化杠杆最大的是连接池：一次配好，同时省掉 DNS+TCP+TLS

```

一句话结论：**"接口慢"要先用 `curl -w` 拆成 5 段再动手——很多时候慢的根本不是你的代码，而是 TLS 握手或者一个没人管的 DNS 服务器。**