Articles

How to fix too many connections in FastAPI and PostgreSQL

Diagnose FastAPI pool timeouts and PostgreSQL connection limits, budget for replicas and deploys, and test recovery with a two-connection example.

Updated

If PostgreSQL reports too many connections, first check who refused the connection. PostgreSQL SQLSTATE 53300 means the server refused a connection. A psycopg PoolTimeout means the app did not get a connection from its own pool before the deadline. They can look alike from the browser, especially if the pool is trying and failing to create new connections in the background.

Gregale publishes this guide. The demo uses FastAPI, psycopg and a private PostgreSQL database.

Check which limit you hit

SignalWhat to investigate
PoolTimeout or TooManyRequests in psycopg_poolLong checkouts, slow SQL, a growing wait queue, or failures to open or replace connections.
PostgreSQL 53300 and too many connections for roleThe connection allowance for that database role, including other app replicas and jobs using that login.
PostgreSQL 53300 and too many clients alreadyTotal server connections and slots reserved for administration. Use the database or pooler logs to identify the limit.

An HTTP 503 alone does not distinguish them. Check application and database logs around the same timestamp before resizing a database or raising a pool limit. See the psycopg pool docs and PostgreSQL error codes.

Calculate the pool budget at peak, not at idle

With one pool per process, count replicas × worker processes × pool max for each release or service that can run at the same time. With direct PostgreSQL connections, three replicas, two workers per replica and four connections per worker can open 24 connections. A fourth replica during a rollout raises that to 32. Leave room for jobs, migrations and administration. If your driver can open overflow connections, count those too.

With a transaction pooler, this arithmetic estimates app-to-pooler connections, not PostgreSQL server sessions. Model server capacity and simultaneous transactions separately. Gregale's standard DATABASE_URL is in transaction-pooling mode; don't rely on session state persisting across transactions. Use a separate migration credential when changing the schema.

For a read-only Gregale estimate, use:

bash
gregale postgres capacity plan DB --app APP --extra-instances 1 --pool-max 8 --json

Here eight is the total of both worker pools per new instance. The preview uses a budget snapshot, not a live count of SQL sessions. An unknown result is not spare headroom.

Bound the wait and release the connection

Create one pool per process, set max_size, cap the number of waiters, and set a checkout timeout that leaves time for the SQL itself. Return the lease as soon as your transaction is over; don't keep it while you wait for a remote API or stream a response to the browser. On a busy pool, use a specific HTTP 503 and a small Retry-After rather than waiting until the edge times out. Retry only requests that are safe to repeat, and use backoff.

Download the runnable demo. It briefly holds two leases from a single app pool. One extra HTTP request then gets 503 {"code":"app_pool_busy"}. After the two leases return, the next call gets 200 {"value":1} from PostgreSQL. The holds use autocommit and do not leave sleeping database transactions.

What we verified

With local PostgreSQL, the pool checkout returned the expected 503 and recovered. We separately gave a local test role just one slot: its second direct connection produced SQLSTATE 53300, and a new connection worked after the first closed. We did not try to exhaust the hosted PostgreSQL server.

On a private Gregale Scale app, a single test request held two connections in the application and ran the extra checkout in that same process. It returned the exact 503 and retry header. The next independent HTTPS request got a 200 from the same PostgreSQL-backed app. The test did not require parallel requests to reach one instance. The read-only capacity preview modeled two extra connections for a replica, but its available database headroom was unknown.

Questions

Is a FastAPI pool timeout the same as PostgreSQL too many connections?

No. A pool timeout means the application did not obtain a connection before its deadline. PostgreSQL SQLSTATE 53300 means the server refused a connection. Check both logs because a server refusal can also leave a pool unable to fill.

How many PostgreSQL connections can my FastAPI deployment open?

With one pool per process, multiply replicas by worker processes and maximum connections per pool. Include overlapping releases, jobs and any overflow connections. A transaction pooler can use fewer PostgreSQL server sessions than it has application clients.