先说结论: HTTPS 请求如果每次都新建连接,除了请求本身的 1 个往返,还要多付 TCP 建连 1 个往返和 TLS 握手的往返(TLS 1.2 要 2 个,TLS 1.3 要 1 个)。在本机加了约 100 ms 往返延迟之后实测:Python 每次新建连接一个请求约 318 ms,复用连接只要约 106 ms;Node 24 用 TLS 1.3 新建连接约 215 ms。这还没算 TCP 建连那一个往返(测试用的转发层推迟不了内核里的三次握手),放到真实网络里差距更大。最容易踩的坑有三个:urllib.request.urlopen 每次都会关连接;httpx.get() 这类顶层函数每次都新建一个 Client;aiohttp 每个请求开一个 ClientSession,结果都一样,一次都没复用。另外,macOS 自带的 Python 3.9 链接的是 LibreSSL 2.8.3,不支持 TLS 1.3,握手比 Node 多一个往返。下面是测试方法和全部原始输出。
先不加延迟,直接对着本机的 HTTPS 服务跑一遍:
$ python3 reuse_bench.py cert.pem 18711
目标 https://localhost:18711/,每种写法顺序发 10 个请求,LibreSSL 2.8.3
urllib.request.urlopen 第1个 2 ms | 其余中位数 1 ms | 服务端 TCP 10 次, TLS 10 次 {'TLSv1.2': 10}
httpx.get(每次新建 Client) 第1个 39 ms | 其余中位数 1 ms | 服务端 TCP 10 次, TLS 10 次 {'TLSv1.2': 10}
httpx.Client 复用 第1个 1 ms | 其余中位数 0 ms | 服务端 TCP 1 次, TLS 1 次 {'TLSv1.2': 1}
aiohttp 每次新建 ClientSession 第1个 2 ms | 其余中位数 1 ms | 服务端 TCP 10 次, TLS 10 次 {'TLSv1.2': 10}
aiohttp 复用 ClientSession 第1个 1 ms | 其余中位数 0 ms | 服务端 TCP 1 次, TLS 1 次 {'TLSv1.2': 1}服务端的计数已经说明问题:三种写法握手了 10 次,两种只握手 1 次。但耗时都是 1 ms 上下,因为本机回环的往返时间不到 0.1 ms,握手只花 CPU。开发时在本机测,看不出任何区别;部署到离对方几千公里的机器上,每个往返都是几十到上百毫秒,握手次数就直接变成了延迟。
(httpx.get 第 1 个的 39 ms 是 httpx 首次调用的初始化开销,和握手无关,后面不再出现。)
三个部分,都跑在 127.0.0.1 上:
服务端核心部分:
const srv = https.createServer({ cert, key, keepAliveTimeout: 30000 }, (req, res) => res.end('ok'));
srv.on('connection', () => st.tcp++); // 新的 TCP 连接
srv.on('secureConnection', (s) => { // 一次 TLS 握手完成
st.tls++;
st.versions[s.getProtocol()] = (st.versions[s.getProtocol()] || 0) + 1;
});转发层的思路是每个方向一个队列,收到数据时记下「到期时间 = 现在 + 50 ms」,到点再写出去:
async def rx():
while True:
data = await reader.read(65536)
q.put_nowait((time.monotonic() + DELAY, data))
if not data:
return
async def tx():
while True:
due, data = await q.get()
await asyncio.sleep(max(0, due - time.monotonic()))
if not data:
writer.close(); return
writer.write(data); await writer.drain()这个转发层有一个局限: TCP 三次握手是内核完成的,客户端 connect() 到转发层时立刻成功,推迟不了。所以下面「新建连接」的数字里只有 TLS 握手和请求本身的往返,真实网络里还要再加 1 个往返。
证书用 openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes -subj /CN=localhost -addext "subjectAltName=DNS:localhost,IP:127.0.0.1" 生成,客户端用 ssl.create_default_context(cafile='cert.pem') 信任它。
$ python3 reuse_bench.py cert.pem 18712
目标 https://localhost:18712/,每种写法顺序发 10 个请求,LibreSSL 2.8.3
urllib.request.urlopen 第1个 318 ms | 其余中位数 318 ms | 服务端 TCP 10 次, TLS 10 次 {'TLSv1.2': 10}
httpx.get(每次新建 Client) 第1个 404 ms | 其余中位数 317 ms | 服务端 TCP 10 次, TLS 10 次 {'TLSv1.2': 10}
httpx.Client 复用 第1个 317 ms | 其余中位数 107 ms | 服务端 TCP 1 次, TLS 1 次 {'TLSv1.2': 1}
aiohttp 每次新建 ClientSession 第1个 331 ms | 其余中位数 317 ms | 服务端 TCP 10 次, TLS 10 次 {'TLSv1.2': 10}
aiohttp 复用 ClientSession 第1个 320 ms | 其余中位数 106 ms | 服务端 TCP 1 次, TLS 1 次 {'TLSv1.2': 1}逐行看:
urlopen 会在请求头里加 Connection: close,每个请求都是新连接,10 个请求 10 次握手。httpx.get() 也不复用。 顶层的 httpx.get、httpx.post 每调用一次就新建一个 Client、用完就关,连接池跟着一起丢掉,效果和 urllib 一样。httpx.Client 复用: 第 1 个请求要握手,318 ms;之后 9 个都走同一条连接,约 106 ms,正好是 1 个往返。ClientSession 不复用,复用 session 才复用,数字和 httpx 一模一样。TLSv1.2。为什么全是 TLS 1.2?看一下 Python 链接的 TLS 库:
$ python3 -c "import ssl; print(ssl.OPENSSL_VERSION, ssl.HAS_TLSv1_3)"
LibreSSL 2.8.3 FalsemacOS 自带的 /usr/bin/python3(3.9.6)链接的是 LibreSSL 2.8.3,不支持 TLS 1.3。服务端明明支持 1.3,握手也只能退到 1.2。用 Homebrew、python.org 安装包或 pyenv 装的 Python 一般链接 OpenSSL 1.1.1 或 3.x,会用上 TLS 1.3。部署在服务器上的 Python 也建议用同一行命令确认一下。
同样的服务和转发层,用 Node 自带的 https 模块,分别强制 TLS 1.3 和 TLS 1.2:
$ node reuse_bench.mjs cert.pem 18712
node v24.14.0, TLSv1.3 default max, target https://localhost:18712/
TLSv1.3 keepAlive agent (reuse) first 218 ms | median(rest) 107 ms | server TCP 1, TLS 1 {"TLSv1.3":1}
TLSv1.3 agent:false (new conn each time) first 213 ms | median(rest) 215 ms | server TCP 10, TLS 10 {"TLSv1.3":10}
TLSv1.2 keepAlive agent (reuse) first 320 ms | median(rest) 105 ms | server TCP 1, TLS 1 {"TLSv1.2":1}
TLSv1.2 agent:false (new conn each time) first 319 ms | median(rest) 318 ms | server TCP 10, TLS 10 {"TLSv1.2":10}https.globalAgent 默认就开了 keep-alive,直接用 https.get(url) 会复用;显式传 agent: false 才会每次新建。把内核里那一次 TCP 建连补回来,按往返次数算(RTT 指一次往返时间):
写法 | 新建连接需要的往返 | RTT = 100 ms 时约 | RTT = 200 ms 时约 |
|---|---|---|---|
复用已有连接 | 1(只有请求) | 100 ms | 200 ms |
新建,TLS 1.3 | 3(TCP 1 + TLS 1 + 请求 1) | 300 ms | 600 ms |
新建,TLS 1.2 | 4(TCP 1 + TLS 2 + 请求 1) | 400 ms | 800 ms |
这张表是按上面实测的往返数推算的,没算服务端处理时间和 DNS 解析。对一个往返 100 ms 的接口顺序调用 100 次,TLS 1.2 每次新建连接比复用多出约 30 秒。
不需要抓包。httpx 可以通过 trace 扩展看每个请求有没有建连、握手;aiohttp 用 TraceConfig 挂两个回调:
import asyncio, ssl, httpx, aiohttp
URL = 'https://localhost:18711/'
ctx = ssl.create_default_context(cafile='cert.pem')
def log(event, info):
if event.endswith('.complete') and event.startswith('connection.'):
print(' httpx trace:', event)
with httpx.Client(verify=ctx) as c:
for i in range(2):
print('request', i + 1)
c.get(URL, extensions={'trace': log})
async def main():
tc = aiohttp.TraceConfig()
async def created(s, ctx_, p): print(' aiohttp: new connection')
async def reused(s, ctx_, p): print(' aiohttp: reused connection')
tc.on_connection_create_end.append(created)
tc.on_connection_reuseconn.append(reused)
async with aiohttp.ClientSession(trace_configs=[tc]) as s:
for i in range(2):
print('request', i + 1)
async with s.get(URL, ssl=ctx) as r:
await r.read()
asyncio.run(main())输出:
request 1
httpx trace: connection.connect_tcp.complete
httpx trace: connection.start_tls.complete
request 2
request 1
aiohttp: new connection
request 2
aiohttp: reused connection第 2 个请求 httpx 没有任何 connect_tcp、start_tls 事件,aiohttp 打出 reused connection,说明都复用了。上线前在日志里挂一下这两个钩子,就能确认是不是每个请求都在重新握手。
# httpx:整个程序(或整个批次)共用一个 Client
with httpx.Client(timeout=10) as client:
for url in urls:
r = client.get(url)
# aiohttp:一个应用一个 ClientSession,不要每个请求开一个
async with aiohttp.ClientSession() as session:
for url in urls:
async with session.get(url) as r:
await r.read()httpx.get()、urllib.request.urlopen() 调同一个服务很多次的,改成共用一个客户端对象,是改动最小、收益最大的优化;Limits(keepalive_expiry=5.0)),aiohttp 默认 15 秒(TCPConnector(keepalive_timeout=15)),对方服务端也有自己的空闲超时,超过了照样要重新握手;verify 时,每新建一个 Client 都会重新加载一遍 certifi 证书包,本机测一次约 1.4 ms,比起网络往返不算大,但别在循环里反复建 Client。httpx.Client 才复用,顶层的 httpx.get() 每次都是新连接。urllib.request、httpx.get()、每次新建 ClientSession 都不复用;trace 扩展或 aiohttp 的 TraceConfig 就能看出每个请求有没有重新握手。测试环境:macOS,Python 3.9.6(LibreSSL 2.8.3),httpx 0.28.1,aiohttp 3.13.5,Node v24.14.0;测试服务、转发层、客户端全部在 127.0.0.1 上,单向延迟 50 ms。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。