Database too many clients crashes
johnlins
HOBBYOP

a year ago

Given the nature of my software, whenever a user uses it, they must make dozens of requests to the database to incrementally decrease a number (the amount of funds in their account).

The result of this is that the database just crashes.

I am not super familiar with databases in general btw, just enough to do CRUD

Thanks!

20 Replies

johnlins
HOBBYOP

a year ago

7ca80dd7-b76f-4860-8cd5-add39d3a162c


a year ago

your app should be using a database pool, not opening a new connection for every query you make to the database


johnlins
HOBBYOP

a year ago

Oh okay thanks. I will look into that.
In the meantime, how can I uncrash my database?


a year ago

well its not crashed, just not accepting any more connections, you can redeploy it to close the connections


johnlins
HOBBYOP

a year ago

@Brody Wait, I'm actually not opening a new connection each time… I don't think. Becuase I open it once and then make it a global variable called db.

```go
package main

import (
"database/sql"
//"os"
"fmt"

_ "github.com/lib/pq"

)

var db *sql.DB

func InitDB( /dbname string, password string, host string, port string, user string/ ) {

var err error

//    "dbname="+dbname+" user="+user+" password="+password+" host="+host+" port="+port+" sslmode=disable"

db, err = sql.Open("postgres", "postgresql://postgres:4B...beB1fd@monorail.proxy.rlwy.net:47665/railway")

if err != nil {
    fmt.Println("InitDB err")
    panic(err)
} else {
    fmt.Println("Connected to DB")
}

}```


johnlins
HOBBYOP

a year ago

I then use the global db object throughout code


a year ago

is there anything else connecting to yoour database?


johnlins
HOBBYOP

a year ago

No, only one app


johnlins
HOBBYOP

a year ago

ChatGPT said to add
go db.SetMaxOpenConns(25) // Maximum number of open connections to the database db.SetMaxIdleConns(25) // Maximum number of idle connections in the pool db.SetConnMaxLifetime(5 * 60)

Do you think this is the solution? Or should have pooling alone fixed the problem?


a year ago

is that even valid code?


johnlins
HOBBYOP

a year ago

Project code or postgres code?


johnlins
HOBBYOP

a year ago

I put … inside the postgres code, I assume I shouldn't make it public


a year ago

code for github.com/lib/pq


johnlins
HOBBYOP

a year ago

Oh


johnlins
HOBBYOP

a year ago

Good question let me check



a year ago

then cant hurt to try


johnlins
HOBBYOP

a year ago

Okay I'll try


johnlins
HOBBYOP

a year ago

Also, is it the constant reading from the database that's the issue or the constant changing of a value? Or it doesn't matter?


a year ago

it would be too many connections being open to the database, but i honestly dont know why that would happen


Loading...