PostgreSQL sequences are commonly used to generate unique identifiers for database records. When an application inserts a new customer, order, payment, or transaction, a sequence can generate the next identifier automatically.
In a database using logical replication, table records can be replicated from a publisher to a subscriber. However, sequence values have traditionally required separate management. This creates a potential problem when an application moves workloads between database servers or prepares a subscriber for failover.
For example, the publisher might generate customer IDs up to 5000, while the subscriber still has a sequence value of 4500. If the subscriber becomes a writable database without synchronizing its sequence, it might generate an identifier that already exists.
PostgreSQL 19 introduces logical replication support for sequence values. Developers can now publish sequences, synchronize their values with subscribers, and refresh sequence state when required.
In this article, we will explore how PostgreSQL 19 sequence replication works, how to configure it, how to monitor synchronization, and how to manage the process from a .NET application using Npgsql.
Understanding PostgreSQL Sequences
A sequence is a database object that generates numeric values, usually in an increasing or decreasing order. It is commonly used with primary keys.
Consider the following table:
CREATE TABLE customers
(
customer_id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer_name VARCHAR(150) NOT NULL,
email VARCHAR(200) NOT NULL
);
The identity column uses a sequence internally to generate customer IDs.
You can also create a sequence explicitly:
CREATE SEQUENCE order_id_seq
START WITH 1000
INCREMENT BY 1;
The application can retrieve the next value using:
SELECT nextval('order_id_seq');
PostgreSQL returns the next available sequence value. The value can then be used when inserting a record.
Sequences are different from ordinary table data. They maintain their own state, including the last generated value and whether the sequence has already been called.
For example, inspect a sequence using:
SELECT last_value, is_called
FROM order_id_seq;
The last_value column indicates the current sequence state, while is_called determines whether the sequence has already generated a value.
This distinction becomes important when replicating data between PostgreSQL servers.
Why Sequence Replication Matters
PostgreSQL logical replication traditionally replicates changes to published tables, but sequence state is handled separately.
Consider an application with two PostgreSQL servers:
The publisher inserts new orders and generates identifiers using a sequence.
INSERT INTO orders (customer_id, total_amount)
VALUES (101, 2500.00);
The corresponding table row is replicated to the subscriber. However, the subscriber's sequence does not automatically advance every time the publisher generates a new value.
This creates a difference between the sequence state on the two servers.
Component | Publisher | Subscriber |
|---|
Order records | Latest records | Replicated records |
Sequence value | 5000 | 4500 |
New ID generation | Continues from publisher state | May generate an outdated value |
If the subscriber is used only for read-only queries, this difference may not immediately cause a problem.
However, it becomes important during database migration, switchover, or failover. If the subscriber becomes writable, its outdated sequence can generate conflicting identifiers.
PostgreSQL 19 addresses this limitation by introducing sequence synchronization through logical replication.
How PostgreSQL 19 Sequence Replication Works
PostgreSQL 19 allows sequence objects to be included in logical publications.
The new FOR ALL SEQUENCES clause makes it possible to publish all sequences in a database.
The subscriber can then synchronize sequence values through a sequence synchronization worker.
There are three important operations:
Initial synchronization when a subscription is created with data copying enabled.
Synchronization of newly added sequences when the publication is refreshed.
Re-synchronization of all sequences already known to the subscription using REFRESH SEQUENCES.
The synchronization worker runs after the relevant subscription operation and exits after synchronization is complete.
An important distinction is that PostgreSQL 19 does not continuously replicate every individual nextval call as an immediate sequence update. Sequence values on the subscriber can become outdated as the publisher continues generating values. Administrators can refresh the sequence state when required.
Sequence synchronization also requires the publisher to run PostgreSQL 19 or later.
Configure Sequence Replication
Let's configure logical sequence replication using a publisher and a subscriber.
Assume that the publisher database contains an orders table and an order_id_seq sequence.
Create the Sequence on the Publisher
Run the following command on the publisher:
CREATE SEQUENCE order_id_seq
START WITH 1000
INCREMENT BY 1;
CREATE TABLE orders
(
order_id BIGINT PRIMARY KEY
DEFAULT nextval('order_id_seq'),
customer_name VARCHAR(150) NOT NULL,
total_amount NUMERIC(12, 2) NOT NULL
);
The sequence generates values for the order_id column.
Insert some records:
INSERT INTO orders (customer_name, total_amount)
VALUES
('John', 1500.00),
('Sarah', 2200.00),
('David', 1800.00);
The publisher now has table records and an associated sequence.
Create a Publication for Sequences
On the publisher, create a publication:
CREATE PUBLICATION orders_publication
FOR ALL SEQUENCES;
This publication includes all sequences in the database.
If the application also needs to replicate table changes, create a table publication separately:
CREATE PUBLICATION orders_table_publication
FOR TABLE orders;
Keeping the publications separate makes it easier to understand which database objects are included in each replication configuration.
Prepare the Subscriber
The subscriber must have compatible database objects and sequence definitions.
For example:
CREATE SEQUENCE order_id_seq
START WITH 1000
INCREMENT BY 1;
CREATE TABLE orders
(
order_id BIGINT PRIMARY KEY,
customer_name VARCHAR(150) NOT NULL,
total_amount NUMERIC(12, 2) NOT NULL
);
Logical replication does not automatically replicate general schema changes or DDL commands. Create the required schema and table definitions on the subscriber before starting replication.
The sequence definitions must also match the publisher. PostgreSQL validates sequence definitions during synchronization and reports mismatches.
Create the Subscription
Run the following command on the subscriber:
CREATE SUBSCRIPTION orders_sequence_subscription
CONNECTION
'host=publisher-db
port=5432
dbname=appdb
user=replication_user
password=secret'
PUBLICATION orders_publication;
The default copy_data setting is true. PostgreSQL starts sequence synchronization as part of subscription initialization.
The sequence synchronization worker copies the initial sequence state from the publisher.
You can verify the subscriber's sequence state:
SELECT last_value, is_called
FROM order_id_seq;
The subscriber should now contain the synchronized sequence state.
In production, store replication credentials securely and use appropriate network and authentication controls rather than placing passwords directly in SQL scripts.
Refresh Sequence Values When They Become Out of Sync
Initial synchronization does not mean that the subscriber's sequence will remain identical to the publisher forever.
As the publisher continues generating sequence values, the subscriber can become outdated.
PostgreSQL 19 provides the following command to synchronize all sequences already known to the subscription:
ALTER SUBSCRIPTION orders_sequence_subscription
REFRESH SEQUENCES;
This command starts a sequence synchronization worker. The worker retrieves the current sequence state from the publisher and updates the subscriber.
Use this operation when preparing a subscriber for a controlled switchover, failover, or other operation that requires updated sequence values.
PostgreSQL 19 also supports refreshing the publication:
ALTER SUBSCRIPTION orders_sequence_subscription
REFRESH PUBLICATION;
This operation synchronizes newly added objects known through the publication, including newly added sequences.
The distinction is important:
Command | Purpose |
|---|
CREATE SUBSCRIPTION | Initializes subscription and copies initial sequence state when data copying is enabled |
REFRESH PUBLICATION | Refreshes publication membership and synchronizes newly added sequences |
REFRESH SEQUENCES | Re-synchronizes all sequences already known to the subscription |
The synchronization worker is limited by the max_sync_workers_per_subscription configuration. Ensure that the subscriber has sufficient synchronization worker capacity for its replication workload.
Monitor Sequence Synchronization
PostgreSQL 19 provides the pg_get_sequence_data() function to inspect sequence state on the publisher.
Run the following query on the publisher:
SELECT *
FROM pg_get_sequence_data('order_id_seq');
The function returns information including:
last_value: The stored sequence value.
is_called: Whether the sequence has been called.
page_lsn: The WAL position associated with the sequence state.
The page_lsn value helps identify when the sequence state was last recorded in WAL.
On the subscriber, inspect the subscription's sequence synchronization information:
SELECT
srrelid::regclass AS sequence_name,
srsublsn
FROM pg_subscription_rel;
The srsublsn column records the sequence synchronization LSN for the subscription.
PostgreSQL documentation describes comparing this value with the page_lsn returned by pg_get_sequence_data() on the publisher to identify sequence states that need refreshing.
There is an important limitation: PostgreSQL sequences typically cache a block of values in memory before generating another WAL record. The default cache is commonly 32 values. Consequently, the sequence page LSN might not advance after every nextval call.
This means an LSN comparison cannot detect every small sequence-value difference. Do not treat matching LSN values as proof that every generated value is identical.
Integrate Sequence Synchronization Into a .NET Application
A .NET application can manage subscription refresh operations using Npgsql.
For example, an administrative service can execute REFRESH SEQUENCES when a maintenance workflow or database migration requires synchronization.
Install the Npgsql package if it is not already part of the application:
dotnet add package Npgsql
Create a service that connects to the subscriber:
using Npgsql;
public sealed class SequenceReplicationService
{
private readonly NpgsqlDataSource _subscriberDataSource;
public SequenceReplicationService(
NpgsqlDataSource subscriberDataSource)
{
_subscriberDataSource = subscriberDataSource;
}
public async Task RefreshSequencesAsync(
CancellationToken cancellationToken)
{
await using var connection =
await _subscriberDataSource.OpenConnectionAsync(
cancellationToken);
const string sql = """
ALTER SUBSCRIPTION
orders_sequence_subscription
REFRESH SEQUENCES;
""";
await using var command =
new NpgsqlCommand(sql, connection);
command.CommandTimeout = 60;
await command.ExecuteNonQueryAsync(
cancellationToken);
}
}
This service connects to the subscriber and executes the sequence refresh command.
The subscription name is a SQL identifier, not a normal query parameter. In this example, it is a fixed application configuration value. If the subscription name must be configurable, validate and safely quote the identifier before building the SQL command.
The database user must have the required privileges to manage the subscription. Subscription management should normally be restricted to an administrative service rather than exposed through a public application endpoint.
You can register the subscriber data source through dependency injection:
builder.Services.AddSingleton<NpgsqlDataSource>(sp =>
{
var configuration =
sp.GetRequiredService<IConfiguration>();
var connectionString =
configuration.GetConnectionString("Subscriber");
return NpgsqlDataSource.Create(connectionString!);
});
For an application that also connects to the publisher, use separate data sources and configuration entries. This keeps database responsibilities clear and prevents accidental execution of subscription-management commands against the wrong server.
A sequence refresh should generally be part of a controlled operational workflow. It is not something that needs to run after every application INSERT.
Advantages and Limitations
PostgreSQL 19 sequence replication provides several practical benefits.
Area | Advantage |
|---|
Database migration | Reduces manual sequence synchronization work |
Failover preparation | Helps update sequence state before a subscriber becomes writable |
Logical replication | Supports publishing sequence objects alongside replicated data |
Administration | Provides a standard refresh operation |
Monitoring | Offers sequence synchronization information through database functions and catalog views |
However, developers should understand its limitations.
Sequence synchronization requires PostgreSQL 19 or later on the publisher. It does not remove the need to manage schema definitions separately. Sequence definitions must match, and the subscriber's sequence state can become outdated as the publisher continues generating values.
Logical replication also does not automatically make a subscriber safe for simultaneous writes. If multiple database servers generate identifiers independently, the application needs an appropriate identifier strategy, such as separate sequence ranges or globally unique identifiers.
Best Practices for Production Applications
Use PostgreSQL 19 sequence replication when logical replication workflows require sequence state to be synchronized between publisher and subscriber.
Keep table and sequence publication requirements clear. Verify that the subscriber contains compatible sequence definitions before starting synchronization.
Before a planned switchover, refresh the sequences and verify that the synchronization operation has completed. Do not assume that a subscriber's sequence values are current simply because its table data is up to date.
Monitor sequence synchronization status and replication health. Remember that sequence caching can delay WAL position changes, so LSN comparisons should not be treated as an exact per-value comparison.
Finally, do not use a subscriber as a writable database until the failover process has addressed sequence state, application routing, replication conflicts, and other operational requirements.
Summary
PostgreSQL 19 introduces logical replication support for sequence values, addressing an important limitation in publisher-subscriber database architectures.
Developers can publish all sequences using FOR ALL SEQUENCES, initialize sequence state when creating a subscription, and synchronize newly added or existing sequences using REFRESH PUBLICATION and REFRESH SEQUENCES.
For .NET applications, Npgsql provides a straightforward way to execute these administrative operations as part of controlled database maintenance and migration workflows.
The important point is that sequence synchronization is not continuous replication of every nextval operation. Sequence values can become outdated as the publisher advances, so applications and database administrators must refresh and verify sequence state before operations such as failover or switchover.
Join the conversation! Your thoughts help the community grow.