Sub topic 8
Replica identity: how updates and deletes find rows
This chapter assumes you can create tables and primary keys, run psql, and know that a publication sends row changes from a publisher to a subscriber. It also assumes you know that a subscription applies those changes to its own copy of the table.
Why the subscriber needs a way to find rows
An INSERT carries the whole new row, so the subscriber can simply add it. An UPDATE or DELETE is different. The subscriber must find the matching row in its own copy of the table before it can change or remove it.
The publisher cannot send a physical row address. Row addresses (ctid values) differ between servers. Instead, the publisher sends a set of column values that identify the old row. That set is the replica identity. It is a property of a table on the publisher, and it decides which old column values go into the change stream for updates and deletes.
The four replica identity settings
Each table has one of four settings. You can see it in pg_class.relreplident.
| Setting | `relreplident` | Old values sent for updates and deletes |
|---|---|---|
| `DEFAULT` | `d` | The primary key columns, if the table has a primary key. Otherwise nothing. |
| `USING INDEX index_name` | `i` | The columns of the named unique index. |
| `FULL` | `f` | All columns of the old row. |
| `NOTHING` | `n` | Nothing. |
DEFAULT
DEFAULT is what every table starts with. If the table has a primary key, the primary key columns are the identity. This is the right choice for most tables, and it is why the orders table from the earlier chapters worked with no extra setup.
If the table has no primary key, DEFAULT sends no old-row key. Such a table can still be published, but it cannot replicate updates or deletes.
USING INDEX
You can name a unique index instead of the primary key. The index must meet these conditions:
- It must be unique.
- It must not be partial.
- It must not be an expression index.
- Every column in it must be
NOT NULL.
The last rule matters because a NULL never equals another NULL in a comparison. The subscriber could not reliably match a row on a nullable column.
CREATE TABLE accounts (
id bigint NOT NULL,
email text NOT NULL,
plan text NOT NULL
);
CREATE UNIQUE INDEX accounts_email_key ON accounts (email);
ALTER TABLE accounts REPLICA IDENTITY USING INDEX accounts_email_key;This is useful when a table has no primary key but has a natural unique column. It is also useful when you want a smaller identity than a wide composite primary key.
FULL
FULL sends every column of the old row. The subscriber then looks for a row where all columns match those old values. This works for any table, including tables with duplicate rows and no unique key.
-- On the publisher: table without a primary key
ALTER TABLE audit_log REPLICA IDENTITY FULL;FULL has real costs:
- Every update and delete writes the whole old row to the WAL, so WAL volume grows.
- On the subscriber, finding the row can require a sequential scan if no suitable index exists. On a large table, each replicated change then scans the whole table.
- Some column types cannot be compared with
=reliably, which can make matching fail or become very slow.
If you must use FULL, create an index on the subscriber that helps the lookup. From PostgreSQL 16 the subscriber can use a B-tree or hash index on the table for this purpose. In earlier versions, only the subscriber's primary key or replica identity index is considered, and otherwise it uses a sequential scan.
NOTHING
NOTHING sends no old-row information. With this setting, updates and deletes on a published table fail on the publisher, as the next section shows. Use it only for tables where you never update or delete, or on tables you do not publish.
What happens when the identity is missing
The error appears on the publisher, at the time of the change, and not on the subscriber. Suppose a table with no primary key is added to a publication that publishes updates and deletes.
-- On the publisher
CREATE TABLE audit_log (
logged_at timestamptz NOT NULL,
message text NOT NULL
);
CREATE PUBLICATION audit_pub FOR TABLE audit_log;
INSERT INTO audit_log VALUES (now(), 'started'); -- works
UPDATE audit_log SET message = 'restarted'; -- failsThe update fails with an error like this:
ERROR: cannot update table "audit_log" because it does not have a replica identity and publishes updates
HINT: To enable updating the table, set REPLICA IDENTITY using ALTER TABLE.This is a safety check. PostgreSQL refuses the change locally instead of letting a change enter the WAL that no subscriber could apply. The inserts still work, which is why the problem often appears only when the first update or delete runs in production.
You can find published tables that are likely to fail with a query like this one. It lists tables in a publication whose identity is DEFAULT but that have no primary key, or whose identity is NOTHING.
SELECT p.pubname, c.oid::regclass AS table_name, c.relreplident
FROM pg_publication_tables pt
JOIN pg_publication p ON p.pubname = pt.pubname
JOIN pg_class c ON c.oid = format('%I.%I', pt.schemaname, pt.tablename)::regclass
WHERE (p.pubupdate OR p.pubdelete)
AND (
c.relreplident = 'n'
OR (c.relreplident = 'd'
AND NOT EXISTS (
SELECT 1 FROM pg_index i
WHERE i.indrelid = c.oid AND i.indisprimary))
);How the identity travels through the stream
For an update, the change record has two parts: the old key values and the full new row. If the key columns did not change, the old key is often omitted and the subscriber uses the key values from the new row. If the key changed, the old key is sent so the subscriber can find the original row.
The diagram shows how the subscriber uses the identity.
If the row is not found, the subscriber does not stop. In current versions it skips an update or delete that matches no row and logs the fact at a low severity. This can hide data drift, so a missing row on the subscriber deserves attention when you monitor replication.
Matching columns on the subscriber
The identity columns on the publisher must exist on the subscriber, and the subscriber needs some way to search on them efficiently. The subscriber's table does not need to use the same kind of identity.
In practice, apply these rules:
- The subscriber's table must have the columns that make up the publisher's identity.
- The subscriber should have a unique index on those columns, or on a primary key, so each lookup is fast.
- The subscriber's own replica identity setting is irrelevant for applying changes. It matters only if the subscriber also publishes the table to other nodes.
Checking and changing the identity
Read the current setting from the catalog:
SELECT relname,
CASE relreplident
WHEN 'd' THEN 'default'
WHEN 'i' THEN 'index'
WHEN 'f' THEN 'full'
WHEN 'n' THEN 'nothing'
END AS replica_identity
FROM pg_class
WHERE relname = 'audit_log';To see which index is used when the setting is index, look for indisreplident:
SELECT indexrelid::regclass AS index_name
FROM pg_index
WHERE indrelid = 'accounts'::regclass
AND indisreplident;Change the setting with ALTER TABLE:
ALTER TABLE audit_log REPLICA IDENTITY FULL;
ALTER TABLE accounts REPLICA IDENTITY USING INDEX accounts_email_key;
ALTER TABLE accounts REPLICA IDENTITY DEFAULT;Two details are easy to miss:
ALTER TABLE ... REPLICA IDENTITYis not replicated. Run it on every node that publishes the table.- If you drop the index that serves as the identity, the setting reverts to behave as if there were no identity, and updates and deletes start to fail. Change the identity before you drop the index.
Choosing an identity: decision guide
| Situation | Choice |
|---|---|
| Table has a primary key | `DEFAULT` |
| No primary key, but a unique `NOT NULL` column set exists | Add a primary key if you can. Otherwise `USING INDEX`. |
| No unique key, small table or low update rate | `FULL` |
| No unique key, large table with frequent updates | Add a key to the table. `FULL` will be slow and bloat the WAL. |
| Append-only table | Any, but `DEFAULT` with no key is fine if you publish inserts only |
Adding a primary key is nearly always the best long-term answer. It makes the table easier to replicate and also easier to use with other tools.
Common errors
- Update fails on the publisher with "does not have a replica identity". The table has no usable identity. Add a primary key or set
REPLICA IDENTITY. - Replication is very slow on one table after it was set to
FULL. The subscriber is scanning the table for each change. Add a suitable index on the subscriber, or move to a key-based identity. USING INDEXfails with "index cannot be used as replica identity because column ... is nullable". AddNOT NULLconstraints to the index columns first.- Rows on the subscriber drift from the publisher. Updates matched no row and were skipped. Compare row counts and check the subscriber logs.
Exercise
A table events(event_id bigint, payload jsonb) has no primary key and no unique index. It is added to a publication that publishes all operations. Inserts work, but the first DELETE on the publisher fails. Give two ways to fix this and name one drawback of each.
Show answer
Option 1: add a primary key (for example on event_id, after making sure it is unique and not null). The drawback is that building the key takes time and locks on a large table, and existing duplicate values must be cleaned up first. Option 2: run ALTER TABLE events REPLICA IDENTITY FULL. The drawback is that each delete writes the full old row to the WAL, and the subscriber may need a sequential scan to find the row, and jsonb values add comparison cost.
Exercise
You set REPLICA IDENTITY USING INDEX accounts_email_key on the publisher, and later a colleague drops that index. What happens to updates and deletes on accounts, and what should have been done first?
Show answer
Updates and deletes on the publisher start failing because the table no longer has a usable replica identity. Before dropping the index, change the identity to another valid setting, for example ALTER TABLE accounts REPLICA IDENTITY DEFAULT if the table has a primary key, or create and select a replacement unique index.