EF Core and big traffic leads to max pool size was reached error

.net-core asp.net asp.net-web-api c# entity-framework-core


We're using ASP.NET Entity Framework Core for querying our MSSQL database in our Web API app. Sometimes when we have big traffic, querying to DB ends with this error:

Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached.

I wonder if our pattern of using DbContext and querying is correct or if I am missing some using/dispose pattern and error is caused by some memory leak (after some research I read then I should not use using because the lifetime is managed by the framework). I am following documentation...

My connectionString:

"myConnection": "Server=xxx;Database=xxx;user id=xxx;password=xxx;Max Pool Size=200;Timeout=200;"

My Startup.cs

public void ConfigureServices(IServiceCollection services)
    // scoped context            
            options => options.UseSqlServer(this.Configuration.GetConnectionString("myConnection")));

then in controllers I used dbcontext by dependency injection:

public class MyController : Controller
   public MyController (MyDbContext context)
        this.Context = context;            

    public ActionResult Get(int id)
        // querying
        return this.Context.tRealty.Where(x=>x.id == id).FirstOrDefault();

Should I use something like:

using (var context = this.Context)
            return this.Context.tRealty.Where(x => x.id == id).FirstOrDefault();

But I think that this is bad pattern when I am using dependency injection of DbContext.

9/30/2016 12:18:35 PM

Accepted Answer

I think problem was caused by storing objects from database context queries to In memory cache. I had one big LINQ query to database context with some other subqueries inside. I called FirstOrDefault() on the end of main query but not inside subqueries. Controller was fine with it, it materialize queries by default.

 return this.Context.tRealty.AsNoTracking().Where(
                x => x.Id == id && x.RealtyProcess == RealtyProcess.Visible).Select(
                s => new
                { .....

// subquery
videos = s.TVideo.Where(video => video.RealtyId == id && video.IsPublicOnYouTube).
                        Select(video => video.YouTubeId).ToList()), // missing ToList()

And there was problem - subqueries were holding connection to database context when they where storing to In memory cache. When I implemented Redis distributed cache, it was first failing on some strange errors. It helps when I write ToList() or FirstOrDefault() to all my subqueries because distributed cache needs materialized objects.

Now I have all my queries materialized explicitly and I got no max pool size was reached error. So that one must be careful when stored objects from database context queries to In memory cache. It is need to materialize all queries to avoid to holding connection somewhere in memory.

10/11/2016 7:50:08 AM

Popular Answer

I am adding an alternative answer, in case anyone lands here with a slightly different root cause, as was the case for my .NET Core MVC application.

In my scenario, the application was producing these "timeout expired... max pool size was reached" errors due to mixed use of async/await and Task.Result within the same controller.

I had done this in an attempt to reuse code by calling a certain asynchronous method in my constructor to set a property. Since constructors do not allow asynchronous calls, I was forced to use Task.Result. However, I was using async Task<IActionResult> methods to await database calls within the same controller. We engaged Microsoft Support, and an Engineer helped explain why this happens:

Looks like we are making a blocking call to an Async method inside [...] constructor.


So, basically something is going wrong in the call to above highlighted async method and because of which all the threads listed above are blocked.

Looking at the threads which are doing same operation and blocked:


85.71% of threads blocked (174 threads)

We should avoid mixing async and blocking code. Mixed async and blocking code can cause deadlocks, more-complex error handling and unexpected blocking of context threads.



Action Plan

Please engage your application team to revisit the application code of above mentioned method to understand what is going wrong.

Also, I would appreciate if you could update your application logic to not mix async and blocking code. You could use await Task instead of Task.Wait or Task.Result.

So in our case, I pulled the Task.Result out of the constructor and moved it into a private async method where we could await it. Then, since I only want it to run the task once per use of the controller, I store the result to that local property, and run the task from within that method only if the property value is null.

In my defense, I expected the compiler would at least throw a warning if mixing async and blocking code is so problematic. However, it seems obvious enough to me, in hindsight!

Hopefully, this helps someone...

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow