Learning center

Sessions left in Cloud SQL after a Cloud Run rollout: shutdown or leak?

Compare each revision's sessions with its live instances. Sessions from a revision with no instances left, which fade without action, are shutdown residue: pools that were not closed in the 10 seconds Cloud Run allows after SIGTERM. Sessions that keep growing on live instances are a leak in the application.

How it shows up#

After a rollout, the session count on the database does not fall back to where it was, or keeps creeping up for hours. Someone asks whether the old revision left sessions behind or the new one leaks. The two need different fixes: a shutdown handler for the first, a code fix for the second. Both end at the admission stage of the four stages if they run long enough.

Cloud Run shuts instances down when they are no longer needed, including idle instances at any time. Before an instance stops, Cloud Run sends SIGTERM to all of its containers, then SIGKILL 10 seconds later; the instance has CPU during those 10 seconds. In the first generation execution environment, an instance that does not trap SIGTERM is shut down immediately. For the second generation, Cloud Run recommends installing a SIGTERM handler. Instance shutdown · Background work and SIGTERM

A pool closed in that window ends its sessions cleanly. A pool that is not closed leaves the database to notice the connections are gone. PostgreSQL notices a lost connection at its next interaction with the socket, or through TCP keepalives, which on Cloud SQL default to a first probe after 60 seconds of silence (tcp_keepalives_idle). On Cloud Run's built-in connection, the session's network peer is the Cloud SQL Auth Proxy, and Cloud SQL does not document how quickly that side closes after an instance stops. Treat the delay on your path as something to measure. client_connection_check_interval · Cloud SQL tcp_keepalives_idle · Connect from Cloud Run

Check 1: do the sessions belong to instances that still exist?#

Group sessions by revision. This needs connections named after the revision; which revision holds the connections shows how to set application_name from K_REVISION.

SELECT application_name,
       state,
       count(*)          AS sessions,
       min(state_change) AS oldest_state_change
FROM pg_stat_activity
WHERE backend_type = 'client backend'
GROUP BY application_name, state
ORDER BY application_name, state;

state_change is when the session's state last changed, so an idle session whose state_change is older than its revision's last instance has not been used since that instance existed. pg_stat_activity

Beside it, chart Cloud Run's container/instance_count for each revision. The metric keeps the history, so it shows when a revision's last instance went away. Cloud Run metrics

Check 2: watch the groups for half an hour#

Run the query again every five to ten minutes. The direction decides more than any single count:

Revision's instancesIts sessions over the next 30 minutesReading
ZeroFall to zero without actionShutdown residue. Pools were not closed at SIGTERM, and the path took this long to notice
ZeroStaySessions the server does not see as dead. Read the keepalive settings, then end them by hand
RunningSteady, at or below instances × pool limitNormal. Nothing lingers
RunningAbove instances × pool limit, or growing with uptimeA leak: connections opened outside the pool, or borrowed and never returned

A leak often shows in the state column as well. Sessions in idle in transaction whose state_change is hours old are connections that began a transaction and were never given back. They hold locks and stop vacuum from removing dead rows while they stay open. idle_in_transaction_session_timeout

Check 3: does the application close its pool on SIGTERM?#

Read the container's logs at the end of an instance's life. A handler that closes the pool can log that it did; its absence on every stopped instance answers the question. With PostgreSQL's log_disconnections on, each session's end is logged with its duration, so a clean shutdown shows a burst of disconnections within 10 seconds of the instance stopping. On Cloud SQL the flag is off by default and changes without a restart; setting it replaces the instance's flag list, so include the existing flags. log_disconnections · Supported flags

What to do with each reading#

For residue, add a SIGTERM handler that closes the pool, which ends the sessions at once instead of when the path notices. It matters most when rollouts happen near the connection budget, since residue counts against it until it clears.

For sessions that stay after their instances are gone, end them. The following changes the database: pg_terminate_backend(pid) terminates one session, and a role may call it for sessions of a role it is a member of. Server signaling functions

SELECT pid, pg_terminate_backend(pid)
FROM pg_stat_activity
WHERE application_name = 'OLD_REVISION'
  AND backend_type = 'client backend';

For a leak, fix the code that borrows without returning or creates connections outside the pool. Until then, idle_in_transaction_session_timeout, which Cloud SQL supports as a flag without a restart, ends sessions left idle inside a transaction after the time you set. Choose a value longer than any legitimate pause inside your transactions.

A worked fixture: one rollout, two problems#

The fixture is illustrative. orders-api-00020 ran 20 instances with a pool of 10 each. At 09:12:30 UTC on 2026-11-26, orders-api-00021 takes all traffic. Neither revision has a SIGTERM handler.

The old revision.

Time (UTC)orders-api-00020 instancesorders-api-00020 sessions
09:1220200
09:209112
09:28064
09:3100

At 09:28 the revision has no instances and still holds 64 idle sessions, all with state_change before 09:14. Three minutes later they are gone with no action. That is residue, cleared by the path within minutes. It held 64 slots during the rollout's busiest quarter-hour. The team adds a SIGTERM handler that disposes of the engine; on the next rollout, the old revision's sessions fall with its instance count, and the postgres log shows each instance's disconnections inside its 10-second window.

The new revision. orders-api-00021 settles at 16 instances, and its group keeps growing:

Time (UTC)InstancesSessionsOf which idle in transaction
09:30161600
12:301621448
15:301626896

With a pool limit of 10, 16 instances should hold at most 160. The group adds 54 sessions every three hours on a steady instance count. A new export handler in this release creates its own engine per call, opens a transaction and never disposes of the engine. The fix goes in the code; meanwhile the team sets idle_in_transaction_session_timeout to 10 minutes on orders-db, longer than any transaction the service runs.

Where the checks mislead#

Unnamed sessions fall outside every revision's group. If the application sets no application_name, the trend still works on totals, but you cannot tell residue from a leak until the naming change ships.

The clearing time in the fixture belongs to that path. A different connection method, an egress setting or a network fault between Cloud Run and the database can make sessions stay longer. Measure your own after one rollout instead of assuming the fixture's minutes.

A leak can hide under an instance count that changes. When instances come and go, divide sessions by instances at each reading; growth per instance over hours is the signal, not the total.

Questions#

Why do database connections stay open after Cloud Run shuts down an instance?

Cloud Run sends SIGTERM and waits 10 seconds before SIGKILL. If the application does not close its pool in that window, the sessions end only when the database or the path between them notices that the client is gone, which can take minutes.

Do I need a SIGTERM handler on Cloud Run to close database connections?

Cloud Run recommends one in the second generation execution environment. Closing the pool in it ends the sessions at shutdown instead of later, which keeps slots free during rollouts and scale-in.

How do I tell a connection leak from connections left by old instances?

Compare each revision's sessions with its instance count. Sessions from a revision with no instances that fade on their own are shutdown residue. Sessions on live instances that exceed instances times the pool limit, or grow with uptime, are a leak.

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.

Start free with GitHub

Related reading