Healthchecks on chan-based connection pool

How would you implement health checks on idle connections in a chan-based connection pool?

I’m using a buffered channel as the connection pool, which makes it easy to get and put connections.

The chan makes it easy to do pool.GetConnWithContext(ctx, ...) and use a select on both the context and channel – great for timeouts.

But: I want to run periodic health checks on idle connections in the pool. The actual check is not important; it’s more about how to handle “free” vs “in-use” connections.

a) The health check could do pool.GetConn(), but if that conn hasn’t idled long enough yet it would have to put the conn back in the channel and try again. How would it know it has cycled through all connections? How would it ensure that connections don’t idle too long before being checked? In any case, it’s not pretty.

b) Each pool connection could have a health check goroutine, which marks the connection as in use when it’s being checked. But then pool.GetConn() would have to check each connection, and put it back in the channel if it is in use. Again, it would have to track whether it has cycled through all connections. Not pretty.

c) Ditch the channel and use map[string]net.Conn instead, but: This makes it trickier to implement a timeout on pool.GetConn(), and it would also have to loop over all items in the map, and possibly sleep a bit before looping again, within the timeout.

So the channel-based approach has nice benefits, but can it be made to play nicely with periodic health checks of the idle connections?

2 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.