fastapi/uvicorn 压测并发与TCP队列(qbit)

前言

  • 技术栈

    操作系统 Ubuntu 20.04
    内核版本 Linux version 5.4.0-155-generic
    Python 3.11
    fastapi 0.99.1
    uvicorn 0.23.2
  • uvicorn 监听端口 8003
  • 用 jmeter 压测 fastapi/uvicorn 接口程序,大量报错:

    java.net.SocketException: Connection reset
    org.apache.http.NoHttpResponseException: ... failed to respond

    服务器 cpu 和内存使用都不高,推测是 tcp 连接队列的问题

处理步骤

  • 查看 tcp 连接数

    ss -natp '( sport = :8003 )' | awk '{count[$1]++} END {for (word in count) print word, count[word]}'
  • 查看应用程序 uvicorn 的 TCP 全连接队列大小

    # ss -nltp '( sport = :8003 )'
    State   Recv-Q  Send-Q  Local Address:Port  Peer Address:Port  Process                          
    LISTEN  0       2048    0.0.0.0:8003        0.0.0.0:*          users:(("uvicorn",pid=172724,fd=14))

    这里的 Send-Q 就是全连接队列大小,与 uvicorn 文档里面 backlog 2048 的默认值是对得上的

  • 查看操作系统半连接队列大小

    # sysctl -a | grep net.ipv4.tcp_max_syn_backlog
    net.ipv4.tcp_max_syn_backlog = 4096
  • 查看操作系统全连接队列大小

    # sysctl -a | grep net.core.somaxconn
    net.core.somaxconn = 4096
  • TCP 连接队列大小值可以修改 /etc/sysctl.conf 文件调整
  • 排查后发现不是 tcp 连接池问题,有相关问题如下:

    日志级别较低时输出日志太多影响性能
    与 redis 的连接数太多报错
    与 PostgreSQL 连接数太多报错
本文出自 qbit snap

你可能感兴趣的:(jmeter)