如何检测僵尸连接?

解读

在国内高并发、云原生场景下,僵尸连接(Zombie Connection)特指已经失效但操作系统或应用层仍认为“存活”的 TCP 连接。它们不响应读写、不触发 FIN/RST,却占用文件描述符、内存、连接池槽位,最终把服务拖垮。
Revel 作为全栈框架,默认并不提供僵尸连接检测机制,需要开发者结合 Go 运行时与内核行为在应用层补齐。面试官问这道题,想看你是否:

  1. 能准确定义僵尸连接与空闲连接的区别;
  2. 熟悉 Linux 下 TCP Keepalive、Go SetKeepAlive 以及应用心跳三套机制;
  3. 能在 Revel 的 Controller、Filter、Server 三层中选择最合理的植入点;
  4. 知道如何联动 Prometheus 告警,实现国内互联网公司要求的可观测性闭环。

知识点

  1. TCP 内核 Keepalive:Linux 的 net.ipv4.tcp_keepalive_time/intvl/probes 三个参数,默认 7200 s 起步,云主机常调至 60/10/3,只能检测死连接,不能感知业务层假死。
  2. Go 的 TCP KeepAlive:net.TCPConn.SetKeepAlive(true) + SetKeepAlivePeriod(d),在 Revel 中需通过 http.Server.ConnState 钩子注入,对 Hijacked 的 WebSocket 无效。
  3. 应用层心跳:Revel 的 WebSocket 模块自带 ping/pong 回调,对普通 HTTP 长连接需自定义 双工心跳协议;心跳超时必须 大于公网 RTT 99 分位 3 倍,避免国内跨省链路抖动误判。
  4. 连接池级检测:若 Revel 背后复用 database/sql 或 redis.Pool,需设置 IdleTimeout、MaxConnLifetime,并与 health check Filter 联动,防止池内僵尸连接被业务逻辑复用。
  5. 可观测性:在 Filter 中埋点 conn_start_time 与最近一次 io_time,通过 Prometheus + Grafana 暴露 zombie_conn_total{state="idle_gt_300s"},告警阈值按 P99 取 5 min 斜率突增 20%。

答案

分四层落地,代码可直接写进 Revel 工程:

  1. 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)
        }
    },
}
  1. 内核层:在 /etc/sysctl.conf 统一调优
net.ipv4.tcp_keepalive_time = 60
net.ipv4.tcp_keepalive_intvl = 10
net.ipv4.tcp_keepalive_probes = 3
  1. WebSocket 层:Revel 的 websocket.Message 封装里,每 30 s 发送 Ping,注册 Pong 回调更新 lastPong;若 90 s 无 Pong 直接 conn.Close()。
  2. 告警闭环:Prometheus 规则
- alert: RevelZombieConnBurst
  expr: increase(zombie_conn_total[5m]) > 20
  annotations:
    summary: "Revel 实例 {{ $labels.instance }} 僵尸连接突增"

以上四层互补,内核 Keepalive 兜底、应用心跳精准、ConnState 实时回收、告警驱动运维,可把线上僵尸连接数长期压到 总连接 1% 以下。

拓展思考

  1. IPv6 双栈:国内云厂商已默认开启 IPv6,Keepalive 参数需同时调优 net.ipv6 同名项,否则 IPv6 僵尸连接会漏网。
  2. Service Mesh 下沉:若公司采用 Istio,mTLS 长连接由 Envoy 托管,Revel 只需暴露 envoy.tcp_proxy.idle_timeout=180s,把检测逻辑下沉到 Sidecar,业务代码零侵入。
  3. 用户态 TCP:使用 github.com/lysShub/netkit/rawtcp 做用户态协议栈时,无法再用内核 Keepalive,必须在 Revel 的 Filter 里完全自实现心跳与 RTT 采样,面试可展示你对 epoll 边缘触发的掌握深度。