You set a 10-second timeout on an API endpoint. A request takes longer than expected, the client receives an error, and the connection closes. But when you check PostgreSQL, the query is still running.
This is easy to miss until it becomes a production problem. A few slow queries might not cause much trouble. Hundreds of requests timing out while their database work continues can consume connections, increase database load, and slow down requests that would otherwise finish normally.
The confusing part is that the API appears to have stopped working on the request. The database has not necessarily received that message.
An HTTP timeout and a database query cancellation are two different things. Fixing this problem means finding where the cancellation signal gets lost and deciding what should happen to the database operation when the client stops waiting.
Why the Query Survives the Timeout
Consider a request passing through Nginx, a FastAPI application, a PostgreSQL driver, and PostgreSQL itself. Each component has its own view of the request's lifetime.
If Nginx returns a 504 Gateway Timeout, it means the proxy could not get a usable response within its configured limit. It does not prove that the upstream application stopped working. The application might still be waiting for PostgreSQL, and PostgreSQL might still be executing the query.
A client disconnect creates a similar situation. The server may eventually detect the disconnect, but that does not automatically cancel every operation already started on the server.
The result depends on how the framework handles cancellation, whether the database driver supports it, and whether the application passes cancellation through to the query.
Remark: Returning an HTTP error is not the same as cancelling the work that was started to produce the response.
First, Find Out What PostgreSQL Is Doing
Before changing timeouts or increasing the connection pool, check whether the database query is actually still running.
PostgreSQL exposes current session activity through pg_stat_activity. This query shows active statements in the current database, how long they have been running, and whether they are waiting on something:
SELECT
pid,
now() - query_start AS running_for,
state,
wait_event_type,
wait_event,
left(query, 160) AS query
FROM pg_stat_activity
WHERE datname = current_database()
AND state = 'active'
AND pid <> pg_backend_pid()
ORDER BY query_start;
Look for statements that have been running longer than expected. A query spending time waiting on a lock needs a different investigation from one actively consuming database resources.
There is one limitation: PostgreSQL cannot tell you from this view alone whether the original HTTP client is still connected. Match the query's timing with your application logs, request IDs, and traces.
If the same queries remain active after their corresponding requests time out, you have a reason to investigate cancellation. If they disappear promptly, the problem may instead be slow queries, connection acquisition, or another part of the request lifecycle.
Make Cancellation Reach the Database
The next question is whether your application tells the database driver to stop when a request is no longer needed.
In an asynchronous Python application, for example, cancellation of a coroutine does not guarantee that every database operation it started has been cancelled. The behavior depends on the driver, framework, and how the query is executed.
The same issue exists in Node.js and other runtimes. A client disconnect may produce a cancellation signal, but the database operation stops only if that signal reaches a cancellation-aware API or driver.
Check the path in order:
- Does your framework detect the client disconnect or request deadline?
- Does the application actually cancel the running database operation?
- Does the database driver send a cancellation request to the server?
- Does the code clean up its session and transaction after cancellation?
It is worth testing this directly rather than assuming that a request handler returning an error means its database work has stopped.
Remark: Request deadlines and client disconnects are not interchangeable. A server may need to cancel an operation because it exceeded an internal deadline even when the client remains connected.
Put a Limit on Long-Running Statements
Even with application-level cancellation, a database-side timeout provides another layer of protection.
PostgreSQL's statement_timeout limits how long a statement can run. For example, this setting applies a five-second limit within the current transaction:
SET LOCAL statement_timeout = '5s';
Because SET LOCAL is transaction-scoped, execute it inside an active transaction before the statement you want to limit. It is not a universal five-second timeout for all future queries.
PostgreSQL also supports configuration at other scopes, including individual roles and databases. Choose a limit that matches the workload. A short interactive API query and a report that legitimately scans millions of rows may need very different limits.
See the PostgreSQL documentation on client connection defaults for the behavior and scope of statement_timeout.
One detail deserves attention: when a statement times out inside a transaction, PostgreSQL reports an error and the transaction generally remains aborted until it is rolled back. The application must handle that outcome before attempting to reuse the connection.
Remark: A database-side timeout is a safety limit, not a substitute for propagating cancellation from the application.
What If a Query Is Already Stuck?
During an incident, you may need to cancel a query manually. PostgreSQL provides pg_cancel_backend(pid), which asks the backend identified by the PID to cancel its current query.
The PID can be obtained from pg_stat_activity. The cancellation request is subject to the server's permissions and execution state.
PostgreSQL also has pg_terminate_backend(pid), but this terminates the session rather than merely requesting cancellation of its current statement. That is a more disruptive action and should not be the default response to every slow query.
Before retrying a write operation, establish what happened to the original transaction. Cancellation does not undo a transaction that has already committed, and external side effects such as a payment may have succeeded before the application saw an error.
Manual cancellation can help restore service, but it will not fix an application that keeps abandoning queries. For that, the cancellation path and timeout policy need to be corrected.
Connection Pools Are Often Where the Problem Becomes Visible
A single abandoned query may go unnoticed. The problem becomes more obvious when timed-out requests accumulate.
Each running query may occupy a database connection. New requests then wait for an available connection, even if the original clients have long since given up. Eventually the application reports connection-pool timeouts, and requests that should be quick begin failing too.
Increasing the pool size can temporarily reduce the waiting, but it may simply allow more abandoned queries to run at once. The database still has finite CPU, memory, and connection capacity.
Track database activity alongside the application's pool metrics. If checked-out connections stay high while request timeouts increase, compare those observations with the active queries and their durations. This helps distinguish a genuine capacity problem from connections being held by work that should have ended.
Not Every Request Should Cancel Its Work
There is an important exception to all this: some operations are supposed to continue after the client disconnects.
A user might start generating a large report or submit an order for asynchronous processing. Once the application accepts that work, disconnecting the browser should not necessarily cancel it.
In that situation, give the operation a lifecycle independent of the HTTP request. A background job, durable queue, or stored operation status lets the client check progress later without keeping the original request open.
For a read query whose result is no longer needed, cancellation will usually save resources. For a write operation, the application must account for whether the operation has already committed or produced external side effects.
The right rule is not “cancel everything when a client disconnects.” It is to decide which operations belong to the request and which have been accepted as independent work.
A Practical Way to Debug It
When you see database activity continuing after an API timeout, avoid changing every timeout setting at once.
Start by confirming which layer produced the error. Inspect PostgreSQL's active queries and correlate them with application logs. Then test whether cancellation reaches the driver, and apply an appropriate statement_timeout as a backstop.
Finally, verify the transaction state and connection cleanup after a query is cancelled. Repeat the test under concurrent load; a single request may behave correctly while many overlapping timeouts expose a race or resource leak.
The important measurement is not merely how quickly the API returns an error. It is whether the work that is no longer needed actually stops.
Conclusion
A database query can outlive an API request because a proxy timeout, client disconnect, application cancellation, and database cancellation are separate events. Unless the application and driver connect those events correctly, PostgreSQL may continue working after the client has stopped waiting.
Use pg_stat_activity to confirm what is happening, propagate cancellation through the database driver, and configure a server-side statement timeout appropriate to your workload. Handle transaction rollback carefully, and separate genuinely asynchronous jobs from request-bound work.
That is how you prevent a simple API timeout from turning into a database capacity problem.



