Learning center

Stop a shared counter row from serializing your PostgreSQL writes

A trigger that bumps a daily counter row locks that row from the first counted write until commit, so every other counted write waits behind it. Make the counter a DEFERRABLE INITIALLY DEFERRED constraint trigger instead. When both writers take the same counter row last, the trigger moves their wait to commit and breaks the illustrated cycle.

Why one row becomes a queue#

Product metrics are often kept by triggers: each insert into validations or replies adds one to a row in daily_counts keyed by the date. The trigger is an ordinary AFTER INSERT ... FOR EACH ROW, so it runs as soon as the insert does, and its UPDATE of the day row takes a row lock that lasts until the transaction ends.

That is harmless while transactions are short. It stops being harmless when a counted insert sits early in a transaction that then does more work. Every other transaction in the database that counts something on the same day now waits for that work to finish, whatever tenant or table it belongs to. Worse, the counter lock is now held while the transaction asks for other locks, so it can join a deadlock cycle with code that never meant to touch it.

The lab#

The lab needs Docker and two psql sessions, and runs in a minute.

docker run -d --rm --name pl-b-counter -e POSTGRES_PASSWORD=x postgres:18
docker exec -it pl-b-counter psql -U postgres
CREATE TABLE daily_counts (
  day date PRIMARY KEY,
  validations int NOT NULL DEFAULT 0,
  replies int NOT NULL DEFAULT 0
);
CREATE TABLE validations (id serial PRIMARY KEY, pr_id int NOT NULL);
CREATE TABLE replies (id serial PRIMARY KEY, pr_id int NOT NULL);
CREATE TABLE pr_cursor (pr_id int PRIMARY KEY, dirty boolean NOT NULL DEFAULT false);
INSERT INTO pr_cursor VALUES (7);
INSERT INTO daily_counts (day) VALUES (current_date);

CREATE FUNCTION count_validation() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
  INSERT INTO daily_counts (day, validations) VALUES (current_date, 1)
  ON CONFLICT (day) DO UPDATE SET validations = daily_counts.validations + 1;
  RETURN NULL;
END $$;
CREATE TRIGGER count_validation AFTER INSERT ON validations
  FOR EACH ROW EXECUTE FUNCTION count_validation();

Create count_reply() and its trigger on replies the same way, with replies in place of validations.

The wait. In session A, run BEGIN; INSERT INTO validations (pr_id) VALUES (1); and leave the transaction open for five seconds. One second in, session B runs a single INSERT INTO validations (pr_id) VALUES (2);. On PostgreSQL 18.7 that one-row insert took 3,862 ms: it waited for A to commit.

The cycle. Now run two transactions that each touch the counter and a per-pull-request cursor row, in opposite orders:

-- Session A: count a validation, then mark the cursor.
BEGIN;
INSERT INTO validations (pr_id) VALUES (7);
                                                  -- Session B
                                                  BEGIN;
                                                  UPDATE pr_cursor SET dirty = false WHERE pr_id = 7;
UPDATE pr_cursor SET dirty = true WHERE pr_id = 7;   -- waits for B
                                                  INSERT INTO replies (pr_id) VALUES (7);  -- waits for A

About a second later session B failed:

ERROR:  deadlock detected
DETAIL:  Process 110 waits for ShareLock on transaction 765; blocked by process 103.
Process 103 waits for ShareLock on transaction 766; blocked by process 110.
CONTEXT:  while inserting index tuple (0,3) in relation "daily_counts"
SQL statement "INSERT INTO daily_counts (day, replies) VALUES (current_date, 1)
  ON CONFLICT (day) DO UPDATE SET replies = daily_counts.replies + 1"

Neither code path mentions daily_counts. The cycle runs through a trigger, which is why it is hard to find from the application side; reading a deadlock log covers that step.

Move the counter to commit#

A constraint trigger is an AFTER ... FOR EACH ROW trigger whose firing time can be deferred to the end of the transaction. The CREATE TRIGGER reference describes it: with DEFERRABLE INITIALLY DEFERRED, the trigger runs at commit rather than at the end of the statement. The function stays the same:

DROP TRIGGER count_validation ON validations;
DROP TRIGGER count_reply ON replies;
CREATE CONSTRAINT TRIGGER count_validation AFTER INSERT ON validations
  DEFERRABLE INITIALLY DEFERRED
  FOR EACH ROW EXECUTE FUNCTION count_validation();
CREATE CONSTRAINT TRIGGER count_reply AFTER INSERT ON replies
  DEFERRABLE INITIALLY DEFERRED
  FOR EACH ROW EXECUTE FUNCTION count_reply();

With the same timing, session B's single insert took 5.5 ms instead of 3,862 ms. The cycle replayed with both transactions committing and no error, and daily_counts held one more validation and one more reply than before.

Both paths in the replay now take the same day row after the other locks in that cycle. The transaction that gets the counter row first can finish without waiting for the other path. Keep that ordering across every writer. A direct update, an early SET CONSTRAINTS, or a transaction that acquires several counters in a different order can reintroduce a cycle.

What deferral changes#

Deferral moves when the function runs, so check what the function reads:

  • Order-sensitive counters. A trigger that records which event happened first for an organization would record which one committed first instead. Keep those immediate.
  • "Count if no other" checks. A counter that counts a row only when no other qualifying row is visible behaves differently: two qualifying rows inserted in one transaction each see the other at commit, and neither counts. Keep it immediate or rewrite the check.
  • Timestamps. now() and current_date still use the transaction's start time. With a deferred trigger that fires during an explicit COMMIT, statement_timestamp() reads the start of that command and clock_timestamp() reads the wall clock, which falls on a different day only for a commit that crosses midnight.
  • Escape hatch. A transaction that needs the counter updated before it continues can run SET CONSTRAINTS count_validation IMMEDIATE, as the SET CONSTRAINTS reference describes.

Commits still serialize on the row for the duration of the commit. If even that is too much, write one row per event to an insert-only table and sum it later; moving a counter with deltas shows what goes wrong when the summing is done carelessly.

Changing a trigger is a migration. DROP TRIGGER and CREATE TRIGGER lock the table briefly, so on a busy table take those locks with a short lock_timeout and retry, and swap both triggers in one transaction so no insert goes uncounted.

Where this came from#

Proofline found this in its own product metrics, where five counters shared one row per day across every tenant, and shipped deferred counters in its production release of 27 November 2026. A pull request command step counted its write, which locked the day row, and then waited for the pull request's cursor; another step held that cursor and was waiting for the same day row. The command failed twice with deadlock detected on one day and retried. A regression test that replays both orders failed with 40P01 before the change and passed after it. Proofline reviews GitHub pull requests; new organizations get one calendar month of hosted code review without a cloud connection. Start a free GitHub review ยท Eligibility and fair-use terms

Questions#

Can a normal trigger be deferred?

No. Only a constraint trigger, created with CREATE CONSTRAINT TRIGGER, can be DEFERRABLE, and it must be an AFTER ... FOR EACH ROW trigger.

Does a deferred trigger still run if the transaction rolls back?

No. Deferred triggers fire during commit, so a rolled-back transaction never runs them and the counter stays unchanged, as it should.

Does a deferred counter still count every row?

Yes. Each inserted row queues one trigger event, and all of them run at commit. A transaction that inserts 1,000 rows runs the function 1,000 times at commit, all of them on the same row.

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