You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
DbContextPool not decrementing active_dbcontexts metrics #38306
I want to use the DbContext pool. Because I have a few places where it's up to the developer to properly dispose the DbContext I want to monitor pool usage and context disposal.
There are no metrics for the pool (e.g. rented out db contexts), so I tried monitoring the 'microsoft.entityframeworkcore.active_dbcontexts' metric. However I notice that this metric is not correct when used in combination with a pool.
I know that the metric includes the idle contexts in the pool as discussed in #35855 , but whenever the pool is exhausted and falls back to creating new contexts, those contexts are also not decremented from the metric after disposal, so you get an ever-incrementing metric. I can monitor the internal pools _count field to check if the pool is not getting saturated, but that also doesn't give me the full picture.
E.g. if you have a pool limit of 50 and rent 75 db contexts at once, of which you return 60, the internal pool _count will show that you have 50 contexts available and the active_dbcontexts metric will show 75 contexts. There is no way to deduce that there are in fact 15 active/lingering contexts.
A project to reproduce and show this error can be found here.
active_dbcontexts is incremented in the DbContext constructor and decremented only when the underlying instance is truly torn down via DisposeSync. So, it counts live DbContext CLR instances, not currently-leased contexts. If it's constantly increasing that indeed signals a leak. If all instances are returned then active_dbcontexts will go down to the size of the pool
Thanks for your reply. Maybe my bug report was not clear. Even if I return all instances, the active_dbcontexts will not go down to the size of the pool, my demo project shows exactly that. I dispose all dbcontexts properly but active_dbcontexts still keeps incrementing as if there are leaks.
Activity
AndriySvyryd commentedon May 27, 2026
active_dbcontexts is incremented in the DbContext constructor and decremented only when the underlying instance is truly torn down via DisposeSync. So, it counts live DbContext CLR instances, not currently-leased contexts. If it's constantly increasing that indeed signals a leak. If all instances are returned then active_dbcontexts will go down to the size of the pool
gijs-hendrikx commentedon May 28, 2026
Hi @AndriySvyryd ,
Thanks for your reply. Maybe my bug report was not clear. Even if I return all instances, the active_dbcontexts will not go down to the size of the pool, my demo project shows exactly that. I dispose all dbcontexts properly but active_dbcontexts still keeps incrementing as if there are leaks.