.NET Architecture & System Design Interview Question #84

Why should database connections and DbContext instances be short-lived?

Transactions, CQRS, Event Sourcing & Distributed Consistency Mid-Level Intermediate

Quick Interview Answer

Database connections are limited resources, and EF Core DbContext represents a unit-of-work-oriented stateful component. Keeping them longer than necessary can increase resource usage, tracked entities, stale state, and concurrency problems.

Detailed Explanation

Database connections are limited resources, and EF Core DbContext represents a unit-of-work-oriented stateful component. Keeping them longer than necessary can increase resource usage, tracked entities, stale state, and concurrency problems.

In ASP.NET Core, a scoped DbContext per request is a common default. Long-running background work should create appropriate scopes or contexts for bounded units of work rather than keeping one context indefinitely.

Code Example

HTTP request
   |
Scoped DbContext
   |
query/update
   |
request ends -> dispose