· 2 min read

How to Handle Connection Lost in Go?

This article was auto-translated from Chinese. Some nuances may be lost in translation.

After looking into several popular sql packages, I found that almost none of them provide a way to immediately trigger an error when a connection is lost. For example, in nodejs’s mysql, we can use connection.on('error') to listen for errors.

However, in Golang (at least among several popular packages), there is no such feature. Looking a bit deeper, it’s not hard to understand why.

The sql package creates and frees connections automatically; it also maintains a free pool of idle connections. If the database has a concept of per-connection state, such state can be reliably observed within a transaction (Tx) or connection (Conn). Once DB.Begin is called, the returned Tx is bound to a single connection. Once Commit or Rollback is called on the transaction, that transaction’s connection is returned to DB’s idle connection pool. The pool size can be controlled with SetMaxIdleConns.

Put simply, calling sql.Open does not actually establish a connection immediately; instead, it maintains an internal connection pool and only attempts to connect when necessary. In other words, if a connection is lost due to network issues while executing a query, database/sql will automatically attempt to retry under the hood.

This is generally a good thing, since you don’t have to handle the retry logic yourself. But sometimes you don’t want to wait until running a query to discover that the connection has been lost; you want the application to be aware of it beforehand.

If you want to achieve something like this, you will need to customize the underlying Dialer logic so that your application can be notified immediately when the network disconnects.

Related Posts

Explore Other Topics