---
title: "A Cloud Run migration job blocks the service's queries on Cloud SQL | Proofline"
description: "A Cloud Run job's migration that waits for a lock makes every later query on that table wait behind it, so the service stalls while the job looks idle."
url: https://proofline.sh/learn/cloud-run-job-migration-locks-cloud-sql/
---

[Learning center](/learn/)

# A Cloud Run migration job blocks the service's queries on Cloud SQL

A Cloud Run job's migration that waits for a lock makes every later query on that table wait behind it, so the service stalls while the job looks idle. The function pg\_blocking\_pids names the waiting migration and the session it waits for. Cancel the migration's statement to release the queue, then run it again with a lock\_timeout shorter than the wait the service tolerates.

Breaking migrations The Proofline team November 23, 2026 7 min read

## How it shows up

The service's latency rises on every endpoint that touches one table, its connection pool runs out, and requests that never touch that table start waiting for a connection. Nothing in the service changed: the deploy pipeline started a Cloud Run job a minute earlier, and the job's log ends at the migration statement with no error.

The mechanism is PostgreSQL's lock queue. Most forms of `ALTER TABLE` take an `ACCESS EXCLUSIVE` lock, which conflicts with every other mode, including the `ACCESS SHARE` lock a plain `SELECT` takes. While one long transaction holds `ACCESS SHARE`, the migration waits; the service's next `SELECT` conflicts with the waiting migration, which is ahead of it in the queue, so it waits too. `pg_blocking_pids` calls this a soft block. [Table-level lock modes](https://www.postgresql.org/docs/current/explicit-locking.html) · [`pg_blocking_pids`](https://www.postgresql.org/docs/current/functions-info.html) · [Why a fast migration blocked every query](/learn/postgres-migration-lock-queue/)

None of the [four connection stages](/learn/cloud-run-cloud-sql-connection-errors/#stage) fails. Connections succeed and then wait, which looks like stage 4 from the application until the database's own view shows the lock.

## Check 1: find the waiting migration and what it waits for

Start from the sessions that are blocked, and ask PostgreSQL who blocks each:

```
SELECT pid, application_name, wait_event_type,
       now() - query_start AS waiting,
       pg_blocking_pids(pid) AS blocked_by,
       left(query, 60) AS query
FROM pg_stat_activity
WHERE cardinality(pg_blocking_pids(pid)) > 0
ORDER BY query_start;
```

Then read the locks on the table from the migration's point of view. `pg_locks` has one row per lock held or awaited, with `mode`, `granted` (false while the session waits) and `waitstart`, the time the wait began. [`pg_locks`](https://www.postgresql.org/docs/current/view-pg-locks.html)

```
SELECT l.pid, a.application_name, l.mode, l.granted, l.waitstart, a.xact_start
FROM pg_locks l JOIN pg_stat_activity a USING (pid)
WHERE l.relation = 'orders'::regclass
ORDER BY l.granted DESC, l.waitstart;
```

| What the rows show | Reading |
| --- | --- |
| One session waits for `AccessExclusiveLock`; many sessions wait behind it; one older session holds a lock and is blocked by nobody | The lock queue. The holder is the root; the migration is what turns one slow reader into an outage |
| The migration holds `AccessExclusiveLock` (`granted` true) and others wait | The migration has its lock and is working, for example rewriting the table. A `lock_timeout` will not shorten this; the statement itself is slow |
| No session waits on a lock | The latency comes from elsewhere: connection count, CPU or I/O |

## Check 2: tie the pid to a job execution

Cloud Run sets `CLOUD_RUN_JOB` and `CLOUD_RUN_EXECUTION` in a job's container. If the migration tool passes the execution name as `application_name`, the first query names the execution directly. If it does not, match times: list the job's executions and read the log of the one that started just before `waitstart`. [Container runtime contract](https://cloud.google.com/run/docs/container-contract)

```
gcloud run jobs executions list --job orders-migrate \
  --project shop-prod --region europe-west1

gcloud logging read \
  'resource.type="cloud_run_job"
   AND resource.labels.job_name="orders-migrate"
   AND timestamp>="START_TIME"' \
  --project shop-prod --order=asc --limit=200 \
  --format='value(timestamp, labels, textPayload)'
```

Job log entries carry the execution name, the task index and the task attempt in their labels, so a retried task shows up as a second attempt in the same execution. [Cloud Run job log fields](https://cloud.google.com/run/docs/logging) · [`gcloud run jobs executions list`](https://cloud.google.com/sdk/gcloud/reference/run/jobs/executions/list)

Two job settings decide how long the problem can last. A task runs for up to 10 minutes by default before Cloud Run stops it, and a failed task is retried 3 times by default. Without a `lock_timeout`, the migration can wait the whole task timeout, then retry and queue again. [Job task timeout and retries](https://cloud.google.com/run/docs/create-jobs)

## Decide: release the queue, then choose the timeout and the time

Cancelling the migration's statement releases every session queued behind it, because they were waiting on its request, not on the long transaction's lock. This step changes the database: it ends the migration's current statement, and with a transactional migration tool, rolls back its transaction. `pg_cancel_backend` needs membership in the session's role or the privileges of `pg_signal_backend`. [Server signaling functions](https://www.postgresql.org/docs/current/functions-admin.html)

```
SELECT pg_cancel_backend(MIGRATION_PID);
```

Do not cancel the long transaction that holds the lock unless you know what it is. It might be a report, or it might be a write the business needs.

Then set the migration's `lock_timeout`. The setting aborts any statement that waits longer than its value to acquire a lock; in the lock-queue lab the error carried SQLSTATE `55P03` (`lock_not_available`). It applies to each lock acquisition separately and never limits a statement that already holds its lock. Set it inside the migration's transaction, for example `SET LOCAL lock_timeout = '2s'` as its first statement. [`lock_timeout`](https://www.postgresql.org/docs/current/runtime-config-client.html) · [PostgreSQL error codes](https://www.postgresql.org/docs/current/errcodes-appendix.html)

| The service tolerates | Choose |
| --- | --- |
| A wait shorter than its request timeout and its pool's wait for a connection | A `lock_timeout` well below both, so a failed attempt costs one short stall |
| No stall at all on this table | Run the migration when no long transaction is open on it, checked by the job itself before it starts |

The job's retries then serve the migration: each attempt waits at most the timeout, and a failed attempt is retried. Bound them with `--max-retries`, so that a transaction that stays open ends the execution after a few short attempts. [`gcloud run jobs update`](https://cloud.google.com/sdk/gcloud/reference/run/jobs/update)

Before starting the job, check for transactions that would block it:

```
SELECT pid, application_name, xact_start, state, left(query, 60)
FROM pg_stat_activity
WHERE xact_start < now() - interval '1 minute'
ORDER BY xact_start;
```

## A worked fixture: one migration, two runs

The fixture is illustrative. `orders-api` serves from `orders-api-00018` against `orders-db`. The deploy pipeline starts the job `orders-migrate`, which runs `ALTER TABLE orders ADD COLUMN note text`. Each tool sets `application_name`: the job to its execution name, the service to its revision, and a reporting service to `orders-report`.

**Run A, no timeout.** Execution `orders-migrate-x7k2p` starts at 13:20:04 UTC. At 13:24 the service's latency is high on every endpoint. The `pg_locks` query on `orders`:

| pid | application\_name | mode | granted | waitstart | xact\_start |
| --- | --- | --- | --- | --- | --- |
| 4102 | `orders-report` | `AccessShareLock` | t |  | 13:05:12 |
| 4377 | `orders-migrate-x7k2p` | `AccessExclusiveLock` | f | 13:20:09 | 13:20:09 |
| 4380 | `orders-api-00018` | `AccessShareLock` | f | 13:20:11 | 13:20:11 |
| 4381 | `orders-api-00018` | `AccessShareLock` | f | 13:20:11 | 13:20:11 |

The first query shows `blocked_by` `{4102}` for pid 4377 and `{4377}` for the service's sessions. The report had held its transaction for 15 minutes when the migration queued at 13:20; on its own it blocked nobody. The team cancels pid 4377 at 13:24:30, and the service's waits end. The task fails, and Cloud Run starts a second attempt, which queues again at 13:24:41. The team cancels it too, and adds a `lock_timeout` to the migration before the next execution.

**Run B, with `SET LOCAL lock_timeout = '2s'` and `--max-retries=3`.** Execution `orders-migrate-q91fm` starts at 13:30:02. The report's transaction is still open. The job's log shows four attempts, each ending in SQLSTATE `55P03` about two seconds after it starts, and the execution fails at 13:30:40. During that time, requests to `orders-api` that touched `orders` were delayed by at most two seconds per attempt. The report commits at 13:41. At 13:45 the check for long transactions returns no rows, the team runs a new execution, and the column is added in 41 ms.

## Where the checks mislead

`pg_blocking_pids` reads the lock state at one moment. A queue that has already drained shows nothing; for an incident that ended, the database logs and the job's log timing are what remain. With `log_lock_waits` on, PostgreSQL logs each session that waits longer than `deadlock_timeout` for a lock; Cloud SQL lists it among its configurable flags. [`log_lock_waits`](https://www.postgresql.org/docs/current/runtime-config-logging.html) · [Cloud SQL flags](https://cloud.google.com/sql/docs/postgres/flags)

A migration tool that runs each statement in its own transaction and does not retry a whole file can leave half a migration applied after a `lock_timeout`. Rehearse the failure once before relying on retries.

A migration that the service runs at startup, instead of a job, takes the same lock with the same effect, but from many instances at once. The sibling guide on [traffic splits during a schema change](/learn/cloud-run-traffic-split-schema-change/) covers which revision then meets which schema.

## Questions

### Why does a Cloud Run job's migration make unrelated requests slow?

Each query waiting behind the migration's lock request holds a connection from the service's pool. When the pool runs out, requests that use other tables wait for a connection too.

### What lock\_timeout should a migration job use?

Shorter than the service's request timeout and its pool's connection wait, so an attempt that cannot get its lock fails before the service's requests do. The job's retries then repeat the attempt.

### Should I cancel the migration or the long transaction?

Cancel the migration's statement first. It releases the queued sessions at once, and it is the change you control. The long transaction may be work someone needs.

## 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

-   ### [Why a fast PostgreSQL migration blocked every query](/learn/postgres-migration-lock-queue/)
    
    Breaking migrations The Proofline team November 20, 2026 3 min read
    
-   ### [A schema change during a Cloud Run traffic split: which revision must accept it?](/learn/cloud-run-traffic-split-schema-change/)
    
    Schema conflicts The Proofline team November 23, 2026 6 min read
