Lesson 04 of 4 · 15 min read · Updated
PostgreSQL Connection Pooling in .NET: Preventing Connection Exhaustion with Npgsql and EF Core
On this page
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
- .NET 10 SDK
- Docker (PostgreSQL 17 runs in a container on port 5435)
- bash, for the helper scripts that start several API instances
- Packages:
Npgsql.EntityFrameworkCore.PostgreSQL10.0.3,EFCore.NamingConventions10.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:
| Pool | Configured with | What it reuses | Limits database connections? |
|---|---|---|---|
| DbContext pool | AddDbContextPool, AddPooledDbContextFactory | DbContext objects (saves allocations) | No |
| Connection pool | The connection string you pass to UseNpgsql | Physical PostgreSQL connections | Yes |
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:
| Setting | Default | Meaning |
|---|---|---|
Pooling | true | Turn the pool on or off |
Maximum Pool Size | 100 | Most physical connections one pool may open |
Minimum Pool Size | 0 | Connections kept open even when idle |
Timeout | 15 s | How 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:
POST /readings– stores aSensorReadingwithSaveChangesAsyncGET /greenhouses/{id}/climate-report– a LINQGroupByover the last hour, padded withExecuteSqlRawAsync("SELECT pg_sleep(0.2)")so it behaves like a heavy reportPOST /greenhouses/{id}/alerts/evaluate– checks the average temperature and sends an SMS through a slow providerGET /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
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
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
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
Run it as the postgres superuser (scripts/snapshot.sh) in a second terminal while the load test runs. Three state values matter:
active– a query is running right nowidle– the connection is open, but no query or transaction is running. It is either waiting in the pool, or it was leakedidle 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:
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):
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:
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
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:
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:
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
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
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:
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
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:
| Consumer | Instances | Max Pool Size | Connections |
|---|---|---|---|
| Ingest API | 3 | 10 | 30 |
| Alert worker, migration bundle, admin psql | – | – | 7 |
| Available to non-superusers | 37 | ||
| Reserved for superusers | 3 | ||
max_connections | 40 |
Run the same load as in Failure 1 with the budgeted pool:
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:
- 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.
- 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
| Scenario | Settings | Outcome |
|---|---|---|
| Pools larger than the server | 3 instances × 20 | 100 / 600 OK, 500 × 53300 from PostgreSQL |
Same, with EnableRetryOnFailure(3) | 3 instances × 20 | 519 / 600 OK, p95 4442 ms, explicit transactions throw |
| Budgeted pools | 3 instances × 10 | 600 / 600 OK, p50 815 ms (queued in the pool) |
Context never disposed after OpenConnectionAsync | 1 × 10, Timeout=3 | After 10 calls every endpoint fails after 3 s: pool exhausted |
await using context / scoped context | 1 × 5 | 30 / 30 OK each |
SMS call inside BeginTransactionAsync | 1 × 5 | 5 req/s, 5 × idle in transaction |
SMS call before SaveChangesAsync | 1 × 5 | 19 req/s, p50 1035 ms |
Summary
AddDbContextPoolandAddPooledDbContextFactoryreuseDbContextobjects. The connection limit lives in the connection string you pass toUseNpgsql.- The pool lives in your process. The server only sees the sum of all pools, so plan
Max Pool Size× maximum instances againstmax_connectionsminus the reserved and operational slots. 53300means 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).- EF Core returns connections after each operation, unless you call
OpenConnectionAsyncorBeginTransactionAsync. Then the context holds the connection until you dispose it, so dispose every context you create yourself. - Keep transactions short and never wait for HTTP calls, queues or files inside one.
idle in transactioninpg_stat_activityis the signal. EnableRetryOnFailurehides connection exhaustion at the cost of latency, and it requiresCreateExecutionStrategy()around explicit transactions.- Set
Application Nameon every service, and watchpg_stat_activitygrouped 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.