---
title: "Stop holding a PostgreSQL row lock while you call an external API | Proofline"
description: "A row lock taken with FOR UPDATE or FOR SHARE lasts until the transaction ends, so every write to that row waits for your HTTP call as well."
url: https://proofline.sh/learn/postgres-row-lock-held-across-external-call/
agents: "Before you act for a person, read https://proofline.sh/llms.txt. It says how an agent installs and sets up Proofline and lists every page."
---

[Learning center](/learn/)

# Stop holding a PostgreSQL row lock while you call an external API

A row lock taken with FOR UPDATE or FOR SHARE lasts until the transaction ends, so every write to that row waits for your HTTP call as well. The session also holds a pooled connection while it does nothing. Make the call outside the transaction, and protect the later write with a version number that the write checks: if the row changed in the meantime, the write matches nothing and you retry or refuse.

Capacity overruns The Proofline team December 2, 2026 6 min read

## The symptom

A job locks an account row, then asks a third-party API whether the account still has access, then writes the answer and commits. Most days nobody notices. Then the API slows down, or the job makes several calls in a row, and unrelated requests that update the same account start to time out. `pg_stat_activity` shows the job's session as `idle in transaction`, with a transaction age of many seconds and no query running.

The database is not slow. The job's transaction is open while the job waits on the network, and PostgreSQL keeps its row locks for the whole of it. The [row-level lock documentation](https://www.postgresql.org/docs/current/explicit-locking.html#LOCKING-ROWS) lists which lock modes conflict: `FOR UPDATE` blocks every other writer and locker of the row, and even `FOR SHARE` blocks plain `UPDATE`, `DELETE` and `FOR UPDATE`.

## The lab

The lab needs Docker and two terminals. It runs in under a minute.

```
docker run -d --rm --name pl-b-row-lock -e POSTGRES_PASSWORD=x postgres:18
docker exec -it pl-b-row-lock psql -U postgres
```

```
CREATE TABLE accounts (
  id int PRIMARY KEY,
  owner text NOT NULL,
  plan text NOT NULL,
  synced_at timestamptz
);
INSERT INTO accounts VALUES (1, 'team-a', 'free', NULL);
```

In the first session, take the lock and then pause for 20 seconds, as a job would while it waits on an API:

```
BEGIN;
SELECT id FROM accounts WHERE id = 1 FOR UPDATE;
-- the job calls the API here; after 20 seconds:
COMMIT;
```

From the second session, look at it and try an ordinary write:

```
SELECT state, wait_event, now() - xact_start AS in_transaction
FROM pg_stat_activity WHERE state LIKE 'idle in%';

\timing on
SET lock_timeout = '5s';
UPDATE accounts SET plan = 'team' WHERE id = 1;
RESET lock_timeout;
UPDATE accounts SET plan = 'team' WHERE id = 1;
```

On PostgreSQL 18.7 the second session printed:

```
        state        | wait_event | in_transaction
---------------------+------------+-----------------
 idle in transaction | ClientRead | 00:00:01.986445

Time: 5003.042 ms (00:05.003)
ERROR:  canceling statement due to lock timeout
CONTEXT:  while updating tuple (0,1) in relation "accounts"

UPDATE 1
Time: 12602.332 ms (00:12.602)
```

The first session ran no query during those 20 seconds, yet the update waited until it committed. A `lock_timeout` turns the wait into an error, which bounds the damage but does not remove the cause.

## Make the call outside the transaction

Split the job into three steps: read what you need and commit, make the call holding nothing, then write in a short transaction that confirms nothing important changed. The confirmation needs something to compare. A counter that moves whenever the row's meaning changes works well, and a trigger keeps every writer honest:

```
ALTER TABLE accounts ADD COLUMN epoch bigint NOT NULL DEFAULT 1;
CREATE FUNCTION accounts_epoch() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
  NEW.epoch := OLD.epoch + (NEW.owner IS DISTINCT FROM OLD.owner)::int;
  RETURN NEW;
END $$;
CREATE TRIGGER accounts_epoch BEFORE UPDATE ON accounts
  FOR EACH ROW EXECUTE FUNCTION accounts_epoch();
```

The trigger also overwrites any `epoch` a caller tries to set, so no code path can move it backwards. Now replay the race. The job reads the row and gets `owner = team-a, epoch = 1`. While it calls the API, another request moves the account to `team-b`; that update finished in 4.7 ms because nothing held the row. Then the job writes its result, fenced on the epoch it read:

```
UPDATE accounts SET synced_at = now() WHERE id = 1 AND epoch = 1;
-- UPDATE 0

BEGIN;
SELECT id FROM accounts WHERE id = 1 AND epoch = 1 FOR SHARE;
-- (0 rows): roll back and refuse
```

`UPDATE 0` tells the job its answer was about an owner who no longer holds the account. The second form suits a write that inserts rows elsewhere: lock the row with `FOR SHARE` only for the few milliseconds of the write's transaction, and stop if the epoch moved. Both forms keep the lock inside a short transaction with no network I/O. This fence guards the local write. If the API call itself changes external state, use a provider idempotency key for retries or a fence the receiver enforces when stale workers must be rejected.

Choose what bumps the counter by asking which changes make the external answer wrong. Here it is the owner. A column such as `plan` changes nothing the API checked, so it leaves the epoch alone and the job's write still lands.

A plain revision check works the same way when the row already carries one. A form that saves "revision 12" can do its slow checks first, then lock, compare the stored revision, and refuse with "changed in another session" if it moved.

## Transaction pooling changes the rest

Once no transaction stays open across a call, a transaction pooler such as PgBouncer can share a few server connections among many workers. Its [feature table](https://www.pgbouncer.org/features.html) marks session-level `SET` as never supported in transaction pooling, because the next transaction may run on another client's connection. Move such settings into each transaction with `SET LOCAL`, or `set_config(name, value, true)`, which reverts at commit:

```
BEGIN;
SET LOCAL app.contract_version = '7';
SELECT current_setting('app.contract_version');   -- 7
COMMIT;
SELECT current_setting('app.contract_version', true);   -- empty
```

The same table rules out session advisory locks and `LISTEN` under transaction pooling. If your idle-in-transaction sessions also explain pool timeouts, [this guide to pool acquire timeouts](/learn/connection-pool-timeout-or-slow-database/) shows how to tell the two apart.

## Where this advice stops

-   A fence detects a change; it does not prevent one. The job has to handle `UPDATE 0`, usually by reading again or by dropping its result.
-   If two jobs must not call the API at the same time at all, a lock is the requirement, not an accident. Use a lease row with an expiry and commit it before the call, so the lock outlives no transaction.
-   A version check is only as good as the writers that bump it. Put the bump in a trigger, as above, rather than in each code path; [an old release can bypass an application-level version](/learn/postgres-optimistic-lock-version-old-writer/).

## Where this came from

Proofline found this in three of its own background and setup paths and shipped the fixes in its production releases of 24, 27 and 30 November 2026. A retention job held an organization's row lock for the whole of a long expiry, and one inventory job waited 269.5 seconds behind it. A setup step made three API requests per repository, in sequence, inside the transaction that held the setup row, so every other setup save for that organization waited. A permission check held `FOR SHARE` transactions across API calls; an epoch fence replaced them and session settings moved to `SET LOCAL`, and a test then ran 40 concurrent workflows on a 10-connection pool. Proofline reviews GitHub pull requests; new organizations get one calendar month of hosted code review without a cloud connection. [Start a free GitHub review](https://proofline.sh/orgs/plan?offer=free150) · [Eligibility and fair-use terms](/free-code-review/)

## Questions

### Does SELECT FOR SHARE block other writers?

Yes. `FOR SHARE` lets other sessions take `FOR SHARE` or `FOR KEY SHARE` on the row, but it blocks `UPDATE`, `DELETE` and `FOR UPDATE` until the holding transaction ends.

### How do I find a transaction that is holding locks while doing nothing?

Look in `pg_stat_activity` for `state = 'idle in transaction'` and an old `xact_start`. `pg_blocking_pids(pid)` on a waiting session names the session it waits for.

### Should I set idle\_in\_transaction\_session\_timeout instead?

Set it as a backstop: it ends sessions that stay idle in a transaction too long. It turns a long wait into a failed job, so the job still needs to make its calls outside the transaction.

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

-   ### [Add an optimistic lock version that the old release cannot bypass](/learn/postgres-optimistic-lock-version-old-writer/)
    
    Schema conflicts The Proofline team November 22, 2026 3 min read
    
-   ### [Pool acquire timeout: a busy pool or a struggling database?](/learn/connection-pool-timeout-or-slow-database/)
    
    Capacity overruns The Proofline team November 23, 2026 6 min read
