Im trying to Get current open Postgres DB connections using golang. We are running our application on aws lambda, and many DB transactions are failing to begin. Error that we see is -- pq: PAM authentication failed for user "username" How can i log the current number of open postgres DB connections using golang so i can see if it reaches the max limit ?
Asked
Active
Viewed 217 times
1
-
4The error *PAM authentication failed for user "username"* has nothing to do with exceeding the maximum number of allowed connections. – Dec 01 '22 at 09:35
-
If you still suspect a problem with the number of connections you can take a look here: https://stackoverflow.com/q/5267715/10171966 – SebDieBln Dec 01 '22 at 09:41
-
[sql.DB.Stats](https://pkg.go.dev/database/sql#DB.Stats) reports details about connections. – Peter Dec 01 '22 at 09:47
-
Thanks for the inputs.. If it helps, the PAM authentication error is occurring when we call the below function in our code to begin a transaction. func (db *DB) BeginTx(ctx context.Context, opts *TxOptions) (*Tx, error) – madhu nandan Dec 01 '22 at 10:14
-
@a_horse_with_no_name - May know in which scenario i would get the "PAM authentication failed for user "username" " ?? – madhu nandan Dec 02 '22 at 05:07
1 Answers
0
The error you get is probably for incorrect user/password and not for reaching max connections. For max connections, you should get an error like "too many connections for ..."
To get the current number of connections, you need to query pg_stat_database:
func getNumberOfConnections(db *sql.DB) int {
queryStmt := "SELECT sum(numbackends) FROM pg_stat_database"
rows, err := db.Query(queryStmt)
if err != nil {
log.Fatal(err)
}
defer rows.Close()
var sum int
for rows.Next() {
rows.Scan(&sum)
}
return sum
}

Ronen
- 189
- 3