Learning center

The first request after idle gets a dead Cloud SQL connection

With request-based billing, Cloud Run throttles an idle instance's CPU, so the connection pool's background maintenance stops. When the server closes an idle session meanwhile, the next request borrows a dead connection. Fix it with a check at borrow time, a lifetime shorter than whatever closes the sessions, or instance-based billing.

How it shows up#

The pattern is narrow and repeatable: after a quiet period, the first request or two on an instance fail with a driver error saying the server closed the connection, or the connection is reset, and the next request on the same instance works. Busy hours show nothing. Services with minimum instances see it most, because their instances survive long quiet periods instead of being replaced.

Cloud SQL's Cloud Run page describes the mechanism. By default Cloud Run uses request-based billing, which allocates CPU only while an instance processes requests; when the instance is idle, Cloud Run throttles its CPU. That pauses the background threads client-side pools use for maintenance: connection validation, closing expired idle connections and periodic health checks. When a request wakes the instance, the pool may hand out connections the database server terminated during the idle period, and the request fails with a connection error or a timeout. The same page warns that the database server or the platform's infrastructure can drop connections, and recommends pools that reconnect broken connections. Connect from Cloud Run: connection pools · Billing settings

The failure sits at the admission-and-use stage of the four stages: the session existed and worked, then ended while nobody was looking.

Check 1: is the revision's CPU throttled between requests?#

gcloud run revisions describe REVISION \
  --project PROJECT --region REGION \
  --format='yaml(metadata.annotations)'

The revision annotation run.googleapis.com/cpu-throttling records the setting: false means CPU stays allocated for the instance's whole life, which is instance-based billing. With request-based billing, the default, the pool's background work runs only while a request is in progress. Revision annotations · CPU allocation

The Cloud SQL language connectors have the same exposure for their certificate refresh. Google's samples set a lazy refresh strategy (refresh_strategy="LAZY" in Python, WithLazyRefresh() in Go, cloudSqlRefreshStrategy=lazy in Java) and recommend it for serverless environments so that refreshes happen when needed instead of on a background schedule that throttled CPU stalls. Cloud SQL connectors

Check 2: do failures follow idle gaps on the same instance?#

Read the request log for the window, with the instance each request ran on:

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

labels.instanceId identifies the instance, and httpRequest.status and httpRequest.latency are the standard request fields. For each failed request, find the previous request on the same instance and note the gap. Cloud Run log fields · LogEntry HttpRequest

Failed requestsSame instance afterwardsReading
First on an instance after a long gap, on several instances at different timesThe next request succeedsStale connections after idle, as described above
Many instances in the same minute, during steady trafficErrors stop togetherSomething ended every session at once: a restart, failover or maintenance. Not idle CPU
Spread through busy periods, no relation to gapsErrors continueNot this. Read the full error and the four stages

Check 3: what closed the sessions?#

The stale connection only shows that something ended the session before the pool reused it. Two sources answer what. Cloud SQL's operations list records restarts, failovers, maintenance and updates with their times: gcloud sql operations list --instance INSTANCE --project PROJECT. And PostgreSQL's log_disconnections flag, off by default and settable on Cloud SQL without a restart, logs each session's end with its duration; Cloud SQL writes these to cloudsql.googleapis.com/postgres.log on the cloudsql_database resource. Setting the flag changes the instance's flag list, so include the flags it already has. Cloud SQL operations · log_disconnections · Supported flags · Cloud SQL logs

Also look for a server-side idle limit. idle_session_timeout ends sessions that have been idle outside a transaction for longer than its value, and PostgreSQL itself warns against applying it to connections made through pooling software. It is not in Cloud SQL's flag list, but a role or database can carry it: SELECT rolname, rolconfig FROM pg_roles WHERE rolconfig IS NOT NULL; shows per-role settings. idle_session_timeout · ALTER ROLE · pg_roles

Choose the fix#

Checks that run when the application borrows a connection run during a request, when the instance has CPU, so they work under request-based billing. Background maintenance does not.

FixWhat it doesCost
Validate on borrowThe pool tests each connection at checkout and replaces a dead one. In SQLAlchemy, pool_pre_ping=TrueA round trip per checkout
Limit connection lifetimeThe pool discards connections older than a set age. In SQLAlchemy, pool_recycle, applied at checkout; set it below the shortest idle limit that closes sessionsReconnects at that interval; does not catch sessions closed early by a restart or failover
Instance-based billingCPU stays allocated, so the pool's own validation and eviction keep runningYou pay for each instance's whole lifecycle, idle time included

SQLAlchemy disconnect handling · Connection duration · Billing settings

Switching billing changes the service: gcloud run services update SERVICE --no-cpu-throttling deploys a new revision with CPU allocated outside requests. Validation on borrow also covers the restart and failover cases, which the billing change does not. --cpu-throttling

A worked fixture: two mornings, two causes#

The fixture is illustrative. orders-api-00018 runs with a service-level minimum of 2 instances and request-based billing; its revision has no run.googleapis.com/cpu-throttling annotation. Each instance's SQLAlchemy pool keeps up to 10 connections to orders-db, with neither pool_pre_ping nor pool_recycle set.

Morning A, 2026-11-19. Traffic stops at 01:40 UTC and resumes at 03:12.

Time (UTC)InstanceStatusNote
01:39:55…c9e2200Last request before the gap
03:12:07…c9e2500Driver reports the server closed the connection
03:12:09…c9e2200
03:12:15…41af500Same error, other minimum instance
03:12:16…41af200

Each instance fails once, on its first request after a 92-minute gap, then recovers. The operations list shows nothing that night. pg_roles shows idle_session_timeout=1h on orders_app, set a week earlier to stop an analyst tool from leaving sessions open. With log_disconnections turned on, the next quiet night's postgres log shows the orders_app sessions ending an hour after their last use. The server closed them while the pools' CPU was throttled. The team removes the setting from orders_app with ALTER ROLE orders_app RESET idle_session_timeout, which changes the role for new sessions, sets it on the analysts' role instead, and turns on pool_pre_ping for the restarts it cannot predict.

Morning B, 2026-11-16. At 14:02:11 UTC, during steady traffic, 31 requests fail across all 11 instances within 40 seconds, each with the same driver error, and the failures stop together. No instance had been idle. The operations list shows a FAILOVER from 14:01:20 to 14:02:05. Instance-based billing would not have prevented this; pool_pre_ping, now on, replaces such connections at checkout.

Where the checks mislead#

A gap in requests is not the same as a throttled instance. With instance-based billing the pool keeps working through the gap, so a failure after idle there points to something that closed the session faster than the pool's maintenance interval.

Pool settings differ by library. The SQLAlchemy names above have equivalents in most pools, such as a validation query or test on borrow and a maximum lifetime, but read your library's documentation for when each check runs; one that runs on a background timer has the same exposure as eviction.

log_disconnections adds a log line per session. Turn it on for the investigation window and size the log volume first on a busy instance.

Questions#

Why does my Cloud Run service fail on the first database request after being idle?

With request-based billing, Cloud Run throttles CPU when the instance is idle, so the connection pool cannot validate or close its connections. If the database server ended a session during that time, the first request after idle receives the dead connection.

Does instance-based billing fix stale Cloud SQL connections on Cloud Run?

It keeps CPU allocated so the pool's own maintenance runs between requests, which Cloud SQL's documentation recommends for this case. It costs CPU for the whole instance lifecycle and does not cover sessions ended by a restart or failover; validation on borrow covers both.

What does the Cloud SQL connector's lazy refresh do?

It makes the connector refresh its connection information and certificate when needed instead of on a schedule. Google's samples recommend it for serverless environments, to avoid background refreshes while CPU is throttled.

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