Lesson 04 of 4 · 15 min read · Updated

PostgreSQL Connection Pooling in .NET: Preventing Connection Exhaustion with Npgsql and EF Core

An EF Core application on PostgreSQL usually passes every test on a laptop and then fails in production with 53300: sorry, too many clients already or The connection pool has been exhausted. Nothing in the code changed. What changed is the number of processes, the traffic, and how long each DbContext keeps a connection. In this lesson you build a greenhouse telemetry API with EF Core, run three copies of it against a deliberately small PostgreSQL server, and reproduce three real failures (too many instances for the server, a DbContext that leaks its connection, a transaction held open across a slow HTTP call). Then you see what EnableRetryOnFailure does and does not fix, and size the pool from a budget that survives the same load.

Technical Requirements

  1. .NET 10 SDK
  2. Docker (PostgreSQL 17 runs in a container on port 5435)
  3. bash, for the helper scripts that start several API instances
  4. Packages: Npgsql.EntityFrameworkCore.PostgreSQL 10.0.3, EFCore.NamingConventions 10.0.1

The complete code is on the postgres-connection-pooling branch of the lesson repository.

Two Pools in Every EF Core Application

Opening a PostgreSQL connection is expensive: a TCP (and often TLS) handshake, authentication, and a new server process forked just for you. Every PostgreSQL connection is a full operating system process with its own memory, which is why max_connections is usually in the low hundreds, not thousands.

An EF Core application on PostgreSQL has two different pools, and they are easy to confuse:

PoolConfigured withWhat it reusesLimits database connections?
DbContext poolAddDbContextPool, AddPooledDbContextFactoryDbContext objects (saves allocations)No
Connection poolThe connection string you pass to UseNpgsqlPhysical PostgreSQL connectionsYes

EF Core does not hold a connection for the whole life of a DbContext. By default it opens one from the Npgsql pool when a query or SaveChanges runs, and gives it back as soon as that operation ends. Two things change this: an explicit Database.OpenConnectionAsync(), and a transaction started with Database.BeginTransactionAsync(). Both keep the connection checked out until you close it, commit, or dispose the context.

The connection pool is controlled by four connection string settings:

SettingDefaultMeaning
PoolingtrueTurn the pool on or off
Maximum Pool Size100Most physical connections one pool may open
Minimum Pool Size0Connections kept open even when idle
Timeout15 sHow long opening waits for a free pooled connection before it throws

The key word is one pool. The pool lives inside your process. The PostgreSQL server only sees the sum of every pool in every process: each API replica, each background worker, each migration job, plus your own psql session. That sum is what must fit into max_connections.

The Sample: a Greenhouse Telemetry Service

The scenario is a company that grows vegetables in 12 greenhouses. Each greenhouse has 8 sensors that post temperature and humidity readings. The API has:

  1. POST /readings – stores a SensorReading with SaveChangesAsync
  2. GET /greenhouses/{id}/climate-report – a LINQ GroupBy over the last hour, padded with ExecuteSqlRawAsync("SELECT pg_sleep(0.2)") so it behaves like a heavy report
  3. POST /greenhouses/{id}/alerts/evaluate – checks the average temperature and sends an SMS through a slow provider
  4. GET /sensors/calibration – two queries on one explicitly opened connection

The database server is intentionally tiny, so that you can exhaust it with a laptop:

docker-compose.yml

name: connection-pooling

services:
postgres:
image: postgres:17
# A deliberately small server: 40 slots, 3 of them reserved for superusers.
command: postgres -c max_connections=40 -c superuser_reserved_connections=3
environment:
POSTGRES_PASSWORD: postgres
ports:
- "5435:5432"
volumes:
- ./db/init.sql:/docker-entrypoint-initdb.d/init.sql:ro
healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres"]
interval: 2s
retries: 30

With 40 slots and 3 reserved for superusers, a normal role such as telemetry_app can use at most 37 connections. The superuser slots are what let you still log in with psql and look around when the application has used everything else.

Configuring the Pool through EF Core

Everything about the connection pool goes into the connection string that EF Core hands to Npgsql. Build it once with NpgsqlConnectionStringBuilder, so the values come from configuration and each instance can get a different limit:

src/GreenhouseTelemetry.Api/PoolSettings.cs

using Npgsql;

namespace GreenhouseTelemetry.Api;

public static class PoolSettings
{
// The pool is configured through the connection string that EF Core passes to Npgsql.
public static string BuildConnectionString(IConfiguration configuration)
{
var pool = configuration.GetSection("Pool");
var csb = new NpgsqlConnectionStringBuilder(configuration.GetConnectionString("Telemetry"))
{
Pooling = true,
MaxPoolSize = pool.GetValue("MaxPoolSize", 10),
MinPoolSize = pool.GetValue("MinPoolSize", 0),
Timeout = pool.GetValue("TimeoutSeconds", 15), // seconds to wait for a free pooled connection
CommandTimeout = 30,
ApplicationName = $"greenhouse-{configuration["InstanceName"] ?? "ingest"}" // shows up in pg_stat_activity
};
return csb.ConnectionString;
}
}

ApplicationName is cheap and pays for itself the first time something goes wrong: every server-side session shows which instance owns it.

Register the context with a pooled factory. Background code and the calibration endpoint ask the factory for a context; ordinary endpoints get a scoped TelemetryDb that comes from the same factory:

src/GreenhouseTelemetry.Api/Program.cs

var connectionString = PoolSettings.BuildConnectionString(builder.Configuration);
var retryOnFailure = builder.Configuration.GetValue<bool>("Database:RetryOnFailure");

// Pooled factory: TelemetryDb instances are reused, and the Npgsql provider keeps
// one connection pool (one NpgsqlDataSource) for this connection string.
builder.Services.AddPooledDbContextFactory<TelemetryDb>(options => options
.UseNpgsql(connectionString, npgsql =>
{
if (retryOnFailure) npgsql.EnableRetryOnFailure(maxRetryCount: 3);
})
.UseSnakeCaseNamingConvention());

// Endpoints that only need a context get a scoped one from the same factory;
// the request scope disposes it, which returns its connection to the pool.
builder.Services.AddScoped(sp => sp.GetRequiredService<IDbContextFactory<TelemetryDb>>().CreateDbContext());

Because every context is built from the same options and the same connection string, the Npgsql provider uses one connection pool per process. The RetryOnFailure switch is used later in the lesson.

scripts/start-instances.sh <instances> <maxPoolSize> [timeout] starts N copies on ports 5091, 5092, … and passes Pool__MaxPoolSize through environment variables. The demo exception handler returns the Npgsql error text with a 503, so the load generator (GreenhouseTelemetry.LoadTest) can group failures by cause.

Watching the Server with pg_stat_activity

pg_stat_activity has one row per server process. Filter on backend_type = 'client backend', because autovacuum and the checkpointer also appear there but do not use max_connections slots:

scripts/connections.sql

-- Who holds the server's connection slots right now?
SELECT application_name, state, count(*) AS connections
FROM pg_stat_activity
WHERE backend_type = 'client backend'
GROUP BY application_name, state
ORDER BY application_name, state;

-- Background processes (autovacuum, checkpointer...) do not use max_connections slots.
SELECT count(*) AS client_connections,
current_setting('max_connections')::int AS max_connections,
current_setting('superuser_reserved_connections')::int AS reserved_for_superusers
FROM pg_stat_activity
WHERE backend_type = 'client backend';

Run it as the postgres superuser (scripts/snapshot.sh) in a second terminal while the load test runs. Three state values matter:

  1. active – a query is running right now
  2. idle – the connection is open, but no query or transaction is running. It is either waiting in the pool, or it was leaked
  3. idle in transaction – a transaction is open, but no query is running. The application is doing something else while it holds the connection and its locks

Failure 1: More Pool Capacity Than the Server Has

Start three instances with Max Pool Size=20 and send 600 report requests with 120 concurrent clients, spread round-robin across the instances like a load balancer would:

scripts/start-instances.sh 3 20
scripts/load.sh GET '/greenhouses/{n}/climate-report' 120 600 3
600 requests, concurrency 120, 1,0 s, 631 req/s
latency p50 78 ms, p95 306 ms, max 521 ms
427 x 503 53300: remaining connection slots are reserved for roles with the SUPERUSER attribute
100 x 200
73 x 503 53300: sorry, too many clients already

Each instance believes it may open 20 connections, so the fleet can ask for 3 × 20 = 60, but only 37 exist. Whichever instances grow first take the slots, and every further open fails at the server. Only 100 of 600 requests succeeded. The errors come from PostgreSQL (53300), not from the pool: no single pool was full. Each setting looked reasonable by itself. Together they were wrong.

Does EnableRetryOnFailure Fix It?

53300 is a transient error for the Npgsql provider, so the first reaction is often to turn on retries. Run the same test with RETRY=true, which calls EnableRetryOnFailure(maxRetryCount: 3):

600 requests, concurrency 120, 6,1 s, 99 req/s
latency p50 206 ms, p95 4442 ms, max 4711 ms
519 x 200
73 x 503 53300: remaining connection slots are reserved for roles with the SUPERUSER attribute
8 x 503 53300: sorry, too many clients already

Retries turned 100 successes into 519, but 81 requests still failed, the p95 went from 306 ms to 4.4 seconds, and every retry was one more connection attempt against a full server. Retries hide a sizing problem; they do not fix it. There is also a side effect: with a retrying execution strategy, the alert endpoint that calls BeginTransactionAsync stops working:

The configured execution strategy 'NpgsqlRetryingExecutionStrategy' does not support user-initiated transactions. Use the execution strategy returned by 'DbContext.Database.CreateExecutionStrategy()' to execute all the operations in the transaction as a retriable unit.

Keep retries for short network blips and failovers, and wrap explicit transactions in CreateExecutionStrategy().ExecuteAsync(...) when you enable them.

Failure 2: A DbContext That Never Gives Its Connection Back

This endpoint creates a context from the factory and opens the connection explicitly, so that both calibration queries run on the same connection. It forgets to dispose the context:

src/GreenhouseTelemetry.Api/DiagnosticsEndpoints.cs

// Bug: the context is never disposed. OpenConnectionAsync tells EF Core to keep the
// connection open until the context is disposed, so it never goes back to the pool.
app.MapGet("/sensors/calibration-leaky", async (IDbContextFactory<TelemetryDb> factory) =>
{
var db = await factory.CreateDbContextAsync();
await db.Database.OpenConnectionAsync(); // both queries on one connection
return Results.Ok(await CalibrationAsync(db));
});

OpenConnectionAsync tells EF Core: "I manage this connection now, keep it open until I close it or dispose the context." Nobody does either. Start one instance with Max Pool Size=10 and Timeout=3, call the endpoint 10 times (all 10 succeed), then call any endpoint:

scripts/start-instances.sh 1 10 3
for i in $(seq 1 10); do curl -s -o /dev/null localhost:5091/sensors/calibration-leaky; done
curl -s localhost:5091/greenhouses/2/climate-report
{"error":"The connection pool has been exhausted, either raise 'Max Pool Size' (currently 10) or 'Timeout' (currently 3 seconds) in your connection string."} 503 3.041533s

This time the error comes from the Npgsql pool, after exactly the 3-second Timeout. The whole service is down, not just the buggy endpoint, because every context shares the same pool. pg_stat_activity makes the leak easy to miss:

application_name | state | connections
---------------------+--------+-------------
greenhouse-ingest-1 | idle | 10

The server sees 10 idle sessions, exactly like a healthy pool at rest. Only the application knows that those 10 are checked out by contexts that will never be disposed. Raising Max Pool Size only delays the outage. Every context you create yourself needs a scope:

src/GreenhouseTelemetry.Api/DiagnosticsEndpoints.cs

// Fix: await using disposes the context, which closes the connection back into the pool.
app.MapGet("/sensors/calibration", async (IDbContextFactory<TelemetryDb> factory) =>
{
await using var db = await factory.CreateDbContextAsync();
await db.Database.OpenConnectionAsync();
return Results.Ok(await CalibrationAsync(db));
});

// Also safe: a context injected per request is disposed by the request scope.
app.MapGet("/sensors/calibration-scoped", async (TelemetryDb db) =>
{
await db.Database.OpenConnectionAsync();
return Results.Ok(await CalibrationAsync(db));
});

The second variant is safe as well: a TelemetryDb injected into an endpoint is disposed by the request scope, which closes the explicitly opened connection. With a pool of 5, 30 calls in a row to each fixed endpoint return 30 × 200. The risky places are the ones outside a request scope: IDbContextFactory in background services, contexts created with new, and contexts stored in fields of singletons.

Failure 3: Holding a Connection While Waiting for Someone Else

The alert endpoint starts an EF Core transaction, reads the average temperature, sends an SMS (one second), adds a ClimateAlert and commits:

src/GreenhouseTelemetry.Api/AlertEndpoints.cs

// Anti-pattern: the transaction (and its connection) stays open while we wait for the SMS gateway.
app.MapPost("/greenhouses/{id:int}/alerts/evaluate-in-transaction", async (int id, TelemetryDb db) =>
{
await using var tx = await db.Database.BeginTransactionAsync();

var avg = await AverageTemperatureAsync(db, id);
if (avg > MaxTemperatureC)
{
await SendSmsAsync($"Greenhouse {id} is at {avg:F1} °C");
db.Alerts.Add(new ClimateAlert { GreenhouseId = id, Message = $"avg {avg:F1} °C", RaisedAt = DateTimeOffset.UtcNow });
await db.SaveChangesAsync();
}

await tx.CommitAsync();
return Results.Ok(new { GreenhouseId = id, AverageC = avg });
});

The SMS call has nothing to do with the database, but BeginTransactionAsync pins one connection until CommitAsync. With one instance, Max Pool Size=5, and 40 requests from 20 clients:

40 requests, concurrency 20, 8,2 s, 5 req/s
latency p50 4036 ms, p95 4174 ms, max 4174 ms
40 x 200

application_name | state | connections
---------------------+---------------------+-------------
greenhouse-ingest-1 | idle in transaction | 5

All five connections are idle in transaction: busy for the pool, doing nothing for the server, and holding any locks the transaction took. Throughput is capped at 5 requests per second, which is the pool size divided by the SMS latency. You often do not need an explicit transaction at all: SaveChangesAsync already wraps its own changes in a short transaction. Read, call the slow service with no connection held, then save:

src/GreenhouseTelemetry.Api/AlertEndpoints.cs

// Fix: read, release the connection, call the slow gateway, then write in a short transaction.
app.MapPost("/greenhouses/{id:int}/alerts/evaluate", async (int id, TelemetryDb db) =>
{
var avg = await AverageTemperatureAsync(db, id);
if (avg > MaxTemperatureC)
{
await SendSmsAsync($"Greenhouse {id} is at {avg:F1} °C");
db.Alerts.Add(new ClimateAlert { GreenhouseId = id, Message = $"avg {avg:F1} °C", RaisedAt = DateTimeOffset.UtcNow });
await db.SaveChangesAsync();
}

return Results.Ok(new { GreenhouseId = id, AverageC = avg });
});
40 requests, concurrency 20, 2,1 s, 19 req/s
latency p50 1035 ms, p95 1043 ms, max 1043 ms
40 x 200

Same pool, same SMS latency, four times the throughput, and the p50 drops from 4 seconds to the 1-second SMS call itself. On the server side, idle_in_transaction_session_timeout is a good safety net that kills sessions which stay in this state too long, but it does not replace fixing the code.

Sizing the Pool from a Connection Budget

Size pools top-down, from the server, not bottom-up from one service. For the greenhouse server:

ConsumerInstancesMax Pool SizeConnections
Ingest API31030
Alert worker, migration bundle, admin psql––7
Available to non-superusers37
Reserved for superusers3
max_connections40

Run the same load as in Failure 1 with the budgeted pool:

scripts/start-instances.sh 3 10
scripts/load.sh GET '/greenhouses/{n}/climate-report' 120 600 3
600 requests, concurrency 120, 4,1 s, 145 req/s
latency p50 815 ms, p95 872 ms, max 1066 ms
600 x 200

application_name | state | connections
---------------------+--------+-------------
greenhouse-ingest-1 | active | 10
greenhouse-ingest-2 | active | 10
greenhouse-ingest-3 | active | 10

Every request succeeded, with no retries. Requests beyond 30 concurrent queries waited in their instance's pool (that is the higher p50) instead of failing at the server. A short queue in front of a saturated database is the behaviour you want; the Timeout setting decides how long a request may queue before it fails fast. The snapshot also confirms that EF Core used exactly one pool per process: each instance stopped at 10.

Two rules follow from the budget:

  1. Autoscaling multiplies pools. If the ingest API can scale to 6 replicas, either the pool per replica must drop to 5, or the server budget must grow. Do the multiplication with the maximum replica count, not the usual one.
  2. Bigger is not faster. Past the point where the server's CPU and disks are busy, more connections only add contention. A pool slightly larger than the number of concurrent queries the server can really run is usually enough.

When an External Pooler Helps

If the budget cannot fit, for example dozens of services each with their own pool, put PgBouncer (or a managed equivalent) between the applications and PostgreSQL. In transaction mode it shares a small number of server connections between many client connections. The trade-off is that session state does not survive between transactions: session-level SET commands, advisory locks, LISTEN, and prepared statements need care, so check what your code relies on before you switch. For a handful of services, a correctly sized per-process pool, as built in this lesson, is simpler and enough.

Results

ScenarioSettingsOutcome
Pools larger than the server3 instances × 20100 / 600 OK, 500 × 53300 from PostgreSQL
Same, with EnableRetryOnFailure(3)3 instances × 20519 / 600 OK, p95 4442 ms, explicit transactions throw
Budgeted pools3 instances × 10600 / 600 OK, p50 815 ms (queued in the pool)
Context never disposed after OpenConnectionAsync1 × 10, Timeout=3After 10 calls every endpoint fails after 3 s: pool exhausted
await using context / scoped context1 × 530 / 30 OK each
SMS call inside BeginTransactionAsync1 × 55 req/s, 5 × idle in transaction
SMS call before SaveChangesAsync1 × 519 req/s, p50 1035 ms

Summary

  1. AddDbContextPool and AddPooledDbContextFactory reuse DbContext objects. The connection limit lives in the connection string you pass to UseNpgsql.
  2. The pool lives in your process. The server only sees the sum of all pools, so plan Max Pool Size × maximum instances against max_connections minus the reserved and operational slots.
  3. 53300 means the server is full (a fleet-wide sizing problem). "The connection pool has been exhausted" means one process is out of connections (a leaked context, long transactions, or a pool that is too small).
  4. EF Core returns connections after each operation, unless you call OpenConnectionAsync or BeginTransactionAsync. Then the context holds the connection until you dispose it, so dispose every context you create yourself.
  5. Keep transactions short and never wait for HTTP calls, queues or files inside one. idle in transaction in pg_stat_activity is the signal.
  6. EnableRetryOnFailure hides connection exhaustion at the cost of latency, and it requires CreateExecutionStrategy() around explicit transactions.
  7. Set Application Name on every service, and watch pg_stat_activity grouped by application and state.

The idea for this lesson came from PostgreSQL Connection Pooling: How to Prevent Connection Exhaustion in Production by Vivek Kumar on C# Corner. The scenario, code and measurements here are original.