Skip to content

WebSocket transport: Stop the heartbeat goroutine on Close - #7463

Closed
StarProxima wants to merge 1 commit into
XTLS:mainfrom
StarProxima:ws-heartbeat-stop
Closed

StarProxima wants to merge 1 commit into
XTLS:mainfrom
StarProxima:ws-heartbeat-stop

Conversation

@StarProxima

Copy link
Copy Markdown
Contributor

Why

With heartbeatPeriod set, every WebSocket connection starts a goroutine that sleeps for the period and sends a ping. It only exits when a ping fails to write, and Close() 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.Instance that Close() closes, so the goroutine exits right away. The ping itself and its period stay the same.

Testing and limits

TestCloseStopsHeartbeat closes a connection with a one hour period and checks that the goroutine count goes back to where it was before the dial. It fails on main, 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.

goroutines at the end memory at the end
no heartbeat 27 40.8 MB
heartbeat, before 104 45.2 MB
heartbeat, this PR 21 38.3 MB

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.

@Fangliding

Copy link
Copy Markdown
Member

这个功能用的很少而且一般多见于使用mux的情况 不用过早优化

@Fangliding Fangliding closed this Nov 22, 2026
@StarProxima

Copy link
Copy Markdown
Contributor Author

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.

@Fangliding

Copy link
Copy Markdown
Member

也许我会想一个其他办法

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants