当websocket超时,如何重试并记录失败率?
解读
- 场景定位
Dash 应用在国内通常部署在「云函数 + API 网关」或「容器 + 负载均衡」架构中,WebSocket 被广泛用于实时推送算法结果、设备 IoT 数据或交易行情。面试官想确认候选人是否能把「前端重连」「后端保活」「指标可观测」三件事在纯 Python 栈里闭环。 - 考点拆解
- Dash 原生并不提供 WebSocket 组件,需要借助 dash-extensions 的 WebSocket 组件或自定义 Component + JavaScript 注入。
- 超时可能发生在三层:浏览器 ↔ 网关(国内常见 60 s 断开)、网关 ↔ 容器(idle timeout)、容器 ↔ 业务代码(阻塞)。
- 重试策略必须兼顾「指数退避 + 最大次数」,否则容易把刚恢复的后端打挂。
- 失败率要落到「可查询」的指标,国内面试常问「你这些指标最后怎么进 Prometheus 或夜莺/阿里云 SLS」。
- 重试过程必须线程安全,因为 Dash 回调可并发。
知识点
- dash-extensions WebSocket 组件生命周期:open → message → close → error。
- 浏览器端重连:Backoff 算法、全双工心跳(ping/pong)。
- 服务端防御性编程:asyncio.wait_for、tenacity 重试装饰器、捕获 trio.Cancelled。
- 线程内指标收集:collections.Counter + threading.Lock,或 prometheus_client Counter/Gauge。
- 国内云厂商超时参数:
- 阿里云 API 网关 WebSocket 默认 60 s 无帧即断;
- 腾讯云 CLB idle 超时 10 ~ 900 s 可调;
- 函数计算最大执行 900 s,但 WebSocket 长连接需改用「异步调用」模式。
- Dash 回调上下文(callback_context)无全局锁,指标写操作必须加锁或使用队列。
答案
下面给出「最小可运行 + 可观测」的参考实现,全部用纯 Python,不依赖 Node 编译,可直接在国产操作系统 + 阿里云容器服务跑通。
-
依赖
pip install dash dash-extensions[websocket] tenacity prometheus-client -
服务端代码(app.py)
import json, time, threading, logging
from collections import Counter
from datetime import datetime
import dash
from dash import html, Input, Output, State
from dash_extensions import WebSocket
from prometheus_client import Counter as PromCounter, start_http_server
from tenacity import retry, stop_after_attempt, wait_exponential
# 1. 指标定义
ws_fail_total = PromCounter("websocket_fail_total", "Total WebSocket failures", ["endpoint"])
ws_retry_total = PromCounter("websocket_retry_total", "Total retry attempts", ["endpoint"])
ws_msg_total = PromCounter("websocket_msg_total", "Messages received", ["endpoint"])
# 2. 线程安全失败率缓存
fail_counter = Counter() # key: endpoint
success_counter = Counter()
lock = threading.Lock()
def record_fail(endpoint: str):
with lock:
fail_counter[endpoint] += 1
ws_fail_total.labels(endpoint=endpoint).inc()
def record_success(endpoint: str):
with lock:
success_counter[endpoint] += 1
ws_msg_total.labels(endpoint=endpoint).inc()
def fail_rate(endpoint: str) -> float:
with lock:
f = fail_counter[endpoint]
s = success_counter[endpoint]
return f / (f + s) if (f + s) else 0.0
# 3. 带重试的消息发送函数(服务端主动 push 场景)
@retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=2, max=10))
async def send_with_retry(ws, message: str):
try:
await ws.send(message)
except Exception as exc:
ws_retry_total.labels(endpoint=ws.url).inc()
record_fail(ws.url)
logging.warning("send failed, will retry: %s", exc)
raise
# 4. Dash 布局
app = dash.Dash(__name__)
app.layout = html.Div([
WebSocket(id="ws", url="wss://your-websocket-gateway"),
html.Div(id="status", children="Connecting…"),
html.Div(id="fail-rate", children="Fail rate: 0%")
])
# 5. 接收消息 + 统计
@app.callback(Output("status", "children"),
Input("ws", "message"))
def on_message(msg):
if msg is None:
return "No data"
record_success(app.layout["ws"].url)
data = json.loads(msg["data"])
return f"Last update: {data}"
# 6. 连接断开时前端自动重连(由 dash-extensions 内部实现指数退避),
# 这里我们只负责把「断开」事件记为一次失败
@app.callback(Output("fail-rate", "children"),
Input("ws", "state"))
def on_state_change(state):
if state == "closed":
record_fail(app.layout["ws"].url)
rate = fail_rate(app.layout["ws"].url)
return f"Fail rate: {rate:.1%}"
# 7. 暴露 Prometheus 指标端口,供夜莺/阿里云 ARMS 抓取
if __name__ == "__main__":
start_http_server(8000)
app.run_server(host="0.0.0.0", port=8050)
- 前端心跳(可选,若网关 60 s 超时)
在 assets/websocket_heartbeat.js 里注入:
// 每 30 s 发一个 ping 帧,防止阿里云网关断开
const ws = document.querySelector("#ws").shadowRoot.querySelector("websocket");
setInterval(() => {
if (ws && ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({type: "ping", ts: Date.now()}));
}
}, 30000);
- 失败率看板
- 开发环境:直接访问 /metrics 看 Prometheus 文本格式。
- 生产环境:夜莺或阿里云 Prometheus 服务抓取 8000 端口,配置告警规则「fail_rate > 5% 持续 2 min」即发出飞书/钉钉。
- 面试时如何讲
- 先画三层架构图(浏览器—网关—容器),指出 60 s 超时参数。
- 说明 dash-extensions 已经内置指数退避重连,我们只需「记录事件」而不是「手写重连」。
- 强调指标用了 prometheus_client,符合国内运维规范,可直接对接夜莺、ARMS、腾讯云 TMP。
- 最后补充:如果后端也要主动 push,用 tenacity 做异步重试,防止雪崩。
拓展思考
- 多实例横向扩容时,Counter 不能留在内存,需要把失败率写进 Redis 或 Pushgateway,再统一聚合。
- 若 Dash 部署在 Serverless(阿里云函数计算),WebSocket 长连接必须改用「异步任务 + MNS 消息队列」模式,重试逻辑要下沉到队列消费端。
- 对金融行情场景,可改用 gRPC-Web over HTTP/2,放弃 WebSocket,以规避网关 60 s 断链限制;此时重试策略要换成「序列号重传 + 幂等去重」。
- 失败率指标可以进一步细分为「网络层失败」「业务鉴权失败」「下游数据源超时」,通过不同的 label 区分,方便快速定界。