Strategy for Connecting to Different DBs

I am creating an API with actix-web and SQLX, and the purpose of this API is to connect to different DBs through it. The user needs to pass the credentials, URL, etc., via headers, and the API should establish a connection to the specified DB and retrieve the information.

The problem or question I have is that for each API request, a new connection to the DB needs to be initialized, and I see that it can be costly and slow. Is there any way or strategy to optimize this process? Or is it inevitable?

Note: The translation assumes that "DB" refers to a "database" in the context of the API. If "DB" refers to something else, please provide clarification for a more accurate translation.

Actix-web has a way to share state across all threads. You could leverage it to share database connections so that you can re-use them.

1 Like

As an extension to @moy2010's answer, see the actix_web::web::Data extractor. Here's the relevant documentation for application state extractors in actix-web: Extractors | Actix

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.