2

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
  • 4
    The error PAM authentication failed for user "username" has nothing to do with exceeding the maximum number of allowed connections. Commented 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/10171966 Commented Dec 1, 2022 at 9:41
  • sql.DB.Stats reports details about connections. Commented 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) Commented 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" " ?? Commented Dec 2, 2022 at 5:07

1 Answer 1

1

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
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.