PostgreSQL replication is commonly used to distribute database workloads across multiple servers. An application sends INSERT, UPDATE, and DELETE operations to the primary database, while read-only queries can be distributed to one or more standby servers. This arrangement reduces the workload on the primary and improves the ability to handle large numbers of read requests.
However, replication introduces a consistency challenge. When an application saves a record on the primary and immediately reads that record from a standby, the latest change may not yet be available. The standby might still be replaying earlier write-ahead log records.
For example, imagine an e-commerce application where a customer updates their delivery address. The API successfully saves the new address on the primary database. The application then loads the customer's profile from a standby server. If replication has not caught up, the response may contain the previous address.
This behavior is known as a read-after-write consistency problem. PostgreSQL 19 provides a WAIT FOR LSN command that helps applications address this situation without requiring every read to go to the primary.
This article explains how replication lag affects .NET applications, how to use PostgreSQL 19 to wait for a standby to replay a particular write, and how to implement the approach with Npgsql.
Understanding Read-After-Write Consistency
In a typical PostgreSQL streaming replication setup, the primary database records changes in its write-ahead log (WAL). The standby receives these WAL records and replays them to update its own database.
The process happens continuously, but it is not necessarily instantaneous.
Consider the following application workflow:
- A user updates their profile through an API.
- The API writes the updated profile to the primary database.
- PostgreSQL commits the transaction.
- The API sends a response indicating that the update succeeded.
- The client requests the updated profile.
- The application routes the read request to a standby.
- The standby has not yet replayed the transaction.
The final query may return outdated information even though the update was successfully committed.
<text color="secondary" size="sm">Conceptual replication flow</text>
.NET Application
|
| UPDATE customer
v
PostgreSQL Primary
|
| Commit transaction
| Generate WAL records
v
WAL Streaming
|
v
PostgreSQL Standby
|
| Replay WAL records
v
Updated data becomes visible
The important distinction is that receiving WAL records and replaying them are different operations. A standby may have received a transaction's WAL records without having applied them to its database yet.
For read-after-write consistency, the application needs to know when the standby has replayed the WAL records associated with its own transaction.
Understanding Log Sequence Numbers
PostgreSQL uses Log Sequence Numbers (LSNs) to identify positions in the write-ahead log.
An LSN represents a location in the WAL stream. As PostgreSQL generates WAL records, the current LSN advances.
For example, an LSN may look like this:
0/306EE20
The primary and standby expose functions that help applications track WAL progress.
| PostgreSQL function | Purpose |
|---|
| pg_current_wal_insert_lsn() | Returns the current WAL insertion position on the primary |
| pg_current_wal_lsn() | Returns the current WAL write position on the primary |
| pg_last_wal_receive_lsn() | Returns the last WAL position received and flushed on the standby |
| pg_last_wal_replay_lsn() | Returns the last WAL position replayed on the standby |
For read-after-write consistency, the application needs a target LSN that is at or after the commit record of the transaction it wants to read.
After the write transaction commits, the application can retrieve a suitable WAL position from the primary.
SELECT pg_current_wal_insert_lsn();
The returned LSN becomes the synchronization point for the subsequent read.
The application passes this position to the standby and waits until its replay position reaches the target.
Using PostgreSQL 19 WAIT FOR LSN
PostgreSQL 19 introduces the WAIT command, which allows a database session to wait until a specified LSN reaches a particular processing state.
For read-after-write consistency, the most important mode is standby_replay.
WAIT FOR LSN '0/306EE20'
WITH
(
MODE 'standby_replay',
TIMEOUT '2s'
);
This command waits until the standby has replayed the specified WAL position.
When the target LSN has been replayed, the command returns successfully. The application can then execute its SELECT query against the standby, knowing that the standby has processed WAL records through the required position.
The WAIT command supports several modes:
| Mode | Meaning |
|---|
| standby_replay | Wait until WAL is replayed and changes become visible to queries |
| standby_write | Wait until WAL has been written to the standby's operating system |
| standby_flush | Wait until WAL has been flushed to durable storage on the standby |
| primary_flush | Wait until WAL has been flushed on the primary |
For read-after-write consistency, standby_replay is generally the appropriate choice. Waiting only for standby_write or standby_flush does not necessarily mean that the changes are already visible to ordinary queries.
The timeout is also important. An application should not wait indefinitely if a standby becomes unavailable or falls significantly behind.
PostgreSQL 19 also supports NO_THROW. With this option, the command can return a status such as success, timeout, or not in recovery instead of raising an error for these outcomes.
WAIT FOR LSN '0/306EE20'
WITH
(
MODE 'standby_replay',
TIMEOUT '2s',
NO_THROW
);
This allows the application to make an explicit routing decision when the standby cannot catch up within the configured time.
Implementing Read-After-Write Consistency With Npgsql
Npgsql provides the database connectivity required to implement this workflow in a .NET application.
The implementation needs two data sources:
- A primary data source for INSERT, UPDATE, and DELETE operations.
- A standby data source for read-only queries.
Both data sources should be configured with the appropriate connection details and registered for reuse.
using Npgsql;
var primaryDataSource =
NpgsqlDataSource.Create(
builder.Configuration.GetConnectionString("Primary")!);
var standbyDataSource =
NpgsqlDataSource.Create(
builder.Configuration.GetConnectionString("Standby")!);
builder.Services.AddSingleton(primaryDataSource);
builder.Services.AddSingleton(standbyDataSource);
For production applications, dispose of the data sources during application shutdown through dependency injection. They should not be created separately for every request.
Step 1: Update the Record on the Primary
Consider a customer table.
CREATE TABLE customers
(
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer_name VARCHAR(200) NOT NULL,
email VARCHAR(200) NOT NULL,
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
The repository first updates the customer on the primary and commits the transaction.
public class CustomerRepository
{
private readonly NpgsqlDataSource _primaryDataSource;
private readonly NpgsqlDataSource _standbyDataSource;
public CustomerRepository(
NpgsqlDataSource primaryDataSource,
NpgsqlDataSource standbyDataSource)
{
_primaryDataSource = primaryDataSource;
_standbyDataSource = standbyDataSource;
}
public async Task UpdateCustomerAsync(
long customerId,
string customerName,
string email,
CancellationToken cancellationToken = default)
{
const string sql = """
UPDATE customers
SET
customer_name = @customerName,
email = @email,
updated_at = NOW()
WHERE id = @customerId;
""";
await using var connection =
await _primaryDataSource.OpenConnectionAsync(
cancellationToken);
await using var command =
new NpgsqlCommand(sql, connection);
command.Parameters.AddWithValue(
"customerId",
customerId);
command.Parameters.AddWithValue(
"customerName",
customerName);
command.Parameters.AddWithValue(
"email",
email);
await command.ExecuteNonQueryAsync(cancellationToken);
}
}
The command runs in its own implicit transaction because no explicit transaction has been started. Once ExecuteNonQueryAsync completes successfully, the statement has committed.
If the application uses an explicit transaction, it must commit the transaction before capturing the synchronization LSN.
Step 2: Capture the WAL Position After the Commit
After the update completes, retrieve the current WAL insertion position from the primary.
private async Task<string> GetCurrentWalLsnAsync(
CancellationToken cancellationToken)
{
const string sql = """
SELECT pg_current_wal_insert_lsn()::text;
""";
await using var connection =
await _primaryDataSource.OpenConnectionAsync(
cancellationToken);
await using var command =
new NpgsqlCommand(sql, connection);
return (string?)await command.ExecuteScalarAsync(
cancellationToken)
?? throw new InvalidOperationException(
"Could not retrieve the WAL position.");
}
Capturing the position after the transaction commits is important. The target must include the commit record of the transaction whose changes the application wants to read.
If the application captures an LSN before committing, the captured position may not include the transaction's commit record.
Step 3: Wait for the Standby to Replay the LSN
The application now needs to wait until the standby reaches the captured position.
private async Task WaitForStandbyAsync(
string targetLsn,
CancellationToken cancellationToken)
{
if (!System.Text.RegularExpressions.Regex.IsMatch(
targetLsn,
@"\A[0-9A-Fa-f]+/[0-9A-Fa-f]+\z"))
{
throw new ArgumentException(
"Invalid WAL position.",
nameof(targetLsn));
}
string sql = $"""
WAIT FOR LSN '{targetLsn}'
WITH
(
MODE 'standby_replay',
TIMEOUT '2s',
NO_THROW
);
""";
await using var connection =
await _standbyDataSource.OpenConnectionAsync(
cancellationToken);
await using var command =
new NpgsqlCommand(sql, connection);
string? status = (string?)await command.ExecuteScalarAsync(
cancellationToken);
if (!string.Equals(
status,
"success",
StringComparison.OrdinalIgnoreCase))
{
throw new TimeoutException(
$"Standby did not reach the required WAL position. Status: {status}");
}
}
The LSN comes directly from PostgreSQL and is validated before being inserted into the WAIT statement. This is important because the WAIT command's LSN is part of its SQL syntax rather than an ordinary query value.
The example uses a two-second timeout to demonstrate bounded waiting. The actual timeout should be selected according to the application's latency requirements and replication behavior.
If the standby cannot reach the target within that period, the application should not silently continue with an ordinary read when the caller requires read-after-write consistency.
Step 4: Read the Updated Record From the Standby
After the wait completes successfully, the application can execute its read query.
public async Task<Customer?> GetCustomerFromStandbyAsync(
long customerId,
CancellationToken cancellationToken = default)
{
const string sql = """
SELECT
id,
customer_name,
email,
updated_at
FROM customers
WHERE id = @customerId;
""";
await using var connection =
await _standbyDataSource.OpenConnectionAsync(
cancellationToken);
await using var command =
new NpgsqlCommand(sql, connection);
command.Parameters.AddWithValue(
"customerId",
customerId);
await using var reader =
await command.ExecuteReaderAsync(cancellationToken);
if (!await reader.ReadAsync(cancellationToken))
{
return null;
}
return new Customer
{
Id = reader.GetInt64(0),
CustomerName = reader.GetString(1),
Email = reader.GetString(2),
UpdatedAt = reader.GetFieldValue<DateTimeOffset>(3)
};
}
The standby has already replayed the required WAL position, so the query can see the committed update.
The complete workflow is now:
Update customer on primary
|
v
Commit transaction
|
v
Capture target WAL LSN
|
v
Connect to standby
|
v
WAIT FOR LSN
|
v
Standby replays target WAL
|
v
Read updated customer
Combining the Workflow Into One Repository Method
The previous examples separate the operations to make the sequence clear. In a real application, the repository can expose one method that performs the complete workflow.
public async Task<Customer?> UpdateAndReadAsync(
long customerId,
string customerName,
string email,
CancellationToken cancellationToken = default)
{
await UpdateCustomerAsync(
customerId,
customerName,
email,
cancellationToken);
string targetLsn = await GetCurrentWalLsnAsync(
cancellationToken);
await WaitForStandbyAsync(
targetLsn,
cancellationToken);
return await GetCustomerFromStandbyAsync(
customerId,
cancellationToken);
}
This method makes the consistency requirement explicit. The application does not read from the standby until the required WAL position has been replayed.
In a production implementation, the repository should also define how it handles timeouts, standby failover, connection failures, and cancellation.
Handling Timeouts and Standby Failures
A standby may not reach the target LSN within the configured timeout. This can happen because of network delays, heavy write activity on the primary, slow storage, long-running queries on the standby, or a replication interruption.
The application should define a fallback strategy based on its consistency requirements.
| Situation | Recommended behavior |
|---|
| Standby reaches the target | Read from the standby |
| Standby times out | Route the read to the primary if strong consistency is required |
| Standby connection fails | Retry another suitable standby or use the primary |
| Standby is promoted during the wait | Re-evaluate the connection role and retry through an appropriate server |
| Client cancels the request | Stop waiting and propagate cancellation |
For example, a customer profile page may require the latest saved information immediately after an update. If the standby cannot catch up, reading from the primary is a reasonable fallback.
For analytics or reporting screens, slightly outdated information may be acceptable. In that case, the application may continue reading from the standby without waiting.
The fallback must be a deliberate business decision. It should not happen accidentally because an exception was ignored.
An Alternative for PostgreSQL Versions Without WAIT FOR LSN
Applications running older PostgreSQL versions can implement similar behavior by checking the standby's replay position.
On the standby, execute:
SELECT pg_last_wal_replay_lsn();
The application compares the returned value with the target LSN.
PostgreSQL provides the pg_lsn type for comparing WAL positions, so the comparison should happen inside PostgreSQL rather than through string comparison in C#.
SELECT
pg_last_wal_replay_lsn() >= @targetLsn::pg_lsn;
The application can repeat this query with a short delay until the result becomes true or a timeout is reached.
For example, the application may poll every 50 milliseconds with an overall timeout of two seconds.
This approach works, but it requires repeated database queries and application-side timeout management. PostgreSQL 19's WAIT command provides a more direct way to express the requirement.
Understanding the Performance Trade-Off
Waiting for a standby to replay a particular WAL position improves consistency, but it adds latency to the read workflow.
The additional time depends on replication lag and the workload running on the standby.
For example, if the standby has already replayed the target position, WAIT can complete quickly. If it is behind, the application must wait until the required WAL records are processed.
This approach is not intended for every read request. Applying it to all queries can reduce the performance benefit of read replicas.
A practical strategy is to use consistency-aware routing:
- Send all writes to the primary.
- Send ordinary read-only queries to a standby.
- Use the LSN synchronization workflow for reads that must immediately reflect a preceding write.
- Route to the primary when the standby cannot meet the required consistency deadline.
This gives the application a balance between read scalability and predictable user experience.
Common Mistakes to Avoid
One common mistake is capturing the target LSN before committing the transaction. The application must capture a position at or after the relevant commit record.
Another mistake is checking the standby's received WAL position instead of its replay position. Receiving WAL does not guarantee that the changes are visible to queries.
Developers should also avoid comparing LSN values as ordinary strings. LSNs represent positions, not text values, so PostgreSQL's pg_lsn comparison operators should be used.
Do not assume that every standby is always available or that every wait will complete within a fixed duration. Replication lag can increase during heavy workloads, and a standby can be disconnected or promoted.
Finally, do not use the synchronization mechanism when stale reads are acceptable. Waiting adds latency and should be reserved for operations that genuinely require read-after-write consistency.
Summary
Reading from PostgreSQL standbys helps .NET applications distribute database workloads, but asynchronous replication can cause a read-after-write consistency problem. A transaction may be committed on the primary while its changes are still waiting to be replayed on the standby.
PostgreSQL 19 provides WAIT FOR LSN, allowing applications to wait until a standby has replayed a specific WAL position. By capturing an LSN after committing a transaction and waiting for standby_replay before executing a read query, an application can ensure that the standby has processed the relevant write.
Npgsql makes it possible to implement this workflow using separate primary and standby data sources. The application should also handle timeouts, cancellation, connection failures, and fallback routing.
The most effective design is not to wait for every read. Instead, use LSN-based synchronization only when the application needs to guarantee that a user's latest write is visible, while allowing ordinary read operations to benefit from replica-based load distribution.
Join the conversation! Your thoughts help the community grow.