如何检测僵尸连接?
解读
在国内高并发、云原生场景下,僵尸连接(Zombie Connection)特指已经失效但操作系统或应用层仍认为“存活”的 TCP 连接。它们不响应读写、不触发 FIN/RST,却占用文件描述符、内存、连接池槽位,最终把服务拖垮。
Revel 作为全栈框架,默认并不提供僵尸连接检测机制,需要开发者结合 Go 运行时与内核行为在应用层补齐。面试官问这道题,想看你是否:
- 能准确定义僵尸连接与空闲连接的区别;
- 熟悉 Linux 下 TCP Keepalive、Go SetKeepAlive 以及应用心跳三套机制;
- 能在 Revel 的 Controller、Filter、Server 三层中选择最合理的植入点;
- 知道如何联动 Prometheus 告警,实现国内互联网公司要求的可观测性闭环。
知识点
- TCP 内核 Keepalive:Linux 的
net.ipv4.tcp_keepalive_time/intvl/probes三个参数,默认 7200 s 起步,云主机常调至 60/10/3,只能检测死连接,不能感知业务层假死。 - Go 的 TCP KeepAlive:
net.TCPConn.SetKeepAlive(true)+SetKeepAlivePeriod(d),在 Revel 中需通过http.Server.ConnState钩子注入,对 Hijacked 的 WebSocket 无效。 - 应用层心跳:Revel 的 WebSocket 模块自带
ping/pong回调,对普通 HTTP 长连接需自定义 双工心跳协议;心跳超时必须 大于公网 RTT 99 分位 3 倍,避免国内跨省链路抖动误判。 - 连接池级检测:若 Revel 背后复用
database/sql或redis.Pool,需设置 IdleTimeout、MaxConnLifetime,并与 health check Filter 联动,防止池内僵尸连接被业务逻辑复用。 - 可观测性:在 Filter 中埋点
conn_start_time与最近一次io_time,通过 Prometheus + Grafana 暴露zombie_conn_total{state="idle_gt_300s"},告警阈值按 P99 取 5 min 斜率突增 20%。
答案
分四层落地,代码可直接写进 Revel 工程:
- Server 层:启动时把
http.Server.ConnState挂到 Revel 的http.Server实例上,状态机记录lastActiveTime。
srv := &http.Server{
Addr: revel.HttpAddr,
Handler: revel.Server,
ConnState: func(conn net.Conn, state http.ConnState) {
key := conn.RemoteAddr().String()
switch state {
case http.StateActive:
connStore.Update(key, time.Now())
case http.StateIdle:
if time.Since(connStore.LastActive(key)) > 3*time.Minute {
revel.AppLog.Warnf("zombie conn detected: %s", key)
conn.Close() // 强制回收
metrics.ZombieConnTotal.Inc()
}
case http.StateClosed, http.StateHijacked:
connStore.Delete(key)
}
},
}
- 内核层:在
/etc/sysctl.conf统一调优
net.ipv4.tcp_keepalive_time = 60
net.ipv4.tcp_keepalive_intvl = 10
net.ipv4.tcp_keepalive_probes = 3
- WebSocket 层:Revel 的
websocket.Message封装里,每 30 s 发送 Ping,注册 Pong 回调更新lastPong;若 90 s 无 Pong 直接conn.Close()。 - 告警闭环:Prometheus 规则
- alert: RevelZombieConnBurst
expr: increase(zombie_conn_total[5m]) > 20
annotations:
summary: "Revel 实例 {{ $labels.instance }} 僵尸连接突增"
以上四层互补,内核 Keepalive 兜底、应用心跳精准、ConnState 实时回收、告警驱动运维,可把线上僵尸连接数长期压到 总连接 1% 以下。
拓展思考
- IPv6 双栈:国内云厂商已默认开启 IPv6,Keepalive 参数需同时调优
net.ipv6同名项,否则 IPv6 僵尸连接会漏网。 - Service Mesh 下沉:若公司采用 Istio,mTLS 长连接由 Envoy 托管,Revel 只需暴露
envoy.tcp_proxy.idle_timeout=180s,把检测逻辑下沉到 Sidecar,业务代码零侵入。 - 用户态 TCP:使用
github.com/lysShub/netkit/rawtcp做用户态协议栈时,无法再用内核 Keepalive,必须在 Revel 的 Filter 里完全自实现心跳与 RTT 采样,面试可展示你对epoll边缘触发的掌握深度。