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 ?
5
-
4The error PAM authentication failed for user "username" has nothing to do with exceeding the maximum number of allowed connections.user330315– user3303152022-12-01 09:35:57 +00:00Commented Dec 1, 2022 at 9:35
-
If you still suspect a problem with the number of connections you can take a look here: stackoverflow.com/q/5267715/10171966SebDieBln– SebDieBln2022-12-01 09:41:45 +00:00Commented Dec 1, 2022 at 9:41
-
sql.DB.Stats reports details about connections.Peter– Peter2022-12-01 09:47:07 +00:00Commented Dec 1, 2022 at 9: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– madhu nandan2022-12-01 10:14:02 +00:00Commented Dec 1, 2022 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– madhu nandan2022-12-02 05:07:49 +00:00Commented Dec 2, 2022 at 5:07
Add a comment
|
1 Answer
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
}