Sub topic 11
Apply errors and conflicts on the subscriber
This chapter assumes you can create a publication and a subscription, and that you know what a replication slot holds back on the publisher. It covers what happens when the subscriber cannot apply a change, how to read the error, and how to recover without losing data.
How the apply worker handles a failure
A subscription has one apply worker. It receives decoded changes from the publisher and applies them in commit order, one remote transaction at a time. Each remote transaction is applied as a local transaction.
If any statement in that transaction fails, the whole local transaction rolls back and the worker exits. The worker then restarts after wal_retrieve_retry_interval (5 seconds by default) and tries the same transaction again. It stops only when you fix the cause or skip the transaction.
While the worker is stuck, the subscriber does not confirm the transaction as flushed. The publisher's slot cannot advance, so the publisher keeps all WAL from that point onward. An apply error that sits unnoticed for a day becomes a disk-space problem on the publisher.
Typical causes
Subscriber tables are ordinary tables and accept local writes. Logical replication does not stop you from changing them, and the apply worker does not coordinate with your other sessions. Most errors come from the subscriber's state differing from what the publisher expects.
| Cause | Typical error | Notes |
|---|---|---|
| Row already exists on the subscriber | `duplicate key value violates unique constraint` | Local insert, or a partial earlier load. |
| Subscriber-only unique index | `duplicate key value violates unique constraint` | The publisher never enforced this index. |
| Subscriber-only constraint | `null value ... violates not-null constraint` or a check violation | Constraints on the subscriber are enforced. |
| Missing table or column | `logical replication target relation ... does not exist` | DDL is not replicated. |
| Type mismatch | `invalid input syntax` or a conversion error | Values are sent as text and parsed on the subscriber. |
| Missing privilege | `permission denied for table` | The worker needs privileges on the target table. |
| Exclusion or foreign key violation | constraint error | Referential checks run on the subscriber. |
Two cases do not raise errors in most versions. An UPDATE or DELETE whose target row is missing on the subscriber is skipped. An update that changes a locally modified row overwrites it. Both can leave the two sides different without any sign that something went wrong.
Reproducing a conflict
The following sequence creates a duplicate key conflict. It assumes the orders_pub and orders_sub setup from earlier chapters. Run the first statement on the subscriber and the second on the publisher.
-- On the subscriber: a local write that the publisher does not know about
INSERT INTO orders (id, customer_id, status, total)
VALUES (42, 7, 'local', 10.00);
-- On the publisher: a different row with the same primary key
INSERT INTO orders (id, customer_id, status, total)
VALUES (42, 9, 'new', 99.50);The subscriber's log now repeats an entry like this every few seconds. The exact wording varies by version.
ERROR: duplicate key value violates unique constraint "orders_pkey"
DETAIL: Key (id)=(42) already exists.
CONTEXT: processing remote data for replication origin "pg_16395" during message type "INSERT" for replication target relation "public.orders" in transaction 740, finished at 0/14C0378Read three things from this message:
- The
DETAILline names the key and the constraint. - The
CONTEXTline names the target relation and the type of change. - The
finished atvalue is the LSN of the end of the remote transaction. You need it if you decide to skip the transaction.
On PostgreSQL 15 and later, you can also confirm that the subscription is failing from the statistics views.
SELECT subname, apply_error_count, sync_error_count
FROM pg_stat_subscription_stats;A steadily rising apply_error_count shows a stuck apply worker. sync_error_count counts the same kind of failure in the initial table copy workers.
Resolving the error
You have two kinds of fix. Change the subscriber so the transaction succeeds, or tell the subscriber to skip the transaction.
Fix the data
Fixing the data is usually correct, because it keeps both sides consistent. Decide which row is right. If the publisher's row should win, remove the local row. The next retry then succeeds without further action.
-- On the subscriber
DELETE FROM orders WHERE id = 42 AND status = 'local';The same approach applies to other causes. Add the missing column, relax the subscriber-only constraint, grant the missing privilege, or create the missing table and run ALTER SUBSCRIPTION ... REFRESH PUBLICATION.
Skip the transaction
Skipping discards every change in that remote transaction, not just the failing row. Use it only when you have decided that the data in the transaction is not needed on the subscriber, or when you have applied the changes by hand. On PostgreSQL 15 and later, a superuser can do this with the finish LSN from the log.
-- On the subscriber (PostgreSQL 15 or later, superuser required)
ALTER SUBSCRIPTION orders_sub SKIP (lsn = '0/14C0378');The worker skips the transaction that finishes at that LSN on its next attempt and clears the setting. If the LSN does not match the transaction being applied, nothing is skipped and the error continues. Check the value against the log before you run the command.
On PostgreSQL 14, SKIP does not exist. The alternative is to disable the subscription and move its replication origin forward with pg_replication_origin_advance. The origin is named pg_ followed by the subscription's OID, and you can list it with SELECT * FROM pg_replication_origin;. Follow the documentation for your exact version for the LSN to use.
Stop the retry loop automatically
If you would rather have the subscription stop than loop, set disable_on_error (PostgreSQL 15 and later).
ALTER SUBSCRIPTION orders_sub SET (disable_on_error = true);After an error, the subscription is disabled and the worker no longer retries. This removes log noise, but the slot is still inactive and the publisher still retains WAL. Disabling does not reduce urgency. It only makes the failure obvious in pg_subscription (subenabled = false). Re-enable with ALTER SUBSCRIPTION orders_sub ENABLE; after you fix the cause.
Conflicts that do not stop replication
Some divergence produces no error. The apply worker handles these cases quietly:
- Update of a missing row. The worker finds no row by replica identity and skips the update.
- Delete of a missing row. The worker skips it.
- Update of a locally changed row. The worker overwrites the local values, because the row is found by key and the new values are applied.
PostgreSQL 18 adds logging for these conflicts, with names such as update_missing and delete_missing. It also adds per-type counters in pg_stat_subscription_stats whose names start with confl_. On older versions you only find this divergence by comparing data.
A practical check is to compare row counts and checksums on a schedule.
-- Run on both sides and compare the output
SELECT count(*) AS n, sum(hashtextextended(o::text, 0)) AS checksum
FROM orders AS o;For large tables, compare by key range so you can find where the sides differ.
Triggers and the apply worker
The apply worker runs with session_replication_role = replica. Ordinary triggers and rules on subscriber tables therefore do not fire for replicated rows. This avoids double-processing, but it surprises people who add audit triggers on the subscriber.
-- On the subscriber: fire this trigger for rows applied by replication
ALTER TABLE orders ENABLE REPLICA TRIGGER orders_audit_trg;Use ENABLE ALWAYS TRIGGER for a trigger that must fire for both local and replicated changes. Be careful about what such a trigger writes. If it modifies a table that is also replicated, you create new conflict opportunities.
Preventing conflicts
- Treat subscribed tables as read-only on the subscriber. Revoke
INSERT,UPDATE, andDELETEfrom application roles, or put the subscriber behind a read-only role. - Keep constraints the same on both sides. A subscriber-only unique index or
NOT NULLis a source of errors that appear only under certain data. - Roll out DDL in a safe order. Add new columns to the subscriber first, then to the publisher. For drops and renames, reverse the order, and pause where needed.
- Alert on
apply_error_count, subscription state, and retained WAL. Do not rely on someone reading the logs. - Test a skip procedure before you need it. Practice on a staging pair so the LSN handling is familiar.
Exercise
The subscriber's log shows the same duplicate key error every five seconds, and the publisher's disk usage is rising. Why does the publisher's disk fill, and what are two ways to get the subscription moving again?
Show answer
The apply worker rolls back the failing transaction and retries, so it never confirms that position. The slot cannot advance and the publisher keeps all WAL after it. To recover, either fix the subscriber so the transaction succeeds (for example delete the conflicting local row), or skip the transaction with ALTER SUBSCRIPTION ... SKIP (lsn = '<finish LSN from the log>') on PostgreSQL 15 or later, accepting that every change in that transaction is lost on the subscriber.
Exercise
A DELETE on the publisher removes a row that does not exist on the subscriber. What happens on a PostgreSQL 16 subscriber, and how could you detect the divergence?
Show answer
The apply worker finds no row for the key and skips the delete without an error, so replication continues and nothing stops. You can detect the divergence only by comparing data, for example with row counts or per-range checksums on both sides. PostgreSQL 18 adds conflict logging and counters that report this case as delete_missing.