You need to enable JavaScript to run this app. 排查自研Node.js负载均衡器运行数小时后内存持续上涨的原因
优惠活动
大模型
产品
解决方案
定价
更多

排查自研Node.js负载均衡器运行数小时后内存持续上涨的原因

概述

我实现了一个功能等价于负载均衡器的Node.js程序:接收客户端Socket发来的请求,根据主机名将请求通过管道转发到对应的后端服务Socket。程序基本满足日常使用需求,但在持续稳定的连接流下运行数小时后,内存占用会从初始的40%攀升至80%甚至更高,始终无法定位内存泄漏的位置。

已尝试的排查操作

我曾尝试将所有匿名函数替换为不依赖闭包、使用this上下文的命名函数,但没有效果,以下是核心运行逻辑代码:

const run = async () => {
  const gateways = await fetchGateways()
  const gatewayIndexByHostname = {}

  const getGatewayIP = (hostname) => {
    // 读取gateways数据,更新gatewayIndexByHostname
    // 返回目标IP地址
  }

  const server = net.createServer()

  server.on('connection', (clientSocket) => {
    clientSocket.on('error', () => {
      clientSocket.destroy()
    })

    clientSocket.once('data', (buffer) => {
      const data = buffer.toString()

      const destinationHostname = getDestinationHostname(data)
      const gatewayIP = getGatewayIP(destinationHostname)

      const [host, port] = gatewayIP.split(':')
      const gatewaySocket = net.createConnection({ host, port })

      gatewaySocket.on('error', (err) => {
        clientSocket.end(handleError(500, err))
        gatewaySocket.destroy()
      })

      gatewaySocket.on('connect', () => {
        clientSocket.pipe(gatewaySocket)
        gatewaySocket.pipe(clientSocket)
        gatewaySocket.write(data)
      })
    })
  })

  server.listen(PORT, () => {
    console.log(`listening on port ${PORT}`)
  })
}

run()

我抓取的堆快照显示,Socket及所有与Socket相关的对象会随每一次请求不断增长,希望能定位到本次内存泄漏的诱因。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.18 11:36:02