session_replication_role = replica tells the server that the rows this session is about to write were already checked somewhere else. A replication system can say that and mean it. Most other sessions that say it found the line in an answer to “how do I turn off foreign keys in PostgreSQL?”

It is an enum with three values: origin (the default), replica and local. The context is superuser, which since PostgreSQL 15 also covers any role that has been given GRANT SET ON PARAMETER session_replication_role. There is nothing here to tune; the parameter decides which triggers and rules exist, as far as the current session is concerned. row_security = off sounds like an off switch and isn’t one. This one sounds like replication plumbing and is an off switch, for more than its entry in the manual admits.

Four letters

Every trigger, rewrite rule and event trigger carries a one-character enable state, stored in pg_trigger.tgenabled, pg_rewrite.ev_enabled and pg_event_trigger.evtenabled. A plain CREATE TRIGGER gives you O, which fires when the session’s role is origin or local and stays quiet under replica. ALTER TABLE ... ENABLE REPLICA TRIGGER changes it to R, which is the reverse. ENABLE ALWAYS is A and fires under all three; DISABLE is D and fires under none. The server treats origin and local as the same thing. The second name is there for third-party replication systems, which can use it to mark a session whose changes should not be replicated.

Jan Wieck added the mechanism in 8.3 so that replication systems, Slony-I first among them, could control trigger firing without editing the system catalogs directly. Two details of that design still matter. ON SELECT rules ignore the state entirely, so views keep working whatever the role. And because rules are applied before a query is planned, changing the parameter discards every cached plan in the session. (Event triggers arrived later and follow the same four states; since 17 they also have a switch of their own, event_triggers.)

The sessions that set it for you

Every logical replication worker sets the parameter to replica as it starts: the apply worker, the parallel apply workers, the table synchronization workers (the cast of max_logical_replication_workers), and in 19 the sequence synchronization worker. pglogical and Spock do the same. So on a subscriber, none of your ordinary triggers fire for replicated rows. That is the right default. If a trigger on the publisher writes a row to a second table and that table is published too, the subscriber already receives the row, and firing the trigger again there would write it twice. It is also why the audit trigger you installed only on the subscriber has never recorded a replicated change.

For a trigger that should fire there, use ENABLE REPLICA (replicated changes only) or ENABLE ALWAYS (those and local ones). For INSERT, UPDATE and DELETE, though, the apply worker fires row-level triggers only; a statement-level INSERT trigger fires during the initial table copy and not afterwards. (The manual says the apply worker fires no statement triggers at all. A replicated TRUNCATE fires its statement-level trigger on 18.7 and 19.0.) And replication workers run with an empty search_path, so a trigger function containing INSERT INTO audit_log works from every session you test it in and fails in the worker with relation "audit_log" does not exist. The worker exits, restarts and fails again every five seconds (the default wal_retrieve_retry_interval), and the whole subscription waits behind that one row while pg_stat_subscription_stats.apply_error_count climbs. Schema-qualify the names, or give the function its own SET search_path.

Foreign keys are triggers, and so is something else

PostgreSQL implements a foreign key between two tables as four internal triggers, two on each: the checks on insert and update on the referencing side, and the ON DELETE and ON UPDATE actions on the referenced side. All four are in state O. Under replica, none of them fire.

1demo=# SET session_replication_role = replica;
2demo=# INSERT INTO child VALUES (99, 999); -- there is no parent 999
3INSERT 0 1
4demo=# DELETE FROM parent WHERE id = 2; -- child 20 references it, ON DELETE CASCADE
5DELETE 1
6demo=# RESET session_replication_role;
7demo=# SELECT * FROM child;
8 id | parent_id
9----+-----------
10 10 | 1
11 20 | 2
12 99 | 999
13demo=# SELECT convalidated FROM pg_constraint WHERE conname = 'child_parent_id_fkey';
14 convalidated
15--------------
16 t
17demo=# ALTER TABLE child VALIDATE CONSTRAINT child_parent_id_fkey;
18ALTER TABLE

The orphan goes in. The parent goes away and its child stays, ON DELETE CASCADE notwithstanding. Afterwards the catalog still calls the constraint valid, and VALIDATE CONSTRAINT returns at once because, by its lights, there is nothing to validate. Nothing in the server will go back and look on its own. The parameter’s entry in the manual spends one sentence on this, added in PostgreSQL 11, ten years after the parameter itself: replica also disables all foreign key checks, “which can leave data in an inconsistent state if improperly used.” (Its regression tests date from the same day. Their commit message: “This was hardly tested at all.”)

That entry stops at foreign keys. The code doesn’t. A DEFERRABLE primary key, unique constraint or exclusion constraint is also enforced by an internal trigger: the index insertion only notes that there might be a conflict, and a trigger function called unique_key_recheck makes the real decision at the end of the statement or at commit. That trigger is in state O as well.

1demo=# CREATE TABLE account (id int PRIMARY KEY DEFERRABLE, name text);
2demo=# INSERT INTO account VALUES (1, 'first');
3INSERT 0 1
4demo=# INSERT INTO account VALUES (1, 'second');
5ERROR: duplicate key value violates unique constraint "account_pkey"
6DETAIL: Key (id)=(1) already exists.
7demo=# SET session_replication_role = replica;
8demo=# INSERT INTO account VALUES (1, 'second');
9INSERT 0 1
10demo=# RESET session_replication_role;
11demo=# SELECT * FROM account WHERE id = 1;
12 id | name
13----+--------
14 1 | first
15 1 | second

That is two rows with one primary key, in a unique index that pg_index.indisvalid still vouches for, on 18.7 and on 19.0. It does not take a careless superuser to get there, either. Give a subscriber table a deferrable primary key and a row whose key the publisher also uses, and the apply worker inserts the second copy without reporting a conflict. (The logical replication chapter defines its conflicts in terms of NOT DEFERRABLE unique constraints. That is accurate, and easy to read past.)

The constraints that are not triggers are still enforced under replica: ordinary primary keys, unique constraints and exclusion constraints, CHECK and NOT NULL. So are row-level security and TRUNCATE’s refusal to empty a table that another table references.

A trigger’s enable state is examined when the row changes, not when the trigger runs. With a DEFERRABLE INITIALLY DEFERRED foreign key, a transaction that sets replica, inserts an orphan, sets the role back to origin and commits has committed an orphan: the check was never queued, so COMMIT has nothing to run.

The migration service tells you to set it

The AWS Database Migration Service documentation for PostgreSQL targets strongly recommends turning foreign keys off for a full load, offers this parameter as a way to do it (the endpoint setting is AfterConnectScript, with the value SET session_replication_role = replica), and ships a premigration assessment that checks whether you remembered. AWS’s Knowledge Center article on turning off foreign keys in RDS and Aurora gives two answers: drop the constraint, or set this parameter, either with SET in the session (after the GRANT, on 15 and later) or in the DB parameter group. It says to set the parameter back when you are done. Neither page says anything about validating the constraints afterwards.

The parameter group and the GRANT are wider than they look. A parameter group is the configuration file, and from the configuration file replica applies to every session of every role, including roles that would get permission denied if they tried to set it themselves. The context limits who may change the value, not who inherits it. And GRANT SET ON PARAMETER session_replication_role TO app lets app skip every foreign key and every O trigger on any table it can write to, including tables it does not own and whatever audit triggers their owner put there.

Finding out

pg_upgrade carries the damage to the new cluster without comment. I took an orphan and a duplicate primary key from 18.7 to 19.0, and both constraints arrived still marked valid. A logical dump and restore is less forgiving: pg_restore loads the rows, reports an error for each constraint the rows violate, finishes everything else and exits with status 1. The database it leaves has the rows and does not have those constraints.

To check before a restore does it for you: for a foreign key, add a second copy of it NOT VALID, run VALIDATE CONSTRAINT on that one (which scans for real), and drop it. For a deferrable unique index on 17 or later, bt_index_check(index, heapallindexed => true, checkunique => true) from amcheck reports the duplicate; without checkunique, the same index passes. To find out whether something on the cluster is set up to run as replica, look in pg_db_role_setting for ALTER ROLE and ALTER DATABASE settings, at pg_settings.source for the configuration file, in pg_parameter_acl for the grant, and in pg_proc.proconfig for functions that carry their own SET (a SECURITY DEFINER function owned by a superuser hands replica to anyone who can call it).

If what you want is a bulk load without foreign key checks, PostgreSQL 18 has a way to say so: ALTER TABLE ... ALTER CONSTRAINT ... NOT ENFORCED, load, then ENFORCED, which rescans the table and fails if the load left orphans. (Be on 18.4 or later; before that, the round trip left a DEFERRABLE INITIALLY DEFERRED foreign key behaving as NOT DEFERRABLE.) Before 18, drop the constraint and add it back afterwards. Either way, every session can see in the catalog that the constraint is off, and the database checks the rows before it says otherwise. session_replication_role does neither. Leave it to the replication workers, and if a migration tool has ever been pointed at your database, go and validate the foreign keys it was told to skip. convalidated only means somebody checked once.