Scrivio Interview library
DebuggingIntermediate7 min read · updated 12 November 2026

Bulk loading 10 million rows into a table became 20 times slower after someone added an AFTER INSERT row trigger that writes an audit row and updates a counter in a stats table. Explain the costs and how you would redesign it.

The row trigger runs once for each of the 10 million rows, adding a function call and an extra audit insert per row, and every one of those calls also updates the same counter row in the stats table. That single hot row is locked by each loading transaction until it commits, so parallel loads serialise, and each update leaves a dead row version behind. The redesign writes audit rows in bulk from a statement-level trigger with transition tables or moves auditing to CDC outside the transaction, replaces the counter with aggregation on read, a periodic job or sharded counters, and for planned bulk loads may disable the trigger deliberately and do the audit work separately.

Why this question is asked

A 20 times slowdown from one small trigger surprises people, because the trigger's code is three lines. Interviewers ask this to see whether we can reason about cost per row and about contention, the two things that turn harmless-looking database code into a bottleneck at scale. In this answer, we will look at the trigger, measure where the time goes, explain the hot row, and then redesign the audit and the counter, finishing with how to handle planned bulk loads.

1The Trigger and What It Does per Row

Here is the kind of trigger that causes this. After each inserted row, it writes an audit row and increments a counter.

SQL
CREATE FUNCTION payment_after_insert() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
INSERT INTO payment_audit (payment_id, amount, loaded_at) VALUES (NEW.id, NEW.amount, now());
UPDATE table_stats SET row_count = row_count + 1 WHERE table_name = 'payment';
RETURN NULL;
END $$;
CREATE TRIGGER payment_ai AFTER INSERT ON payment
FOR EACH ROW EXECUTE FUNCTION payment_after_insert();
COPY payment FROM '/data/payments.csv' WITH (FORMAT csv);
-- before the trigger: 10000000 rows in about 1.5 minutes
-- with the trigger: 10000000 rows in about 30 minutes

Notice what one row of COPY now costs. Without the trigger, COPY writes rows into the table in a tight loop, one of the fastest paths PostgreSQL has. With the trigger, every row also queues an AFTER trigger event, calls a PL/pgSQL function, runs an INSERT into another table with its own index updates, and runs an UPDATE on table_stats. That is three statements' worth of work for every row, 30 million extra operations for the load.

2Why the Counter Row Is the Worst Part

The audit insert is costly but scales; the counter update does not. Every inserted payment updates the same single row of table_stats. An UPDATE in PostgreSQL never changes a row in place: it writes a new version of the row and marks the old one dead. Within one load of 10 million rows, the counter row gets 10 million new versions. Vacuum cannot remove the dead ones while the loading transaction is still running, so each update has to work past a growing chain of versions, and the stats table and its index bloat.

With parallel loads it gets worse. An UPDATE takes a row lock that is held until the transaction commits. The first loader to touch the counter holds that lock for its whole load, so a second loader's first counter update waits, and the two loads, which were supposed to run in parallel, run one after the other. This is a hot row: a single row that every transaction must lock and change, which turns concurrent work into a queue.

Step throughTwo parallel loads and one counter row
Loader Atable_stats rowLoader B
UPDATE row_count + 1 (lock held until commit)
inserts millions more rows, updating the counter each time
UPDATE row_count + 1: waits for A's lock
COMMIT after 30 minutes, lock released
lock granted, B finally starts

5 messages in order. Play them, or step through them one at a time.

The parallel loads become serial because both must change the same row.

3Redesigning the Audit: Statement-Level With Transition Tables

If the audit must stay in the database and in the same transaction, we change the trigger to fire once per statement instead of once per row. Since PostgreSQL 10, an AFTER statement trigger can use transition tables: it sees every inserted row as a table, here new_rows, and inserts all audit rows with one set-based statement.

SQL
DROP TRIGGER payment_ai ON payment;
CREATE FUNCTION payment_audit_bulk() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
INSERT INTO payment_audit (payment_id, amount, loaded_at)
SELECT id, amount, now() FROM new_rows;
RETURN NULL;
END $$;
CREATE TRIGGER payment_ai_stmt AFTER INSERT ON payment
REFERENCING NEW TABLE AS new_rows
FOR EACH STATEMENT EXECUTE FUNCTION payment_audit_bulk();
COPY payment FROM '/data/payments.csv' WITH (FORMAT csv); -- about 3 minutes: one bulk audit insert

The audit rows are still written in the same transaction, so the guarantee is unchanged, but there is one function call and one efficient insert instead of 10 million. The alternative is to move auditing out of the transaction entirely: logical decoding, the PostgreSQL feature that change data capture tools such as Debezium use, reads committed changes from the write-ahead log and can write them to an audit store, with no extra work in the writing transaction at all.

4Replacing the Counter

The counter should not be a single row updated by every insert. The options depend on how exact and how fresh the count must be. Often nobody needs a stored count: SELECT count(*) on demand, or pg_class.reltuples for an estimate, answers the question. If a stored count is needed, a periodic job can recompute it every few minutes. If it must be exact and current, sharded counters spread the updates over many rows so concurrent writers rarely collide, and readers sum the shards.

SQL
-- Sharded counter: 16 rows instead of one
CREATE TABLE table_stats_shard (table_name text, shard int, row_count bigint,
PRIMARY KEY (table_name, shard));
-- In a statement-level trigger: one increment per statement, on a random shard
UPDATE table_stats_shard
SET row_count = row_count + (SELECT count(*) FROM new_rows)
WHERE table_name = 'payment' AND shard = floor(random() * 16)::int;
-- Reading the total
SELECT sum(row_count) FROM table_stats_shard WHERE table_name = 'payment'; -- 10000000

Notice that doing the increment once per statement already removes almost all the cost: one update per COPY instead of 10 million. Sharding then removes the remaining contention between parallel loads.

5Planned Bulk Loads: Disable With Care

For a planned, controlled load, such as a migration or a backfill, we can disable the trigger for the load and do its work separately in bulk. ALTER TABLE ... DISABLE TRIGGER turns the trigger off for every session, not just ours, and takes a lock on the table, so other writers during that window would also skip the audit. That makes it suitable only when the load is the only writer, or when we accept and handle the gap. After the load, we write the audit rows in one INSERT ... SELECT, recompute the counter, and enable the trigger again, ideally in a script that re-enables it even if the load fails.

SQL
ALTER TABLE payment DISABLE TRIGGER payment_ai_stmt;
COPY payment FROM '/data/payments.csv' WITH (FORMAT csv); -- about 1.5 minutes
INSERT INTO payment_audit (payment_id, amount, loaded_at)
SELECT id, amount, now() FROM payment WHERE batch_id = 20261105;
ALTER TABLE payment ENABLE TRIGGER payment_ai_stmt;

6Follow-up questions

Why is COPY affected more than single inserts?

COPY is designed to write rows very fast with minimal per-row overhead, so a per-row trigger multiplies its cost the most. For row-by-row inserts from an application, the trigger adds a smaller relative cost, because each insert already pays for a statement and a round trip.

Could we keep the row trigger but make the counter cheaper?

Doing the counter update less often is the key. Even a per-row trigger that only writes audit rows, with the counter moved to a statement trigger or a job, removes the hot row. The per-row function call and audit insert would still cost several times the load, so a statement trigger is better for bulk loads.

How do you find which triggers slow down a load?

Compare the load with and without triggers in a staging copy, and use EXPLAIN ANALYZE on a sample INSERT, which reports the time spent in each trigger. pg_stat_user_functions, with track_functions enabled, shows how often each trigger function ran and its total time.

7Conclusion

In this answer, we saw why an AFTER INSERT row trigger made a 10-million-row load 20 times slower: it adds a function call, an audit insert and a counter update to every row, and the counter is a hot row that serialises parallel loads and fills with dead versions. We redesigned the audit as a statement-level trigger with transition tables, or as CDC outside the transaction, replaced the single counter with on-demand counts, a periodic job or sharded counters, and for planned loads disabled the trigger deliberately and did the audit work in bulk afterwards.

What to say in the interviewAbout 90 seconds aloud

Open with

There are two costs. First, a row trigger runs once per row, so for 10 million rows we added 10 million PL/pgSQL calls, 10 million audit inserts with their index updates, and 10 million counter updates.

Then, if they want more

COPY is fast because it has almost no per-row overhead, so tripling the work per row hurts it most. Second, and worse, the counter is a hot row. Every insert updates the same row in table_stats.

In PostgreSQL every update writes a new row version, so one load creates 10 million dead versions that vacuum cannot clean until the load commits, and the row lock is held until commit, so a second loader waits for the first and parallel loads become serial.

To redesign, I would replace the row trigger with an AFTER INSERT statement-level trigger using a transition table, REFERENCING NEW TABLE AS new_rows, and write all audit rows with one INSERT SELECT; or, if the audit does not need to be in the same transaction, capture changes with logical decoding or Debezium outside it.

For the counter, I would ask whether anyone needs it stored; if so, a periodic job or sharded counters, incremented once per statement. And for planned bulk loads, I might disable the trigger with ALTER TABLE DISABLE TRIGGER, knowing it affects all sessions, then write the audit rows in bulk and re-enable it.

About this answer

Last updated
12 November 2026
Versions it names
PostgreSQL 10
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Bulk loading 10 million rows into a table became 20 times slower after someone added an...": https://scrivio-interview-library.netlify.app/databases/stored-code/f641575213/