Is it good to use single database connection for all database operations in one API request?

Abhilash Perla 20 Reputation points
2024-09-30T18:48:01.8833333+00:00

In general, I know the best practice while handling database connections in C#/ADO.NET is to open Db connection just before querying the Db & close the connection immediately after query execution, so that connection gets back to pool. My question now is, can we cache the database connections & re-use the same connection to execute all the queries? Let's say in one Rest API request, is it good to use the same Db connection to perform N number of database operations? The reason why we want to do this is, in case of parallel processing we want to use same database connection & hence reduce the number of database connections being created. Does this a good practice to do or will it effect connection pooling? Please advise. Thanks.

SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
13,948 questions
{count} votes

Accepted answer
  1. Erland Sommarskog 112.6K Reputation points MVP
    2024-09-30T21:22:56.48+00:00

    So you want to roll your own connection pooling?

    Just keep in mind that your Rest API is supposed to be multi-thread, things will be "interesting" if you cache one connection object on module level and all calling threads try to reuse that connection. You can avoid with having a semaphore or similar device around your connection object. Which means that your parallel processes will be seriliased.

    I may be misunderstanding what you are trying to do, but I think the answer is: Don't do it.

    1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 66,061 Reputation points
    2024-10-01T15:21:02.7433333+00:00

    NO, its a bad idea.

    while a connection can be shared between threads, they can not use it at the same time. one thread must complete the query and reading results before another thread can use it. as suggested you would need to do locking to prevent concurrent use.

    instead, every concurrent task should have it own connection. setting the connection pool size will control the number of concurrent connections. if the all connections are in use, the thread will wait until one is free.

    note: if one task awaits another, it can pass a connection that is not currently in use.

    1 person found this answer helpful.

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.