Repository navigation
WebSocket transport: Stop the heartbeat goroutine on Close - #7463
StarProxima wants to merge 1 commit into
Conversation
|
这个功能用的很少而且一般多见于使用mux的情况 不用过早优化 |
|
We use WebSocket heartbeat in production to keep idle connections alive through CDNs. This affected many of our users during rollout. Our VPN client regularly hits its memory limit, so a few extra MB matter when we decide whether we can enable heartbeat more broadly. With a 45-second heartbeat, a connection can close and its ping goroutine can still hold on to the WebSocket and its buffers for up to 45 seconds. When many short connections close in a burst, those buffers add up. We reproduced this with heartbeat enabled in both runs. Before the fix we ended at 45.2 MB and 104 goroutines. With the fix we ended at 38.3 MB and 21 goroutines, and heartbeat still kept idle connections alive. Would you reopen this PR? The fix and regression test are already here. We’d like to ship it so we can enable heartbeat for more users. |
|
也许我会想一个其他办法 |
…g to task.Periodic (#7470) #7463 (comment) #7470 (comment) #7470 (comment) --------- Co-authored-by: StarProxima <[email protected]>
Why
With
heartbeatPeriodset, every WebSocket connection starts a goroutine that sleeps for the period and sends a ping. It only exits when a ping fails to write, andClose()does not wake it, so a closed connection stays in memory with its gorilla buffers until the next ping is due. With short connections and a period of tens of seconds these pile up.What changed
The ping goroutine now waits on a ticker and on a
done.InstancethatClose()closes, so the goroutine exits right away. The ping itself and its period stay the same.Testing and limits
TestCloseStopsHeartbeatcloses a connection with a one hour period and checks that the goroutine count goes back to where it was before the dial. It fails onmain, where the goroutine sleeps for the whole hour.Measured on a build based on v26.10.31, on a CDN emulator with 100 short connections and three bursts of 24, ping every 45 s.
With the change the ping still keeps idle connections of 70 and 120 s alive through an emulator that drops them after 60 s without data.
go test -race ./transport/internet/websocket/passes.