Difference between connecting to the database in app.on_event('startup') vs in a dependency in FastAPI

Question:

In Tiangolo’s FastAPI, it states that you can create a persistent database connection by using a dependency

https://fastapi.tiangolo.com/tutorial/sql-databases/#create-a-dependency

However, in the Async database docs, the database is connected to in app startup

https://fastapi.tiangolo.com/advanced/async-sql-databases/#connect-and-disconnect

This same pattern is followed in the encode/databases docs

https://www.encode.io/databases/connections_and_transactions/

Which is the right pattern? It seems to me that using dependencies, one database connection would be created per API call, while connecting the the database during startup would establish one database connection per worker. If this is correct, connecting to the database on startup would be far superior.

What the difference between the two and is one better?

Asked By: Cyon

||

Answers:

I won’t go into the details of each database library. Let me just say that most modern tools use a connection pool. They do it explicitly or implicitly, hiding behind certain abstractions like Session in your first link.

In all of your examples, the connection pool is created when the application starts. And when creating a session, there is no heavy operation of establishing a new connection, but only a connection is fetched from the pool, and when the session is closed, the connection is returned to the pool.

Answered By: alex_noname