---
title: "A Cloud Run request timed out, but its PostgreSQL query is still running | Proofline"
description: "Cloud Run's request timeout closes the caller's connection and returns 504, but it stops neither the container nor the query."
url: https://proofline.sh/learn/cloud-run-request-timeout-postgres-query-keeps-running/
---

[Learning center](/learn/)

# A Cloud Run request timed out, but its PostgreSQL query is still running

Cloud Run's request timeout closes the caller's connection and returns 504, but it stops neither the container nor the query. The query keeps its database connection, and any locks it holds, until it finishes. Set statement\_timeout below the request timeout, and look for such queries in pg\_stat\_activity by how long they have been active.

Broken dependencies The Proofline team November 23, 2026 6 min read

## How it shows up

Callers receive HTTP 504 after exactly the service's request timeout, five minutes unless someone changed it. The application logs nothing unusual at that moment, because from inside the container the request is still running. Minutes later the database shows active queries from the service that are older than any request could be, the service's pool runs short, and callers who retried have started the same work again. Nothing failed to connect, so [the four stages](/learn/cloud-run-cloud-sql-connection-errors/#stage) show nothing until the pool or the table runs out.

Cloud Run's documentation states the cause. When a service does not respond within the request timeout, Cloud Run closes the network connection and returns a 504. Closing the connection does not terminate the container instance, which may continue processing the aborted request. The timeout defaults to 300 seconds and can be raised to 3,600; frameworks may have their own timeouts, and callers can impose shorter ones. A caller that reconnects starts a new request, which may land on another instance. [Request timeout](https://cloud.google.com/run/docs/configuring/request-timeout)

PostgreSQL has no reason to stop the query. The application's connection to the database is still open and working, because the instance is still running. `client_connection_check_interval`, which lets PostgreSQL abort a query whose client has disconnected, does not help here: the database client, the instance, never left. [`client_connection_check_interval`](https://www.postgresql.org/docs/current/runtime-config-connection.html)

## Check 1: do the 504s end at the timeout?

Read the revision's timeout and the request log:

```
gcloud run revisions describe REVISION \
  --project PROJECT --region REGION \
  --format='value(spec.timeoutSeconds)'

gcloud logging read \
  'resource.type="cloud_run_revision"
   AND resource.labels.service_name="SERVICE"
   AND logName="projects/PROJECT/logs/run.googleapis.com%2Frequests"
   AND httpRequest.status=504
   AND timestamp>="START_TIME"' \
  --project PROJECT --order=asc --limit=200 \
  --format='value(timestamp, labels.instanceId, httpRequest.latency, httpRequest.requestUrl)'
```

`spec.timeoutSeconds` is the maximum time an instance has to respond to a request. 504s with a latency at that value are request timeouts. 504s that come back faster have another source, and this guide does not apply. [RevisionSpec](https://cloud.google.com/run/docs/reference/rest/v1/RevisionSpec) · [LogEntry HttpRequest](https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry)

## Check 2: is the query still running?

Look for active sessions from the service older than the timeout. If the application names its connections after the revision ([how](/learn/which-cloud-run-revision-holds-cloud-sql-connections/)), the name places them.

```
SELECT pid,
       application_name,
       now() - query_start               AS running_for,
       wait_event_type,
       cardinality(pg_blocking_pids(pid)) AS blocked_by,
       left(query, 80)                    AS query
FROM pg_stat_activity
WHERE backend_type = 'client backend'
  AND state = 'active'
  AND now() - query_start > interval '300 seconds'
ORDER BY running_for DESC;
```

Use your timeout in place of 300 seconds. `query_start` is when the active query began. To see whether a long query blocks others, look for sessions whose `pg_blocking_pids` contains its `pid`; those sessions show `wait_event_type` `Lock`. [pg\_stat\_activity](https://www.postgresql.org/docs/current/monitoring-stats.html) · [`pg_blocking_pids`](https://www.postgresql.org/docs/current/functions-info.html)

| 504 at the timeout | Active query older than the timeout | Reading |
| --- | --- | --- |
| Yes | Yes, from the service | The query outlived its request. It holds a connection, and possibly locks, for nothing |
| Yes | No | The request spent its time elsewhere: waiting for a pool connection, or calling another dependency. Read the application's own timings |
| No, the 504s are faster | Not applicable | Not the request timeout |

## What to do

Stop the queries that have no request left. The following changes the database: `pg_cancel_backend(pid)` cancels the session's current query and leaves the connection open for the pool; a role may cancel sessions of a role it is a member of. [Server signaling functions](https://www.postgresql.org/docs/current/functions-admin.html)

Then make the database stop such queries on its own. `statement_timeout` aborts any statement that runs longer than its value, measured from the moment the command arrives at the server; 0, the default, disables it. PostgreSQL advises against setting it for all sessions in the server configuration, and Cloud SQL's flag list does not include it. Set it where it fits the workload instead:

-   for a role: `ALTER ROLE orders_app SET statement_timeout = '250s';` which applies to the role's new sessions;
-   for a connection: the libpq `options` parameter, such as `-c statement_timeout=250s`;
-   for one transaction or statement, from the application, where a single endpoint needs a different limit.

[`statement_timeout`](https://www.postgresql.org/docs/current/runtime-config-client.html) · [ALTER ROLE](https://www.postgresql.org/docs/current/sql-alterrole.html) · [libpq `options`](https://www.postgresql.org/docs/current/libpq-connect.html) · [Supported flags](https://cloud.google.com/sql/docs/postgres/flags)

Order the limits so each layer gives up before the one above it: the statement timeout below the application's own deadline for the request, that deadline below Cloud Run's request timeout, and Cloud Run's below the caller's. Work that legitimately needs longer than a request allows belongs somewhere that is not waiting on an HTTP connection.

## A worked fixture: two kinds of 504

The fixture is illustrative. `orders-api-00018` has `timeoutSeconds: 300`. Its export endpoint runs one large query against `orders-db`. Each instance's pool holds up to 10 connections, and the application names connections with `K_REVISION`.

Case A, 2026-11-23.

| Time (UTC) | Event |
| --- | --- |
| 11:00:00 | Request to `/reports/export` starts on instance `…c9e2` |
| 11:05:00 | Caller receives 504, latency 300.4 s |
| 11:05:02 | Caller retries; new request on `…c9e2` |
| 11:10:02 | Second 504 |
| 11:10:03 | Caller retries; third request on `…c9e2` |

At 11:12:00 the query in Check 2 returns two active sessions from `orders-api-00018`, both running the export query, for 720 and 418 seconds. Without the age filter, a third export from the 11:10:03 retry has run for 117 seconds. Three of the instance's ten connections are busy with work nobody is waiting for, and the other requests on `…c9e2` wait longer for a connection. None blocks another session. The team cancels the three queries with `pg_cancel_backend`, sets `statement_timeout = '250s'` on `orders_app`, and moves the export to a job that does not run inside a request.

**Case B, 2026-11-24.** Checkout requests return 504 at 300 seconds, with the same pattern of retries. Check 2 returns nothing: no session from the service has been active for more than 2 seconds. The application's timings show the checkout handler waiting on the payment provider's API, which accepts the connection and never answers, and the client has no timeout. The database is not involved. The fix is a client timeout on that call below the request timeout.

## Where the checks mislead

`pg_stat_activity` shows the present. A query that ran for twelve minutes and finished is gone from it; the evidence is then in the request log's 504s and in Cloud SQL's query insights, if enabled. [Query insights](https://cloud.google.com/sql/docs/postgres/using-query-insights)

`statement_timeout` limits each statement, not a transaction. A request that runs many short statements in one long transaction keeps its connection and locks without tripping it, and a transaction left open after the request ends shows as `idle in transaction`, which [sessions left after shutdown](/learn/cloud-run-shutdown-cloud-sql-connections/) covers.

A role-level timeout applies to every session of that role, including migrations or maintenance that run as it. Give those their own role or their own setting.

## Questions

### Does a Cloud Run request timeout cancel the database query?

No. Cloud Run closes the caller's connection and returns 504, but the container instance keeps running and may continue the request. The query runs until it finishes, unless a database timeout or a cancel stops it.

### What should statement\_timeout be on Cloud Run?

Below the request timeout, with room for the rest of the request's work. With Cloud Run's default of 300 seconds, a statement timeout a little under that, or much lower for interactive endpoints, stops a query before Cloud Run abandons the request.

### Can I set statement\_timeout as a Cloud SQL flag?

Cloud SQL's supported flag list does not include `statement_timeout`, and PostgreSQL advises against setting it for all sessions anyway. Set it per role with `ALTER ROLE ... SET`, per connection with the `options` parameter, or per transaction from the application.

## One month of free code review.

New organizations get one calendar month of hosted code review for private and public GitHub repositories. No card or cloud connection required. [Eligibility and fair-use terms](/free-code-review/).

[Start free with GitHub](https://proofline.sh/orgs/plan?offer=free_month)

## Related reading

-   ### [Sessions left in Cloud SQL after a Cloud Run rollout: shutdown or leak?](/learn/cloud-run-shutdown-cloud-sql-connections/)
    
    Broken dependencies The Proofline team November 23, 2026 6 min read
    
-   ### [Bad release or unhealthy dependency?](/learn/bad-release-or-unhealthy-dependency/)
    
    Deployment failures The Proofline team November 20, 2026 10 min read
