pgx icon indicating copy to clipboard operation
pgx copied to clipboard

Disconnected acquired sessions stay connected if context does not expire

Open bck01215 opened this issue 1 year ago • 3 comments

Not really a bug, but I noticed a leak in our code that on DB fail over sessions would stay acquired eventually using up all web sessions for background tasks. The root cause was that the background task's context lasts the duration of the program, so the the session is never released.

I believe a good feature would be to ensure that disconnected sessions are released from the pool.

bck01215 avatar Feb 21 '24 21:02 bck01215

Sorry, I don't understand what you are asking.

jackc avatar Feb 24 '24 15:02 jackc

In the codebase I have (I haven't been able to reproduce in a sample yet) that when the database restarts or another issue causes the connection to disconnect the connection stays acquired in the pool

bck01215 avatar Feb 25 '24 17:02 bck01215


+	logger := logger.LoggerFromContext(ctx)
+	poolConn, err = pgPool.Acquire(ctx)

+	if err != nil {
+		logger.Errorf("failed to acquire postgres connection: %v", err)
+	}
+	defer poolConn.Release()
	for {
-		for {
-			poolConn, err = pgPool.Acquire(ctx)
-			if err != nil {
-				logger := logger.LoggerFromContext(ctx)
-				logger.Errorf("failed to acquire postgres connection: %v", err)
-				time.Sleep(time.Second)
-				continue
-			}
-			break
-		}
		conn := poolConn.Conn()

		_, err = conn.Exec(ctx, "listen "+pgx.Identifier{"sync"}.Sanitize())

I found the problematic code in our own code base. Still not sure why the Acquire was stuck open after calling it when the connection failed

bck01215 avatar Feb 25 '24 19:02 bck01215