You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

同域名下并行发起多个API请求响应变慢,如何优化提速?

问题根因
  • 同域名并发连接限制:主流浏览器对同一HTTP/1.1域名默认最多允许6-8个并发TCP连接,HTTP/2虽然支持多路复用,但大体积请求的流调度依然会产生排队开销;Node.js的HTTP客户端默认也受操作系统层面的端口、TCP缓冲区限制,并非并发数越高性能越好
  • 大请求体的传输开销:单个请求体大小约41MB,100个并行会瞬间占满可用连接的发送缓冲区,后续请求的Request sent阶段需要等待前面的请求完成传输才能开始,自然耗时拉长
优化方案

通用优化策略

  • 控制并发度:根据实际环境的连接上限设置合理的并行数,不要无脑堆高并行。HTTP/1.1环境下建议并行数控制在6-10,HTTP/2环境可以适当提升到30-50,通过实测取最优值即可,你测试的10就是比较适配当前场景的并行数
  • 请求合并:如果业务逻辑允许多个请求的参数合并提交,优先把多个请求合并为单个大请求发送,服务端统一处理后返回结果,完全避免多请求的调度开销
  • 启用压缩:请求体开启gzip/deflate压缩,41MB的JSON压缩后体积可以降到原来的1/10甚至更小,大幅降低Request sent阶段的传输耗时

浏览器端实现方案

用并发池控制并行数,不要一次性把所有请求丢给Promise.all,示例代码:

// 并发请求池实现
async function fetchWithPool(url, data, parallel = 10, total = 100) {
  const result = []
  const executing = []
  for (let i = 0; i < total; i++) {
    const p = fetch(url, {
      method: 'POST',
      body: JSON.stringify(data),
      // 可选:开启请求压缩,需要服务端支持
      headers: { 'Content-Encoding': 'gzip' }
    }).then(res => res.json())
    result.push(p)
    if (parallel <= total) {
      const e = p.finally(() => executing.splice(executing.indexOf(e), 1))
      executing.push(e)
      if (executing.length >= parallel) {
        await Promise.race(executing)
      }
    }
  }
  return Promise.all(result)
}
// 调用示例
fetchWithPool('你的接口地址', data, 10, 100)

Node.js端实现方案

使用node-fetch时除了用上述并发池逻辑,还可以调整HTTP客户端的连接配置,复用TCP连接减少握手开销:

const fetch = require('node-fetch')
const http = require('http')
const https = require('https')
// 复用连接池,减少TCP握手开销
const httpAgent = new http.Agent({ keepAlive: true, maxSockets: 10 })
const httpsAgent = new https.Agent({ keepAlive: true, maxSockets: 10 })

async function nodeFetchWithPool(url, data, parallel = 10, total = 100) {
  const result = []
  const executing = []
  for (let i = 0; i < total; i++) {
    const p = fetch(url, {
      method: 'POST',
      body: JSON.stringify(data),
      agent: url.startsWith('https') ? httpsAgent : httpAgent
    }).then(res => res.json())
    result.push(p)
    if (parallel <= total) {
      const e = p.finally(() => executing.splice(executing.indexOf(e), 1))
      executing.push(e)
      if (executing.length >= parallel) {
        await Promise.race(executing)
      }
    }
  }
  return Promise.all(result)
}

内容的提问来源于stack exchange,提问作者Sergii Zinkevych

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 00:18:03