Many applications use PostgreSQL primary and standby servers to distribute database workloads. The primary server handles write operations, while one or more standby servers handle read-only queries. This architecture can improve read scalability and reduce the workload on the primary database.
However, asynchronous replication introduces a consistency challenge. When an application writes data to the primary and immediately reads the same data from a standby, the latest changes might not yet be available.
For example, a user updates their profile and then opens the profile page. The application successfully saves the changes, but the next request reads from a standby that has not replayed the corresponding WAL records. The user sees the old profile information.
PostgreSQL 19 introduces a new WAIT command that helps address this problem. Applications can wait until a standby has replayed changes up to a specific Write-Ahead Log (WAL) position before executing a read query.
In this article, we will explore how read-your-writes consistency works, how PostgreSQL 19's WAIT FOR LSN command helps, and how to implement this behavior in a .NET application using Npgsql.
Understanding Read-Your-Writes Consistency
Read-your-writes consistency means that after a user successfully writes data, subsequent reads by that user should reflect the committed changes.
Consider an application with two database servers:
Primary: Handles INSERT, UPDATE, and DELETE operations.
Standby: Handles read-only queries.
The application performs an update on the primary:
UPDATE customers
SET email = '[email protected]'
WHERE customer_id = 1001;The transaction commits successfully. The application then executes a SELECT query against the standby:
SELECT
customer_id,
email
FROM customers
WHERE customer_id = 1001;The problem is that PostgreSQL streaming replication is asynchronous by default. The primary sends WAL records to the standby, which replays them independently.
There can be a short period between the primary committing a transaction and the standby making the changes visible to queries.
During this period, the SELECT statement might return the previous email address.
This is called a replication consistency problem. It does not necessarily indicate that replication is broken. The standby may simply be processing the incoming WAL records.
PostgreSQL 19 provides a mechanism to wait for a specific replication position before reading from the standby.
How PostgreSQL 19 WAIT FOR LSN Works
PostgreSQL 19 introduces the WAIT command for synchronizing reads with WAL replay progress.
The application follows three important steps:
Commit the write transaction on the primary.
Retrieve a WAL Log Sequence Number (LSN) from the primary.
Send that LSN to the standby and wait until it has replayed the corresponding WAL records.
An LSN represents a position in the PostgreSQL write-ahead log. It helps identify how far database changes have progressed through the WAL stream.
For example, an LSN might look like this:
0/306EE20After the primary commits a transaction, the application can retrieve a WAL position:
SELECT pg_current_wal_insert_lsn();The application then connects to the standby and executes:
WAIT FOR LSN '0/306EE20';The standby waits until its WAL replay position reaches or passes the requested LSN.
When the command returns success, PostgreSQL guarantees that all changes up to that WAL position have been applied. Subsequent queries can therefore see the committed changes associated with that position.
This approach provides read-your-writes consistency without requiring every transaction to use synchronous replication. <Cite refs={["turn403695search3","turn403695search0"]} />
Configure the PostgreSQL Primary and Standby
Before implementing the .NET integration, configure PostgreSQL streaming replication.
The primary and standby servers must already be connected through a supported replication configuration.
On the primary, verify the current WAL level:
SHOW wal_level;For physical streaming replication, the standard configuration uses replica:
wal_level = replica
max_wal_senders = 10
max_replication_slots = 10The actual values should depend on the number of standby servers and other replication consumers.
The standby must be configured with the primary connection information and appropriate authentication.
You can check connected replication servers on the primary:
SELECT
application_name,
state,
sync_state,
sent_lsn,
write_lsn,
flush_lsn,
replay_lsn
FROM pg_stat_replication;The replay_lsn column indicates how far the standby has replayed WAL records.
On the standby, you can inspect its recovery status:
SELECT
pg_is_in_recovery() AS is_standby,
pg_last_wal_receive_lsn() AS received_lsn,
pg_last_wal_replay_lsn() AS replayed_lsn;The is_standby value should be true for a physical standby operating in recovery mode.
PostgreSQL 19's WAIT command is intended for a standby session. It synchronizes that session with the specified WAL position rather than changing the replication configuration itself.
Implement Read-Your-Writes in a .NET Application
A .NET application can implement this behavior using Npgsql, the PostgreSQL data provider for .NET.
The application needs two database connections:
A primary connection for write operations and retrieving the WAL position.
A standby connection for waiting and executing subsequent reads.
Do not assume that a connection pool automatically routes queries to the correct server. Configure separate connection strings or data sources for the primary and standby.
For example, application settings might contain:
{
"ConnectionStrings": {
"Primary": "Host=primary-db;Database=appdb;Username=appuser;Password=secret",
"Standby": "Host=standby-db;Database=appdb;Username=appuser;Password=secret"
}
}Use a secret store or environment-specific configuration for production credentials instead of committing passwords to source control.
Create a Service for Database Connections
Register separate NpgsqlDataSource instances:
builder.Services.AddSingleton<NpgsqlDataSource>(sp =>
{
var configuration = sp.GetRequiredService<IConfiguration>();
var connectionString =
configuration.GetConnectionString("Primary");
return NpgsqlDataSource.Create(connectionString!);
});
builder.Services.AddSingleton<StandbyDataSource>(sp =>
{
var configuration = sp.GetRequiredService<IConfiguration>();
var connectionString =
configuration.GetConnectionString("Standby");
return new StandbyDataSource(connectionString!);
});Define a small wrapper for the standby data source:
public sealed class StandbyDataSource : IAsyncDisposable
{
public NpgsqlDataSource DataSource { get; }
public StandbyDataSource(string connectionString)
{
DataSource = NpgsqlDataSource.Create(connectionString);
}
public ValueTask DisposeAsync()
{
return DataSource.DisposeAsync();
}
}In this example, the primary data source is registered directly, while the standby data source uses a wrapper to make its role explicit.
A production application can also define dedicated interfaces and database connection services to keep routing decisions separate from business logic.
Write Data and Retrieve the WAL Position
The application should first commit its transaction on the primary.
After the commit succeeds, it can retrieve the current WAL insertion position:
public async Task<string> UpdateCustomerAsync(
int customerId,
string email,
NpgsqlDataSource primaryDataSource,
CancellationToken cancellationToken)
{
await using var connection =
await primaryDataSource.OpenConnectionAsync(
cancellationToken);
await using (var transaction =
await connection.BeginTransactionAsync(
cancellationToken))
{
await using var command = new NpgsqlCommand(
"""
UPDATE customers
SET email = @email
WHERE customer_id = @customerId;
""",
connection,
transaction);
command.Parameters.AddWithValue("email", email);
command.Parameters.AddWithValue("customerId", customerId);
var affectedRows = await command.ExecuteNonQueryAsync(
cancellationToken);
if (affectedRows != 1)
{
throw new InvalidOperationException(
"Customer was not found or was not updated.");
}
await transaction.CommitAsync(cancellationToken);
}
await using var lsnCommand = new NpgsqlCommand(
"SELECT pg_current_wal_insert_lsn()::text",
connection);
var lsn = (string?)await lsnCommand.ExecuteScalarAsync(
cancellationToken);
return lsn ?? throw new InvalidOperationException(
"Could not retrieve the WAL position.");
}There is an important detail here. The WAL position is retrieved after the transaction has committed.
This ensures that the returned position is obtained after the commit record has been generated. It may include additional WAL activity from other transactions, which is acceptable because the standby must replay at least up to that position.
The method returns the LSN as a string so that the application can pass it to the standby-reading component.
Join the conversation! Your thoughts help the community grow.