Introduction

Distributed applications often use multiple PostgreSQL databases to support reporting, read-heavy workloads, regional deployments, or disaster recovery. Logical replication makes it possible to copy selected table changes from one PostgreSQL instance to another without replicating the entire database.

However, applications that use auto-generated IDs have an additional requirement. PostgreSQL tables commonly use sequences to generate values for primary keys. Before PostgreSQL 19, logical replication copied table rows but did not automatically synchronize the sequence values that generated those IDs.

This created a problem during database migration or failover. The subscriber could contain the latest replicated records while its sequences still held older values. If the subscriber became the primary database, new inserts could generate IDs that already existed in the table.

PostgreSQL 19 introduces logical replication support for sequence values. Developers can now publish sequences and synchronize their values between a publisher and subscriber.

This feature makes database migration and planned switchover workflows easier. However, sequence synchronization is not continuous in the same way as table replication. Understanding when synchronization happens and how to refresh sequence values is important before using it in a production application.

Understanding Sequence Replication in PostgreSQL 19

A PostgreSQL sequence is a database object that generates numeric values. It is commonly used with SERIAL columns or identity columns.

Consider a table that stores customer records:

Code
CREATE TABLE customers (
    id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    name TEXT NOT NULL,
    email TEXT NOT NULL
);

When a new customer is inserted, PostgreSQL automatically generates the ID using an associated sequence.

Code
INSERT INTO customers (name, email)
VALUES ('John Smith', '[email protected]');

The generated ID is stored in the table, but the sequence maintains its own state independently.

In earlier PostgreSQL versions, logical replication transferred the inserted customer row to the subscriber, but it did not continuously replicate the sequence's current value.

For example, the publisher might generate IDs up to 5000 while the subscriber's sequence remains at 1000. The subscriber can contain the replicated customer records, but its sequence does not automatically know that the publisher has advanced.

PostgreSQL 19 adds support for publishing sequence values through logical replication. A publisher can include all sequences in a publication, and the subscriber can synchronize their values.

There is an important distinction: PostgreSQL 19 does not continuously replicate every sequence increment. Sequence synchronization occurs when the subscription is created or when specific subscription refresh operations are executed.

Setting Up the Publisher Database

Let's create a simple distributed application scenario with two PostgreSQL databases:

  • Publisher: the primary application database where customer records are inserted.

  • Subscriber: a secondary database that receives replicated customer records.

First, create the customer table on the publisher.

Code
CREATE TABLE customers (
    id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    name TEXT NOT NULL,
    email TEXT NOT NULL
);

Insert a few records.

C#
INSERT INTO customers (name, email)
VALUES
    ('John Smith', '[email protected]'),
    ('Sarah Lee', '[email protected]'),
    ('David Brown', '[email protected]');

The identity column uses an associated sequence to generate the IDs.

Next, create a publication that includes the customer table and all sequences in the database.

Code
CREATE PUBLICATION app_publication
FOR TABLE customers, ALL SEQUENCES;

The ALL SEQUENCES clause makes the database sequences part of the publication. This is useful when an application has multiple identity columns or uses sequences for different types of records.

If the application has additional tables that need replication, include them in the publication as required.

For example:

Code
CREATE PUBLICATION app_publication
FOR TABLE customers, orders, products,
ALL SEQUENCES;

The publication defines which table changes and sequence objects are available to subscribers.

Creating the Subscriber Database

The subscriber needs a compatible table and sequence structure before logical replication can work correctly.

Logical replication does not automatically replicate database schema definitions or DDL commands. You should create the required tables, columns, constraints, and sequence definitions on the subscriber before starting replication.

For example, create the customer table with the same structure:

Code
CREATE TABLE customers (
    id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    name TEXT NOT NULL,
    email TEXT NOT NULL
);

Make sure the associated sequence has compatible settings. PostgreSQL checks sequence definitions during synchronization. Differences in properties such as increment, minimum value, maximum value, or cycle behavior can prevent synchronization from completing.

Now create a subscription on the subscriber:

Code
CREATE SUBSCRIPTION app_subscription
CONNECTION 'host=publisher-host
port=5432
dbname=appdb
user=replication_user
password=your_password'
PUBLICATION app_publication;

The subscription connects to the publisher and starts receiving changes.

By default, copy_data is true. PostgreSQL copies the initial table data and synchronizes the initial sequence values as part of subscription initialization.

In production, use an appropriate authentication method and secure the connection rather than placing passwords directly in scripts or source control.

Understanding How Sequence Synchronization Works

PostgreSQL 19 provides three important subscription operations for sequence synchronization.

The first is initial synchronization during subscription creation. When a subscription is created with the default copy_data setting, PostgreSQL copies the initial sequence values from the publisher.

The second operation is REFRESH PUBLICATION. When new sequences are added to the publication, refreshing the publication allows the subscriber to synchronize newly added sequences known through that publication.

Code
ALTER SUBSCRIPTION app_subscription
REFRESH PUBLICATION;

The third operation is REFRESH SEQUENCES. It synchronizes all sequences currently known to the subscription.

Code
ALTER SUBSCRIPTION app_subscription
REFRESH SEQUENCES;

This operation is particularly useful before a planned database switchover. The publisher may have generated many new sequence values since the initial synchronization. Refreshing the sequences brings the subscriber's stored sequence values up to date.

A sequence synchronization worker performs the operation and exits after synchronization completes. The number of workers available for synchronization is controlled by max_sync_workers_per_subscription.

It is important to remember that sequence synchronization is not continuous. Normal inserts on the publisher do not automatically update the subscriber's sequence state after the initial synchronization.

Checking Sequence Synchronization

PostgreSQL 19 provides the pg_get_sequence_data function to inspect sequence information on the publisher.

For example:

Code
SELECT *
FROM pg_get_sequence_data('customers_id_seq');

The function returns information including:

  • last_value: the stored sequence value.

  • is_called: whether the sequence has already been used.

  • page_lsn: the WAL location associated with the sequence state.

You can use this information to compare the publisher's sequence state with the synchronization information stored on the subscriber.

On the subscriber, inspect pg_subscription_rel:

VB.NET
SELECT
    srrelid::regclass AS sequence_name,
    srsublsn
FROM pg_subscription_rel
ORDER BY srrelid::regclass::text;

The srsublsn value records the sequence synchronization position known to the subscription.

For a reliable comparison, obtain the publisher's page_lsn using pg_get_sequence_data and compare it with the corresponding subscriber synchronization position. If the publisher has advanced beyond the recorded position, the sequence may need refreshing.

There is an important limitation when interpreting these values. PostgreSQL sequences cache blocks of values in memory, typically 32 values by default. The sequence page LSN advances only after the cached block has been consumed and a new WAL record is generated.

Therefore, an LSN comparison may not detect every sequence value difference. Applications should not treat this comparison as a guarantee that the publisher and subscriber have identical next values at every moment.

Preparing for a Database Switchover

One of the most useful scenarios for PostgreSQL 19 sequence replication is a planned database switchover.

Imagine an application currently using a publisher database in one region. A second PostgreSQL instance receives table changes through logical replication and is prepared to become the new primary database.

Before the switch, the secondary database must have the latest available table data and sequence values.

A controlled switchover process should include the following steps:

  1. Stop or temporarily restrict new application writes on the publisher.

  2. Wait for the subscriber to apply the outstanding table changes.

  3. Execute REFRESH SEQUENCES on the subscriber.

  4. Verify that the required sequences have synchronized successfully.

  5. Confirm that the subscriber has the expected table data and sequence definitions.

  6. Redirect application writes to the new primary database.

For example, the final sequence refresh can be performed with:

Code
ALTER SUBSCRIPTION app_subscription
REFRESH SEQUENCES;

Do not assume that this command alone guarantees a safe failover. The application must also account for outstanding transactions, replication lag, schema compatibility, and any writes that were accepted after the last synchronization point.

A planned switchover should use a controlled write-freeze or equivalent coordination process. This prevents the old publisher from generating additional values after the subscriber has been prepared.

Handling Sequence Definition Mismatches

Sequence synchronization requires compatible definitions on both databases.

For example, suppose the publisher uses this sequence:

Code
CREATE SEQUENCE order_number_seq
START WITH 1000
INCREMENT BY 1;

But the subscriber has a different definition:

Code
CREATE SEQUENCE order_number_seq
START WITH 1
INCREMENT BY 10;

The sequence synchronization worker detects the mismatch and reports an error. It does not silently change the subscriber's sequence definition to match the publisher.

You should inspect the sequence settings and align them using ALTER SEQUENCE.

Code
ALTER SEQUENCE order_number_seq
INCREMENT BY 1
MINVALUE 1
START WITH 1000;

The exact settings should match the publisher's intended sequence definition. Do not blindly copy example values into a production database.

After correcting the mismatch, allow the synchronization worker to retry or execute the appropriate refresh operation.

Monitoring PostgreSQL logs is important because a definition mismatch can prevent sequence synchronization from completing even while normal table replication continues.

Important Limitations and Best Practices

PostgreSQL 19 sequence replication is useful, but it does not turn sequences into continuously replicated data objects.

For a production application, keep the following points in mind.

First, sequence synchronization requires the publisher to run PostgreSQL 19 or later. Do not assume that a PostgreSQL 18 publisher can provide the same sequence synchronization behavior.

Second, sequence values are not continuously replicated. A read-only subscriber can use the replicated table data without immediately needing the latest sequence state, but a subscriber intended for promotion must be refreshed before it accepts new writes.

Third, schema changes are not automatically replicated. When you add a new table or sequence, update the subscriber's schema and refresh the publication as part of your deployment process.

Fourth, avoid allowing independent application writes to the same replicated tables on both publisher and subscriber. Logical replication is not a multi-primary conflict-resolution system. Independent writes can create data and sequence conflicts.

Finally, monitor sequence synchronization workers and PostgreSQL logs. A successful subscription does not necessarily mean that every sequence definition is compatible or that every sequence is synchronized.

Summary

PostgreSQL 19 adds logical replication support for sequence values, addressing an important gap in distributed database environments. Applications can publish all sequences using the ALL SEQUENCES clause and synchronize their values when creating or refreshing subscriptions.

The REFRESH SEQUENCES operation is particularly useful before a planned switchover because it updates the subscriber's known sequences from the publisher. However, sequence changes are not continuously replicated, so applications must coordinate writes and synchronization carefully.

By maintaining compatible sequence definitions, monitoring synchronization status, and refreshing sequences before promoting a subscriber, development teams can make PostgreSQL logical replication more reliable for distributed applications.