what is the best practice for connecting to the database and manipulating data?

Viewed 39

some people said one connection per each request and some others said to create one connection and use it for each request.

I think if we want to create one connection per request the number of requests that we can handle each time depends on our database.

and if we want to create one connection for all requests we should always check our connection is alive.

for example, in FastApi documentation, they said to use this code for access to the database.

def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

and my problem is when I send a lot of async requests to my application in some requests I got sorry, too many clients already error because of the number of connections that I can make to Postgres.

I know I can change the pool_size like this in sqlarchmy

engine = create_engine(settings.SQLALCHEMY_DATABASE_URI, pool_size=200, max_overflow=0)

but is it a good way to fix my problem?

0 Answers
Related