Middle
What is a memory leak? How did you detect and fix a leak in WebSocket Hub using pprof?
sobes.tech AI
Answer from AI
Memory leak is a situation where a program continues to occupy memory that is no longer needed but does not release it, leading to increased memory consumption and potential failure.
In the case of WebSocket Hub in Go, you can detect a leak using pprof as follows:
- Import
net/http/pprofand run an HTTP server for profiling. - Capture heap profiles at different times and compare.
- Use
go tool pproffor analysis, identifying objects that are not released.
For example, if the Hub stores a map of clients, and upon disconnecting a client, the reference to it is not removed, memory is not freed.
To fix this:
- Check the logic for removing clients from the Hub structure when closing the connection.
- Ensure all channels and goroutines are properly terminated.
- Add tests and memory monitoring.
Example of removing a client from the Hub:
func (h *Hub) unregisterClient(client *Client) {
delete(h.clients, client)
close(client.send)
}
Thus, regular analysis with pprof and careful management of object lifecycle helps identify and eliminate memory leaks.