Error: System.Exception: failed InternalServerError: An exception was thrown while activating - 53,300 database connection errors
Description:
If you are getting this type of errors on your datadogs -> error sections then how to trouble shoot those?
To address this, we have implemented the following fix and will continue to monitor its impact.
Solution Implemented:
Search this line in your API code - Ctl+ shift + F = Database.EnsureCreated();
Removed the following line from the API startup configuration: Database.EnsureCreated();
Why This Change Was Required
Purpose of EnsureCreated()
- Intended only for local development
- Suitable for in-memory or demo databases
Behavior
- Checks if the database exists
- Automatically creates the database and tables from the EF model
- Completely bypasses EF Core migrations
The issue is that Database.EnsureCreated() executes on every DbContext initialization, which triggers a database existence/schema check each time. In a high-traffic production API, this results in excessive DB connections and initialization calls.
This behavior is well-documented by EF Core: EnsureCreated() is intended only for local or test scenarios and should not be used in production systems with an existing database.
The change is based on:
- Known EF Core behavior of EnsureCreated()
- The fact that our DB schema is already managed outside the API
Why It Caused Issues in Our Environment
- Executes on every DbContext creation
- Triggers repeated database initialization checks
- Leads to excessive database connections
- Results in large spikes in connection errors and timeouts
Result After Fix
- Database connection usage dropped significantly
- ~53,300 database connection errors stopped
- Security API timeouts no longer observed
0 Comments
If you have any queries, please let me know. Thanks.