NodeJS+AWS Lambda异步HTTP请求单请求耗时统计不准确如何修复
问题根因
- 原有代码依赖axios拦截器传递请求开始时间戳,高并发场景下拦截器回调受Node.js事件循环调度影响,存在计时偏差
- Node.js 内置HTTP/HTTPS模块默认存在并发套接字数量限制,大量异步请求同时发起时会进入等待队列,排队时间被计入单请求耗时,导致和同步执行时的单请求耗时不一致
解决方案
优化计时逻辑 + 解除并发连接限制
直接在发起请求前记录开始时间,请求结束后直接计算耗时,避免拦截器调度带来的偏差;同时调整HTTP代理配置解除并发连接限制,减少请求排队:
async makeRequests() { const http = require('http'); const https = require('https'); const axios = require('axios').default; // 复用axios实例,配置自定义代理解除并发连接限制,数值可根据实际并发量调整 const axInstance = axios.create({ httpAgent: new http.Agent({ maxSockets: 100 }), httpsAgent: new https.Agent({ maxSockets: 100 }) }); const axList = []; this.reponses = []; for (const item of this.targets) { const {url, method} = item; const config = {url, method}; const stat = { startTime: this.getTime(), duration: 0, status: 0, response: null }; const axItem = axInstance.request(config) .then((resp) => { const {status, data} = resp; stat.duration = this.getTime() - stat.startTime; stat.response = data; stat.status = status; }) .catch((error) => { stat.duration = this.getTime() - stat.startTime; stat.status = error.response?.status || -1; console.log(error); }) .finally(() => { this.reponses.push(stat); }); axList.push(axItem); } await Promise.all(axList); // 替换已废弃的axios.all方法 return this.reponses; }
可选优化:分批控制并发
如果目标服务端有并发请求限流规则,可以将100个请求拆分为多批次执行,每批控制10-20个并发,既避免触发服务端限流,也能进一步减少排队带来的耗时统计偏差。
内容的提问来源于stack exchange,提问作者Nasir Aliyev
相关产品推荐
相关产品推荐

