The message is Execution Timeout Expired. The timeout period elapsed prior to completion of the operation or the server is not responding., thrown as a SqlException with Number -2 from Microsoft.Data.SqlClient. It means one command ran longer than CommandTimeout, which is 30 seconds unless you changed it. The fast fix is o.CommandTimeout(60) inside UseSqlServer(...), but that only buys time. In most cases the real cause is a query that scans a table, a transaction somebody else is holding open, or a pool that is starved, and the sections below show how to tell which one you have. The same advice applies to Npgsql and MySQL with different wording, covered further down.
A second family of errors looks similar and gets mixed up with it: "A transient failure has occurred", "An error occurred using the connection to database", "A connection was successfully established with the server, but then an error occurred during the login process", and Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. Those are about connecting, not about the query. They are fixed with retries, pool sizing and connection string settings, and they matter more once your database is on another machine, which is the normal case for a hosted database.
Which timeout is it?#
Three different timeouts produce messages that read almost the same. Fixing the wrong one is the most common reason a "fix" does not work.
| Message contains | Real cause | Setting involved |
|---|---|---|
Execution Timeout Expired | One command took too long | CommandTimeout |
obtaining a connection from the pool | Every pooled connection is busy | Max Pool Size |
Connection Timeout Expired or Connect Timeout | Could not open a connection in time | Connect Timeout |
The exact text matters. Read the stack trace to see where it was thrown. If the top frames are SqlCommand.ExecuteReader or SqlDataReader.Read, a command was running. If they are SqlConnection.Open or SqlConnectionFactory, you never got as far as sending the query. A pool timeout also says max pool size was reached in the message, and it usually appears as a symptom of slow queries, not as its own disease: connections are all busy because queries are slow, so the next request waits for one and gives up after the connect timeout.
On the other providers the names differ:
- Npgsql (PostgreSQL):
Npgsql.NpgsqlException: Exception while reading from streamwith an innerSystem.TimeoutException: Timeout during reading attempt, whenCommand Timeout(default 30 seconds) is exceeded. Pool exhaustion readsThe connection pool has been exhausted, either raise 'Maximum Pool Size' (currently 100) or 'Timeout' (currently 15 seconds). - MySqlConnector / Pomelo (MySQL):
MySqlConnector.MySqlException: The Command Timeout expired before the operation completed, governed byDefault Command Timeout(default 30 seconds).
Defaults vary a little between driver versions, so check the documentation of the version you have installed before relying on a number. The pattern, 30 seconds for a command and 15 seconds to connect, has been stable for years.
The quick fix: raise CommandTimeout#
If a report, an export or a one-off job legitimately takes longer than 30 seconds, tell EF Core. Do it where the context is registered:
builder.Services.AddDbContext<AppDbContext>(options => options.UseSqlServer( builder.Configuration.GetConnectionString("Default"), sql => sql.CommandTimeout(60)));The same call exists on the other providers: UseNpgsql(cs, npg => npg.CommandTimeout(60)) and UseMySql(cs, serverVersion, my => my.CommandTimeout(60)). The value is in seconds, and 0 means no timeout at all, which is almost never what you want in a web request.
You can also set it for one operation instead of the whole application:
await using var db = await factory.CreateDbContextAsync(ct);db.Database.SetCommandTimeout(TimeSpan.FromMinutes(5));var rows = await db.Orders.Where(o => o.Year == 2025).ToListAsync(ct);That second form is the one to prefer. A global 60-second timeout means a web request can hold a database connection and a worker for a full minute before anybody finds out something is wrong. A long timeout for the nightly export and the default for everything else is the safer shape. For migrations, which run DDL against large tables and routinely exceed 30 seconds, see EF Core migrations in production, where the timeout is set on the migrator and not on the web app.
The client timeout also does not cancel work on the server in every case. When it fires, the driver sends an attention signal and the server should abort the statement, but a long rollback can follow. If you see the database still busy after your app logged the exception, that tail is why.
Find the slow query before touching anything else#
You cannot fix a query you have not seen. EF Core already knows how long each command takes; you only have to listen.
Turn on command logging for the Microsoft.EntityFrameworkCore.Database.Command category. In appsettings.json:
{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft.EntityFrameworkCore.Database.Command": "Information" } }}Each line then reads Executed DbCommand (4,812ms) [Parameters=[...], CommandType='Text', CommandTimeout='30'] followed by the SQL. Search the log for large millisecond values and for the commands that were Failed executing DbCommand. Parameter values are hidden by default; EnableSensitiveDataLogging() shows them, and you should keep that off in production because it writes user data to the log. For a quick local look, optionsBuilder.LogTo(Console.WriteLine, LogLevel.Information) does the same without configuration.
Logging every command is noisy on a busy service. A command interceptor lets you log only the slow ones:
using System.Data.Common;using Microsoft.EntityFrameworkCore.Diagnostics;public sealed class SlowQueryInterceptor(ILogger<SlowQueryInterceptor> log) : DbCommandInterceptor{ private static readonly TimeSpan Threshold = TimeSpan.FromSeconds(1); public override ValueTask<DbDataReader> ReaderExecutedAsync( DbCommand command, CommandExecutedEventData data, DbDataReader result, CancellationToken ct = default) { if (data.Duration > Threshold) log.LogWarning("Slow query {Ms} ms: {Sql}", (long)data.Duration.TotalMilliseconds, command.CommandText); return base.ReaderExecutedAsync(command, data, result, ct); }}Register it with options.AddInterceptors(...) on the context options. It only sees queries that finish, so pair it with the failed-command log line for the ones that do not. If you have a LINQ query in front of you and want the SQL without running it, call .ToQueryString() on the IQueryable and paste the output into your database client.
Once you have the SQL, run it in the database with the execution plan switched on. How to read the plan is database-specific, and we have a post for each: SQL Server Query Store and slow queries, EXPLAIN ANALYZE for slow PostgreSQL queries and the MySQL slow query log.
The usual suspects in EF Core queries#
After a few dozen of these investigations the same shapes keep turning up.
- A missing index on the filtered column.
Where(o => o.CustomerId == id)over a table with a million rows and no index onCustomerIdis a full scan every time. It was fast in development with 500 rows. EF Core only creates indexes for foreign keys by convention; anything else you filter or sort by needsmodelBuilder.Entity<Order>().HasIndex(o => o.CreatedAt), or the equivalent[Index]attribute, plus a migration. - An N+1 pattern. A loop that touches a navigation property and triggers one query per row turns one request into hundreds of round trips. Each one is fast, the total is not, and each pays network latency. Use
Include, or better, project only what you need withSelect. - A cartesian explosion. Several collection
Includecalls in one query make the database return the product of the child rows, which can be millions of rows for a handful of parents. EF Core logs a warning about this. Add.AsSplitQuery()to the query, orUseQuerySplittingBehavior(QuerySplittingBehavior.SplitQuery)globally. Split queries use several round trips, so they trade latency for volume. - Loading entities you only read. Tracking costs memory and time.
AsNoTracking()on read-only queries is a free win. - Client evaluation of a filter. Modern EF Core throws instead of silently pulling a whole table when it cannot translate a
Where, butToList()followed by LINQ-to-objects does the same thing by hand. Keep theWherebefore the materialisation. - Wide results. Returning a 2 MB
nvarchar(max)column in a list view, for every row, is slow before the database does anything clever. - Parameter sniffing and stale plans. A query that is fast with one parameter value and slow with another, on SQL Server, is often a plan compiled for the wrong value. Query Store, linked above, is the proper tool to see it.
- Paging with `Skip` on huge offsets.
Skip(500000).Take(50)still reads and discards 500,000 rows. Keyset paging, filtering on the last seen id, stays fast.
None of these are fixed by a bigger timeout. Several are fixed by an index and a single line of C#.
When the query is not slow: blocking and locks#
Some Execution Timeout Expired errors come from queries that are fast on their own. They wait. Another session holds a lock, and your command sits behind it until the clock runs out. Typical sources: a long-running transaction that was started and never committed, a background job updating a large table in one statement, a migration holding a schema lock, or an await inside a transaction while the code calls an external service.
On SQL Server, ask the server what is waiting:
SELECT r.session_id, r.blocking_session_id, r.wait_type, r.wait_time, r.status, t.textFROM sys.dm_exec_requests AS rCROSS APPLY sys.dm_exec_sql_text(r.sql_handle) AS tWHERE r.session_id <> @@SPID;A non-zero blocking_session_id means that request is waiting for another session, and wait_type of LCK_M_S, LCK_M_U or LCK_M_X confirms a lock wait. Follow the chain to the session at the head: that is the one to fix. On PostgreSQL the equivalent is pg_stat_activity with wait_event_type = 'Lock' and pg_blocking_pids(pid). MySQL has the same story with its own error for it, covered in MySQL lock wait timeout exceeded.
The fix is in the code: keep transactions short, never call an HTTP API or wait for user input inside one, and do bulk updates in batches. EF Core 7 and later have ExecuteUpdateAsync and ExecuteDeleteAsync, which turn a "load 200,000 rows, change them, save" loop into one set-based statement.
Transient connection failures and EnableRetryOnFailure#
Connecting to a database across a network fails sometimes for reasons that disappear a second later: a TCP connection reset, a server restart, a login that took too long, a brief overload. EF Core has a feature for exactly this, an execution strategy that retries the operation.
builder.Services.AddDbContext<AppDbContext>(options => options.UseSqlServer( builder.Configuration.GetConnectionString("Default"), sql => sql.EnableRetryOnFailure( maxRetryCount: 5, maxRetryDelay: TimeSpan.FromSeconds(10), errorNumbersToAdd: null)));Called with no arguments, EnableRetryOnFailure() uses a maximum of 6 retries and a maximum delay of 30 seconds between them, with exponential backoff and some random jitter. UseNpgsql and UseMySql have the same method, and Npgsql accepts extra error codes through errorCodesToAdd. Each provider ships a list of errors it considers transient. Treat that list as provider-specific and check the provider's source or documentation before assuming a particular error is on it; the SQL Server list, as far as we know, includes network failures and a number of Azure-style throttling codes, but a deadlock victim or a plain timeout is worth testing for rather than assuming.
Three rules keep this feature from hurting you.
- Retrying a slow query makes things worse. If a command timeout were retried six times, one stuck request becomes six, each taking another 30 seconds and holding a connection. Check what your provider version does with timeouts before enabling retries on a service that has a slow-query problem. Fix the query first.
- Manual transactions need to be wrapped. An execution strategy has to be able to replay the whole unit of work, so
BeginTransactionAsyncon its own throwsThe configured execution strategy 'SqlServerRetryingExecutionStrategy' does not support user-initiated transactions. Wrap the transaction in the strategy:
var strategy = db.Database.CreateExecutionStrategy();await strategy.ExecuteAsync(async () =>{ await using var tx = await db.Database.BeginTransactionAsync(ct); // do the work, SaveChangesAsync, anything that must be atomic await tx.CommitAsync(ct);});- The work must be safe to run twice. If the connection drops after the commit but before the acknowledgement arrives, EF Core can retry something that already succeeded. EF Core tries to verify a commit's result in some cases, but your own code should still be idempotent for inserts that matter: a unique key, or a client-generated id, turns a duplicate into an error you can handle.
Retries are for brief faults. If the database is down for ten minutes, six retries over a minute will not save you, and a circuit breaker or a clear "service unavailable" response is the correct answer.
Idle connection resiliency in the driver
Microsoft.Data.SqlClient has a separate, lower-level feature: ConnectRetryCount (default 1) and ConnectRetryInterval (default 10 seconds) in the connection string. They let the driver silently re-establish a connection that dropped while idle in the pool. It complements EF Core's retries rather than replacing them. A long Connect Timeout is not a retry mechanism either; a lower value with real retries behind it fails faster and recovers sooner.
Pooling: stop opening connections you do not need#
ADO.NET pools connections by connection string. Each DbContext opens a connection when a query runs and returns it to the pool when the context is disposed or the query finishes reading. Max Pool Size defaults to 100 for SqlClient and, in current Npgsql, also 100, per process and per distinct connection string. The pool exhaustion message appears when all of them are checked out and a request waits past Connect Timeout.
Exhaustion is nearly always one of these:
- Slow queries keep connections busy longer than traffic expects. Fix the query.
- A leaked context. A
DbContextcreated by hand and never disposed, or aDataReaderleft open, holds its connection. Alwaysawait using, or let dependency injection own the lifetime. - Sync over async.
.Resultor.Wait()on a database call blocks a thread pool thread while it holds a connection; under load the thread pool starves and everything times out together. Useasyncall the way. - A shared context. A
DbContextis not thread-safe. Using one instance in parallelTask.WhenAllbranches throws, and sharing a singleton context holds a connection for the lifetime of the app. - Too many instances for the server. Ten app instances times a pool of 100 is a thousand potential connections against a database plan that allows far fewer.
Raising Max Pool Size to 500 is the instinctive answer and usually the wrong one: it lets more slow queries pile onto a database that is already struggling. The arithmetic of sizing a pool, and why smaller is often faster, is in connection pools and limits.
EF Core has its own pool that people confuse with this. AddDbContextPool<AppDbContext>(...) reuses DbContext instances, default maximum 1024, to save the cost of constructing them. It does not pool database connections and it does not fix pool exhaustion. For a service that creates contexts in background tasks, AddDbContextFactory with await using var db = await factory.CreateDbContextAsync() makes the lifetime obvious.
A reasonable connection string for a small SQL Server database on a hosted plan:
Server=host,port;Database=app;User Id=app;Password=...;Encrypt=True;TrustServerCertificate=False;Connect Timeout=15;Max Pool Size=40;Min Pool Size=2For the certificate and encryption settings, which are the other common cause of "error occurred during the login process", see SQL Server connection strings.
Timeouts against a hosted database#
When the database stops being on localhost, three things change.
First, latency is a multiplier. A page that issues 80 sequential queries costs 80 round trips. At 0.2 ms on one machine nobody notices; at several milliseconds across a network it is a noticeable fraction of a second, and an N+1 loop that "worked fine" on your laptop becomes the slow page. Fewer, larger queries win. Put the application and the database close together: on RE:NODE you can host the app on app hosting (C#/.NET is one of the runtimes) and the database on database hosting (PostgreSQL, MySQL 8.4 or SQL Server 2022 Express, with host, port and credentials generated per server). Whichever host you use, measure the round-trip time from your own app to the database instead of assuming it is small.
Second, the plan's CPU is a hard limit. A database server on a small plan is throttled to the share you bought; heavy queries do not crash it, they run slowly. A server at its CPU limit is slow, not broken, and a query that took 8 seconds on your workstation can take 40 on a one-core share. Watch the graphs in the panel while the slow request runs: if CPU sits at the ceiling the plan is undersized or the query is wasteful, and the earlier sections tell you which. On the SQL Server line, Express edition limits each database to 10 GB, so a table-heavy database that grows may hit that long before it hits a timeout. Express also has its own CPU and memory limits set by Microsoft; read the current edition limits in Microsoft's documentation.
Third, connections come from a fixed budget. A database plan allows a finite number of simultaneous connections, and what that number is depends on the engine and its configuration. Add up every pool in every process that connects, including the migrator and any worker, and keep the total comfortably below it. If you hit too many connections or its siblings, the post on connection pools and limits walks through the numbers.
If the app and database both live on RE:NODE and you cannot connect at all, the problem is not a timeout, so confirm the host and port from the panel (SQL Server's name in SSMS is host,port with a comma) before you change retry settings. A general setup guide for .NET against each engine is in .NET with PostgreSQL, MySQL or SQL Server.
Cancellation, so the server stops too#
Pass the CancellationToken into every EF Core call: ToListAsync(ct), SaveChangesAsync(ct). ASP.NET Core supplies HttpContext.RequestAborted as a minimal API or controller parameter. When a client gives up or a proxy times out the request, the query is cancelled instead of continuing to run for a user who has left. Without it, the 30-second query keeps burning database CPU after the request has failed, and the next retry from the impatient user starts another.
This also gives you a place to set a deadline that is shorter than the database timeout. A CancellationTokenSource with CancelAfter(TimeSpan.FromSeconds(10)) linked to the request token fails an interactive page quickly with a clear message while a background job keeps its generous CommandTimeout.
A checklist from error to fix#
- Read the exact message and the top stack frames: command, pool or connect.
- Turn on
Microsoft.EntityFrameworkCore.Database.Commandlogging and find the commands with large durations. - Run that SQL in the database with the plan on; look for a scan where you expected a seek.
- Check for blocking while the problem is live (
sys.dm_exec_requests,pg_stat_activity). - Add the index, reshape the query or batch the write. Re-measure.
- Only then adjust
CommandTimeoutfor the jobs that really are long. - Add
EnableRetryOnFailurefor the brief network faults, with transactions wrapped in the execution strategy. - Size the pool for the database, not for the app, and pass cancellation tokens everywhere.
FAQ#
What is the default EF Core command timeout?
30 seconds for SQL Server (the SqlClient default), Npgsql and MySqlConnector, all configurable. EF Core only overrides it when you call CommandTimeout(...) on the provider options or Database.SetCommandTimeout(...) on a context.
Should I set CommandTimeout to 0?
No. Zero means wait for ever, so a blocked query holds a connection and a request thread indefinitely, and the pool exhausts silently. Give long jobs a generous finite value and keep the default elsewhere.
Does EnableRetryOnFailure fix Execution Timeout Expired?
Not by itself, and it can make a slow query worse by repeating it. It is meant for transient connection faults. Fix the query or the lock first, and check how your provider version classifies timeouts.
Why does it only time out in production?
Production has more rows, concurrent users and network latency than your laptop, and its CPU share is limited. A query with a missing index is invisible at 500 rows and fatal at 5 million. Reproduce it against a copy of production data, with logging on.
Is Max Pool Size 100 too high?
For a small hosted database, often yes. A pool that large lets the app open far more concurrent queries than the server can run, so everything gets slower together. Start nearer 20 to 40 and measure.
Do these fixes apply to MySQL and PostgreSQL?
The concepts do, and the settings have provider-specific names: Command Timeout in Npgsql, Default Command Timeout in MySqlConnector, and the same EnableRetryOnFailure call on both EF Core providers. The diagnostics differ, which is why the linked posts cover each engine.


