Skip to content

Memory Issue with EF Core 7 DbContext ServiceProviderCache #31539

@easaevik

Description

@easaevik

We have a .net 7 app using EF Core 7 running on Azure App Service. It's an API for both our web app and mobile app. Memory usage typically grows from 50MB to 3GB during peak hours (8-16) and only get released when things calm down at approximately 16 in the afternoon. During these 8 hours we have around 60k requests to our API. It's a multitenant app with Azure Sql database per tenant and approximately 180 tenants. We use ModelCacheKeyFactory to get correct global query filters for each tenant. Not only that, but we also have to differentiate between user roles in a tenant, given that we do authorization through EF Core global query filters.

image

Not sure what happens in the afternoon, but could it be IIS recycling? It's not restarting, that I have checked. Anyway, what could possibly cause such a big pile-up of memory in Gen 2 and the DbContext ServiceProviderCache?

image

image

image

As for the code I have tried to short it down to the essentials. In out startup.cs we use services.AddDbContext<IXDbContext, XDbContext>(); so nothing fancy there, but in the DbContext there is a lot more going on:

image

image

The EntityDbContextManager uses reflection to get the correct Authorization handler:

image

A typical Authorization handler for a given entity (i.e. User) looks like this:

image

So all in all a lot going on here. The question is why does ServiceProviderCache retain so much memory under load? The system works as it should, just not happy with all this retained bytes ending up in Gen 2. I fear there could be problems ahead as more tenants are added. Any help would be greatly appreciated.

Metadata

Metadata

Assignees

No one assigned

    Type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions