View : 0

12/04/2026 18:16pm

EP.108 Advanced Timeout and Connection Cleanup Techniques

EP.108 Advanced Timeout and Connection Cleanup Techniques

#WebSocket

#WebSocket Server

#Timeout

#Golang timeouts

#Go

#Golang

#Go Language

#Cleanup

When your WebSocket Server enters a real Production Environment, one of the most common problems is stale connections or idle connections that are no longer active but still consume system resources.

 

If left unmanaged, this can lead to resource leaks, which waste CPU and memory — eventually slowing down your system and even causing crashes.

 

In this episode, you’ll learn essential techniques to:

  • Set timeouts to detect unresponsive connections
  • Monitor idle connections
  • Build cleanup mechanisms to handle stale connections

All to make your WebSocket Server more stable, secure, and scalable for production use. 🔧

 

🧩 1. Why Timeout and Cleanup Are Necessary

 

WebSocket is a long-lived connection that might remain open without being properly closed. For example:

  • A user closes the browser without sending a close frame
  • Temporary network drops
  • The client stops sending data for too long

 

Without a proper management system, this results in:

❌ Memory leaks from stuck connections
❌ Unnecessary CPU usage
❌ Limits on the number of users your system can handle

 

🕒 2. Timeout Technique Using Ping/Pong

 

Go supports Ping/Pong via gorilla/websocket, which helps check whether a client is still active.

 

✅ Example Code:

const (
	pongWait   = 10 * time.Second
	pingPeriod = (pongWait * 9) / 10
)

conn.SetReadDeadline(time.Now().Add(pongWait))

conn.SetPongHandler(func(string) error {
	conn.SetReadDeadline(time.Now().Add(pongWait))
	return nil
})

ticker := time.NewTicker(pingPeriod)
defer ticker.Stop()

for {
	select {
	case <-ticker.C:
		if err := conn.WriteMessage(websocket.PingMessage, nil); err != nil {
			log.Println("Ping error:", err)
			return
		}
	default:
		_, _, err := conn.ReadMessage()
		if err != nil {
			log.Println("Connection closed:", err)
			return
		}
	}
}

 

🔍 Explanation:

  • SetReadDeadline: Set a timeout if no data or pong is received
  • WriteMessage(PingMessage): Send ping to the client
  • SetPongHandler: Extend timeout if pong is received
  • If timeout occurs → connection is closed automatically

 

🧹 3. Cleanup Stale Connections Using Worker

 

In large-scale systems with tens of thousands of connections, you need a worker that periodically removes inactive connections from memory.

 

✅ Example Code:

type Client struct {
	ID         string
	Connection *websocket.Conn
	LastActive time.Time
}

func cleanupInactiveConnections() {
	for {
		time.Sleep(30 * time.Second)
		for id, client := range clients {
			if time.Since(client.LastActive) > 1*time.Minute {
				log.Printf("Closing inactive connection: %s\n", id)
				client.Connection.Close()
				delete(clients, id)
			}
		}
	}
}

 

  • Check every 30 seconds
  • If inactive for more than 1 minute → close and remove the connection

 

⚙️ 4. Best Practices for Timeout and Cleanup

 

PracticeDetails
⏱ Set Read/Write DeadlineClose unresponsive connections
🔄 Use Ping/Pong MechanismCheck if client is still active
🧹 Use Goroutine Cleanup WorkerRemove expired connections
🧠 Store Last Active TimestampsTrack client activity
🧯 Handle PanicPrevent system crash during cleanup

 

🧠 5. Debug and Monitor the System

 

Once you've implemented timeout and cleanup:

  • Use Logs: Track when connections are closed
  • Use Metrics: Monitor number of active connections
  • Use pprof: Check for goroutine or memory leaks

 

🚀 Challenge

 

Enable Ping/Pong and Timeout, then:

  • Leave an idle connection open
  • Close browser without sending a close frame
  • See if the server auto-closes the connection

 

You'll notice your WebSocket Server becomes:

✅ Lighter
✅ Free from resource leaks
✅ More ready to handle higher loads 🚀

 


 

🌟 Next EP:

 

EP.109: Optimizing WebSocket Performance for Mobile Devices

Learn techniques to improve WebSocket performance on mobile, including:

  • Reducing power consumption
  • Handling reconnect when signal drops
  • Adjusting timeout for mobile behavior

📱 With real-world production-ready Go code examples!

 

Read more

🔵 Facebook: Superdev Academy

🔴 YouTube: Superdev Academy

📸 Instagram: Superdev Academy

🎬 TikTok: https://www.tiktok.com/@superdevacademy?lang=th-TH

🌐 Website: https://www.superdevacademy.com/en