Skip to content

[connectors] Retry a Postgres batch on a read-only session - #8026

Merged
bestouff merged 1 commit into
issue-8014from
issue-8014-readonly
Nov 27, 2026
Merged

bestouff merged 1 commit into
issue-8014from
issue-8014-readonly

Conversation

@bestouff

@bestouff bestouff commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Linked Issue

Related to #8014. Stacked on #8017. #8098, stacked on this PR, removes the limit of 10 attempts. This PR covers a failure of the same kind that #8017 does not handle: a session that stays open on a server that cannot write.

What changes

After a failover, a connection pooler can hold a session on the old primary, which is then a read-only replica. The server rejects each write with SQLSTATE 25006 and the session stays open. With #8017, the connector classifies this error as permanent and drops the batch. It also drops each later batch for as long as the session stays open.

Area With #8017 With this PR
Error class of a statement error on an open session Temporary for class 08 and for 57P01, 57P02, 57P03 Also temporary for 25006, 55P03 (lock not available) and for the classes 40 (serialization failure, deadlock), 53 (insufficient resources), 57 (all of the class, which adds a cancelled statement), 58 (system error), XX (internal error)
Connection for a new attempt The worker keeps a session that passes a validity check. A read-only session passes it The worker opens a new connection for each new attempt. It closes the old session first, because the old session can hold the only connection slot of the role
Wait between the attempts on one batch None when the session stays open The second attempt starts at once. Each later attempt waits 1 second more: 36 seconds in total for the 10 attempts
Prepare that fails on a new session that stays open Permanent: the batch is dropped at once Uses one of the 10 attempts. The wait with no limit stays for a server or a pooler that is not available: a failed login (any severity), and a connection error (class 08) also with severity ERROR, which PgBouncer before 1.16 sends before it closes the session
New client and prepared statements A failed prepare left the new client with the statements of the old session (#8019) The worker keeps a new client only together with its statements. Not tested separately
Error for a batch that the worker gives up on "the connection dropped, or the transaction did not start" States the error that lost the transaction

A statement that the server rejects for its rows (a constraint, a type, a permission) stays permanent.

The statement and its rows usually do not cause the errors that are now temporary, but some of them come back each time: a statement that is always slower than the statement timeout, a role that is configured as read-only, an internal error that a trigger raises. The cost is at most 10 attempts, which can take 10 times the statement timeout. This cost must be examined again if the number of attempts becomes unbounded.

Not changed:

Describe Manual Test Plan

No manual test with a real failover. The suite cases use the TCP proxy of #8017, which now can answer a statement as a server does that cannot run it (ERROR, session left open).

I ran the outage test of #8017 again on this tree: PgBouncer 1.26.1 (transaction pooling) in front of PostgreSQL 15, PostgreSQL stopped while a batch of 3000 rows was pending, then started again. Result: 3000 of 3000 rows, no fatal error, one pg_batch_start error and 6 pg_conn_retry errors while the server was down.

Test Result
6 classifier unit tests (2 new), 1 unit test for the wait before each attempt Pass
Suite case: one session is read-only, a new session can write Pass. The proxy sees exactly 1 rejected statement
Suite case: the same with a role that has one connection slot Pass
Suite case: each session is read-only for the first 4 attempts Pass. The 4 attempts take 3 seconds or more
Suite case: the server cancels each statement and each prepare (57014) Pass. The connector gives up after 10 attempts and the error has the cause of the last attempt (the prepare)
Suite case: a pooler that sends ERROR 08P01 at the transaction start and at 9 prepares, then recovers Pass, no batch dropped (about 45 s of waits)
Suite case: a crash, then 9 logins refused with ERROR 53300 Pass, no batch dropped (about 45 s of waits)
Revert check: classifier change removed The 2 new unit tests and the 3 read-only suite cases fail
Revert check: validity check restored (no new connection) The 2 cases with one read-only session fail
Revert check: login before the old session is closed The case with one connection slot fails
Revert check: wait removed The wait case and the unit test fail
Revert check: a failed prepare does not use an attempt The 57014 case fails (it does not end)
Revert check: a failed login counts as an attempt The refused login case fails (rows lost). Checked on #8098, where the case allows one new attempt
Revert check: class 08 with severity ERROR keeps the session open The ERROR 08P01 case fails (rows lost). Checked on #8098
4 proxy suite cases of #8017 Pass
Postgres output suite (not TLS, not the CDC input cases), local PostgreSQL 15 33 of 33 pass, on the tree of #8098 (which contains this PR). The 4 changed proxy cases pass on this branch

Checklist

  • Unit tests added/updated
  • Integration tests added/updated
  • Documentation updated
  • Changelog updated

Breaking Changes?

None. The connector now writes a batch again in more cases where it dropped the batch before. A retry of a batch that used an open session now opens a new connection.

// for example because of a lock on the table. A wait here
// for the server to come back has no end, so the failure
// counts as an attempt to write the batch.
if server_answered {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

pitfall (medium): server_answered is computed for errors from connect() too, not only from PreparedStatements::new. Any startup-phase ErrorResponse ends the connection, whatever its severity. But session_stays_open() only treats it as ended when the severity is FATAL/PANIC. PgBouncer before roughly 1.19 always sent ERROR severity (send_pooler_error), and so do some other poolers. That covers 08P01 server login has been failing, try again later and no more connections allowed. With those poolers, the "server/pooler not available" case now uses the 10 attempts (about 36 s) and drops the batch, where it used to wait with no limit. The PgBouncer 1.26.1 manual run doesn't exercise this. Suggest returning Reconnect::Failed only for a prepare failure (e.g. tag it in retry_connecting), and keeping every connect() error on the unbounded backoff path.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch, fixed: only a failed prepare can use an attempt now, a failed login always waits with no limit. A class 08 error also counts as the end of the session whatever its severity, for the old PgBouncer that sends ERROR and closes the session at the first statement. Small correction: PgBouncer switched to FATAL in 1.16, not 1.19. Two new suite cases, one for each (refused login with ERROR 53300, and ERROR 08P01 at the prepare).

@mythical-fred-oss

Copy link
Copy Markdown
Contributor

Review: Postgres sink retries on read-only and server-side errors

What I ran Result
cargo test -p dbsp_connectors --lib for postgres::error and write_attempts_wait_longer_each_time 7/7 pass
cargo test -p dbsp_connectors --lib postgres 115 pass. The 7 failures need a live Postgres, which this runner doesn't have. That includes the 4 new suite cases, so I could not run them.
pre-commit run --files <changed> Pass (clippy, fmt, machete, docs)

Gates: tests ✅ (unit tests plus suite cases with revert checks), docs and changelog ✅, SAFETY comment still holds with Option<Client> ✅, no new deps. The new timing assertion only checks a lower bound with 1 thread, so it should not be flaky ✅.

  • pitfall (medium): a login error with ERROR severity from a pooler uses up batch attempts. See the inline comment.
  • missing (medium), cases not covered by tests:
    1. A pooler that refuses login with an ERROR-severity 08P01. The worker should keep waiting and not drop the batch. The proxy can't fake this today, because faults start after login.
    2. A Reconnect::Failed on the last attempt. The final error should give the prepare error as the cause; the 57014 case covers this only through the bind path.
    3. A read-only (25006) error on COMMIT in CDC mode, which is where duplicate rows are possible.

@bestouff
bestouff requested a review from gz November 20, 2026 13:09
/// [`PostgresWorker::retry_connecting_with_backoff`], and is not bounded.
///
/// The second attempt starts at once. Each later attempt waits one second
/// longer than the one before it, so the waits add up to 36 seconds. See

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what's the total wait time?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Other output connectors have the max_retries setting. We need the same option here, and we need to make sure it has the same behavior and the same defaults across all connectors. Today the default behavior is not consistent: delta retries forever by default, while dynamodb defaults to 10 retries. I think the delta default is better. I will create a separate issues to unify the max_retries behavior.

    /// Maximum number of retries for failed operations.
    ///
    /// <skipped delta-specific details>
    ///
    /// When not specified, the connector performs infinite retries. When set to 0, the connector doesn't
    /// retry failed operations.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_retries: Option<u32>,

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

36 s of waits for the 10 attempts (0, 0, 1 to 8 s), plus the time of each attempt. The wait for a server that doesn't answer isn't in it, and has no limit. Your chaos test agrees: the loss starts after about 36 s of rejected writes. With #8098 there's no limit by default, and the wait grows to 60 s max.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, done in #8098: max_retries with the Delta semantics (not set = no limit, the default; 0 = no retry), plus unhealthy/healthy reports while it retries.

// pooler can limit the connections of the role, and the old session
// then holds the slot that the new one needs.
self.client = None;
let mut client = connect(&self.config, &self.endpoint_name)?;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

how does this interact with other open connections? do they all end up making a new client?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No. Each worker thread owns its client, there's no shared pool. A worker makes a new client only before a new attempt on its own part of a batch; a worker whose part committed keeps its session. In a failover each worker fails its own write, so each one connects again, and as each closes its old session first, we never have more than threads connections.

@gz

gz commented Nov 20, 2026

Copy link
Copy Markdown
Contributor

Chaos test of #8017, #8018 and #8026 on Kubernetes

We ran the three PRs merged together (#8017 at 82708ab, #8018 at d4a286d, #8026 at aa3d756, no merge conflicts) against faults in PostgreSQL and PgBouncer, and ran the same faults against v0.385.0, which is the merge base.

Result: with the PRs, no run lost data without a report. 41 of 44 runs lost nothing. The 3 other runs had a server that rejected writes for 75 s, longer than the 10 attempts of the connector. The connector dropped 2 batches in each of them, and the completion tokens of exactly those batches returned OutputNotDelivered. v0.385.0 lost data in 17 of 41 runs, and each token said complete.

Build Runs No loss Loss that the tokens reported Loss with no report
v0.385.0 41 24 0 17
PRs merged 44 41 3 0

Setup

            HTTP ingress               postgres_output connectors (materialized mode)
driver ------------------> pipeline --+-- 1 thread  --> PgBouncer --+--> Service --> primary  (hot standby in the failover scenarios)
   |                                  +-- 4 threads --> PgBouncer --+
   |                                  +-- 2 threads -----------------------------> primary --streaming replication--> hot standby
   +-- injects the fault, then reads each sink table on the primary
Part Setup
Platform Kubernetes. Feldera from the helm chart, one pipeline with 4 workers
PostgreSQL 15. Primary with a persistent volume, and a hot standby with streaming replication
PgBouncer 1.26.1, pool_mode = transaction, max_prepared_statements = 200, other settings at their defaults
Fault injection chaos-mesh 2.8.8 (PodChaos, NetworkChaos), the PgBouncer admin console, SQL on the primary, and a Kubernetes Service that moves the server of PgBouncer from the primary to the standby
Pipeline One table and three views. Each view has one postgres_output connector to its own sink table with a primary key
Workload 4 ingress requests per second for the time of the fault plus 16 s. Each request has 1,500 row changes: new keys, updates and deletes of older keys. The tiny scenarios use 3 row changes, so most worker threads get no rows of a batch

Check

The driver keeps the completion token and the changed keys of each ingress request, and the rows that each sink table must have at the end. After the fault ends, it asks for the status of each token and reads each sink table on the primary.

Verdict Condition
No loss Each token is complete and each sink table has exactly the expected rows
Reported loss Each key that is missing, extra or stale in a sink table is in a request whose token returned OutputNotDelivered
Loss with no report A key differs and no token reported it

Each run also sends a small batch before and after the scenario and checks that it reaches each sink, so a connector that stays broken after a fault fails the run. This did not occur.

Scenarios

The numbers are the keys that differ from the expected rows in the worst sink table. The error column is from the pipeline log and the PgBouncer log of the run with the PRs.

# Scenario Fault Errors that the connector got v0.385.0 PRs merged
1 no_fault None None 0 0
2 pgb_pod_kill Kill the PgBouncer pod with no grace period. A new pod starts Connection closed 0 0
3 pgb_pod_failure_30s PgBouncer pod not available for 30 s Connection closed, then connect errors 0 0
4 pgb_kill_resume Admin KILL of the database, RESUME after 10 s 08P01 database removed 722 0
5 pgb_pause_query_wait_timeout Admin PAUSE for 15 s with query_wait_timeout = 3 08P01 query_wait_timeout 607 0
6 pgb_reconnect Admin RECONNECT each 2 s for 12 s None 0 0
7 pgb_query_timeout query_timeout = 2 for 8 s, while a trigger makes each INSERT statement take 4 s 08P01 query timeout. 55P03 while the test switches the trigger 3,303 0
8 pgb_idle_transaction_timeout idle_transaction_timeout = 1 and 1.2 s of network latency between the pipeline and PgBouncer, for 20 s 08P01 idle transaction timeout 0 0
9 pgb_net_partition_30s Network partition between the pipeline and PgBouncer for 30 s None. The writes wait and then continue 0 0
10 pgb_net_loss_30s 40% packet loss between the pipeline and PgBouncer for 30 s None 0 0
11 pgb_shutdown Admin SHUTDOWN. The container starts again Connection closed 0 0
12 pg_pod_kill Kill the primary pod with no grace period. It starts again with its volume 57P01, then connect errors 0 0
13 pg_container_kill Kill the postgres container of the primary Connection closed 0 0
14 pg_pod_failure_20s Primary not available for 20 s 57P01, then connect errors 0 0
15 pg_pod_failure_120s Primary not available for 120 s 57P01. Pooled: 08P01 server login has been failing and query_wait_timeout. Direct: connect errors 334 0
16 pg_terminate_backends_20s pg_terminate_backend on each session of the connector, each 0.3 s for 20 s 57P01 on direct and pooled sessions. PgBouncer passes the error on and logs server conn crashed? 0 0
17 pg_cancel_backends_15s pg_cancel_backend on each active session of the connector, each 50 ms for 15 s 57014 9,501 0
18 pg_read_only_15s ALTER SYSTEM SET default_transaction_read_only = on and a reload, for 15 s 25006 64,195 0
19 pg_read_only_75s The same for 75 s 25006 288,786 1,822 on the direct sink, reported by 2 of 365 tokens
20 pg_table_lock_8s ACCESS EXCLUSIVE lock on the sink tables for 8 s. The role of the connector has lock_timeout = 1s 55P03 7,996 0
21 pg_connection_exhaustion_20s Each connection slot of the role is taken for 20 s, and the sessions of the connector are terminated Direct: 53300. Pooled: 08P01. Both: 57P01 0 0
22 pg_net_partition_30s Network partition between the primary and its clients (PgBouncer and the pipeline) for 30 s None. The writes wait and then continue 0 0
23 pg_idle_in_transaction_timeout The role of the connector has idle_in_transaction_session_timeout = 300ms, with 500 ms of network latency to the primary, for 20 s 25P03 on direct and pooled sessions 5,220 0
24 pg_and_pgb_pod_kill Kill the primary pod and the PgBouncer pod at the same time 57P01, connection closed 0 0
25 failover_pooler_on_standby_15s The server connections of PgBouncer go to the hot standby for 15 s, then back to the primary 25006 on each session, also on a new one 66,368 0
26 failover_pooler_on_standby_75s The same for 75 s 25006 291,251 1,869 on each pooled sink, reported by 2 of 373 tokens
27 tiny_no_fault Scenario 1 with 3 row changes per request None 0 0
28 tiny_pgb_pod_kill Scenario 2 with 3 row changes per request Connection closed 0 0
29 tiny_pgb_pod_failure_30s Scenario 3 with 3 row changes per request Connection closed 0 0
30 tiny_pgb_pause_query_wait_timeout Scenario 5 with 3 row changes per request 08P01 query_wait_timeout 0 0
31 tiny_pg_pod_failure_20s Scenario 14 with 3 row changes per request 57P01 0 0
32 tiny_pg_terminate_backends_20s Scenario 16 with 3 row changes per request 57P01 0 0
33 tiny_pg_read_only_15s Scenario 18 with 3 row changes per request 25006 8 0
34 soak_mixed_faults 240 s of faults in random order, 1 s to 5 s apart: short forms of scenarios 2, 4, 5, 6, 11, 12, 13, 16, 17, 18, 20 and 25 08P01, 25006, 55P03, 57014, 57P01 179,497 (1 run) 0 in each of 4 runs (23, 3, 39 and 36 faults)

Notes on the table:

  • We ran scenarios 1, 4, 9, 24, 25, 26 and 33 a second time on both builds. With the PRs the results were the same (scenario 26: 1,827 keys on each pooled sink, reported by 2 of 373 tokens). On v0.385.0, scenario 4 lost nothing in the second run and scenario 24 lost 1,184 keys. The loss on v0.385.0 depends on which error the connector reads first, as the description of [connectors] Retry a Postgres batch when a pooler ends the session #8017 says.
  • The soak run with 3 faults had two container kills, and the restart back-off of Kubernetes kept PostgreSQL down for about 100 s and 170 s. The last two soak runs did not use scenarios 11 and 13 for that reason.
  • With the PRs, the pipeline pod did not restart, and the pipeline log has no error that the connector classified as permanent.

Observations

  1. Loss that remains. A server that answers and rejects each write for more than about 36 s still loses batches (scenarios 19 and 26). The connector reports the loss in its status and the completion token reports it too, but the rows are not written later. A server that does not answer is different: the connector waited for the full 120 s of scenario 15, and for outages of about 100 s and 170 s in a soak run, and lost nothing. A failover can take longer than 36 s, so the limit of 10 attempts is the case to look at next.
  2. The token error names one connector. In scenario 26 both pooled connectors dropped the same step, and OutputNotDelivered named only one of them. A client that repairs only the named sink misses the other one.
  3. PgBouncer hides default_transaction_read_only. While the parameter was on in the server configuration, a new client session through PgBouncer 1.26.1 could write, and SHOW default_transaction_read_only returned off in that session on the same server backend. A session that was open before stayed read-only. So scenarios 18 and 19 reach a pooled connector for one attempt only: the new connection of [connectors] Retry a Postgres batch on a read-only session #8026 corrects the session at once. This is why we added the hot standby scenarios 25 and 26, where a new session cannot write.
  4. Stale prepared statements. In scenario 7 and in the soak, v0.385.0 got 08P01 prepared statement did not exist from PgBouncer and classified it as permanent. With the PRs this error did not occur in any run. This agrees with the change in [connectors] Retry a Postgres batch on a read-only session #8026 that keeps a new client only together with its statements, which the description lists as not tested separately.

Limits

  • Each scenario ran one time with the PRs, 7 of them two times. A fault hits a batch at an arbitrary point, so one run does not cover each interleaving. The 4 soak runs add 101 faults.
  • The failover scenarios move the pooler to a standby and back. They do not promote the standby, so they do not test commits that were not replicated.
  • Not covered: CDC mode, TLS, a pipeline restart or a checkpoint during a fault, disk faults on PostgreSQL, and the session and statement pooling modes of PgBouncer.
  • 3 more soak runs stopped because of errors in our test driver (a fault that was requested while a pod was still restarting). We did not count them. The sink tables were correct in each of them.

After a failover, a connection pooler can hold a session on the old
primary, which is then a read-only replica. The server rejects each
write with SQLSTATE 25006 and the session stays open. The Postgres
output connector classified this error as permanent and dropped the
batch, and it dropped each later batch for as long as the session
stayed open.

These changes correct this:

- The classifier also treats these errors as temporary: 25006, 55P03
  (lock not available), and the SQLSTATE classes 40 (serialization
  failure, deadlock), 53 (insufficient resources), 57 (operator
  intervention, which now includes a cancelled query), 58 (system
  error) and XX (internal error). The statement and its rows usually do
  not cause them. Where they do, the limit of 10 attempts bounds the
  cost.
- Each new attempt to write a batch opens a new connection. Before, the
  worker kept a session that passed a validity check, and a read-only
  session passes it. The worker closes the old session before the new
  login, because the old session can hold the only connection slot of
  the role. It keeps the new client only together with its prepared
  statements.
- The worker waits between the attempts: the second attempt starts at
  once, and each later attempt waits one second longer, 36 seconds in
  total for the 10 attempts. Before, the attempts on an open session ran
  with no wait.
- A server that answers and does not prepare the statements after a new
  connection uses one of the 10 attempts. The wait with no limit stays
  for a server or a pooler that is not available: a failed login, and
  a connection error (class 08) of any severity, which ends the session
  also when a pooler sends it as ERROR (PgBouncer before 1.16).
- The error for a batch that the worker gives up on states why the
  transaction was lost.

The test proxy can now answer a statement as a server does that cannot
run it, with the session left open. Four new suite cases use it. Each
fails if the change that it covers is removed: the classifier, the new
connection, the order of logout and login (with a role that has one
connection slot), the wait, and the attempt limit for a failed
prepare. Two more cases check that a failed login with severity ERROR
and a pooler that sends ERROR 08P01 at the prepare do not use the
attempts. A unit test covers the wait before each attempt.

Document the new cases, and add the fix to the changelog.

Related: #8014
Signed-off-by: Xavier Bestel <xavier.bestel@feldera.com>
@bestouff

Copy link
Copy Markdown
Contributor Author
  1. Added (refused login with severity ERROR), see the inline answer.
  2. The case already ended with a prepare failure, but only checked E57014, which the write failure has too. It now also checks the text of the prepare error.
  3. PostgreSQL rejects the write statement, not the COMMIT, so I don't expect a 25006 at commit from a real server. Not tested.

@bestouff

Copy link
Copy Markdown
Contributor Author

Thanks, that's a great test. On the observations:

  1. Handled by [connectors] Add max_retries to the Postgres output connector #8098: no limit by default, so scenarios 19 and 26 should not lose anything anymore.
  2. Moot now: [connectors] Report dropped output through completion tokens #8018 is closed, the token keeps its meaning.
  3. Nothing to change on our side, the new connection does the right thing.
  4. Yes, it's the "client kept only with its statements" change ([connectors] Postgres output keeps the prepared statements of the old session when the prepare fails after a reconnect #8019), good to see it confirmed.

@bestouff
bestouff merged commit 749842f into issue-8014 Nov 27, 2026
2 checks passed
@bestouff
bestouff deleted the issue-8014-readonly branch November 27, 2026 16:44
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants