bigywater.tech
Flask · 147

请求超时

请求超时到底由谁负责?gunicorn 的 --timeout 是不是请求超时?nginx 超时了后端还在跑吗?Flask 自己怎么限时?这篇用真实的 gunicorn 与 nginx 把每一层超时的行为量出来。

500 vs 200
gunicorn --timeout 2、视图 5 秒时,sync worker 与 gthread worker 的客户端结果
504
nginx proxy_read_timeout 到点返回的状态码
仍然跑完
客户端与代理放弃之后,后端慢请求的结果

gunicorn --timeout

实测 · 本机执行输出
  sync worker      客户端:500,用时 2045 ms,'<html>   <head>     <title>Internal Server Error</title>   <' | 服务端日志有 WORKER TIMEOUT:True
  gthread worker   客户端:200,用时 5018 ms,'slow done' | 服务端日志有 WORKER TIMEOUT:False

上一篇:后台线程与 Application Context;下一篇:长轮询。

nginx 的超时

实测 · 本机执行输出
  客户端:504,用时 2013 ms,'<html>\r <head><title>504 Gateway Time-out</title></head>\r <body>\r <center><h1>50'
  4 秒之后查看服务端:慢请求是否仍然跑完了: True (客户端早就拿到 504,工作还是做完了)

nginx 是自己起的实例(自签证书),上游是 gthread 的 gunicorn。

应用层的截止时间

实测 · 本机执行输出
  /deadline?limit=1 → 504,用时 1074 ms,'{"error":"took too long","steps":10}'
  /deadline?limit=20(够用)→ 200,用时 5316 ms

分步演示

请求超时
本步的对象

    本文用到的工具与边界

    • 本机 macOS 27 arm64 / Python 3.14.7 / Flask 3.1.3 / Werkzeug 3.1.9 / Jinja2 3.1.6 / SQLAlchemy 2.1.1 / gunicorn 26.2.0(都装在自己的虚拟环境里);大多数实验用 Flask 的 test_client(直接调用 WSGI 应用,不经过网络),需要真实 HTTP 时另起 gunicorn 或开发服务器(端口 9600 以上,本机 127.0.0.1);计时用 time.perf_counter,数字每次运行会有小幅抖动。gunicorn sync 与 gthread worker、nginx 1.31.6(自己的配置、非默认端口)
    • 没有验证:gevent worker 的 --timeout 行为、proxy_connect_timeout 与 proxy_send_timeout、客户端断开时 gunicorn 的处理、数据库 statement_timeout 与 requests 的 timeout 参数、负载均衡器的空闲超时
    京ICP备2026067502号-1京公网安备11010502063487号