Skip to content

feat: Add automatic pooler pause/resume during switchover or failover - #9873

Open
jakubhajek wants to merge 1 commit into
cloudnative-pg:mainfrom
jakubhajek:add-pause-pooler
Open

jakubhajek wants to merge 1 commit into
cloudnative-pg:mainfrom
jakubhajek:add-pause-pooler

Conversation

@jakubhajek

@jakubhajek jakubhajek commented Feb 4, 2026 •

Copy link
Copy Markdown

Summary

Add automatic Pgbouncer pooler pause/resume during switchover or failover operations to minimize client connection failures. The operator drives the pause entirely through operator-owned state (status + an annotation) and never touches the user-owned Pooler spec, so it is safe to use with GitOps.

Fix: #8299

Disclaimer

This feature was developed with assistance from Claude Code. Significant effort was invested in manual testing to validate the behavior across multiple scenarios including manual switchover, automatic failover, multiple poolers, and edge cases.

Changes

API Changes

Add the following fields to spec.pgbouncer in the Pooler CRD, since each pooler independently manages its
own pause/resume lifecycle:

  • pauseDuringSwitchover - opt-in boolean to enable the feature (default: false)
  • pauseDuringSwitchoverTimeout - safety timeout (default: 120s)

Add status fields to Pooler:

  • status.pausedForSwitchover - tracks if this pooler is currently paused for a switchover
  • status.pausedForSwitchoverTimestamp - when this pooler was paused (RFC3339Micro)

Add cnpg.io/pausedDuringSwitchover annotation to track auto-paused poolers.

Controller Changes

  • Pooler controller now watches Cluster objects via a predicate that fires when CurrentPrimary or TargetPrimary changes
  • When a switchover/failover is detected (currentPrimary != targetPrimary), the pooler is marked paused via status.pausedForSwitchover and the cnpg.io/pausedDuringSwitchover annotation; the operator never writes to spec.pgbouncer.paused
  • The pooler instance manager issues the PgBouncer PAUSE/RESUME command when either the user requested it via spec or the operator paused it for switchover via status, so a manual pause and an automatic switchover pause coexist
  • Resume pooler when switchover completes (currentPrimary == targetPrimary)
  • Timeout check runs each reconcile to force-resume if stuck, and the reconcile requeues at the timeout so the force-resume fires even if no further cluster event arrives
  • Each pooler independently manages its own pause/resume state

Documentation Changes

  • Updated docs/src/connection_pooling.md - new "Automatic pause during switchover/failover" section explaining the feature, configuration, and behavior, including the GitOps-safe design
  • Updated docs/src/labels_annotations.md - added cnpg.io/pausedDuringSwitchover annotation documentation
  • Updated docs/src/cloudnative-pg.v1.md - updated PgBouncerSpec and PoolerStatus API reference tables

Default Behaviour

  • Opt-in: Feature disabled by default, no behavior change without explicit configuration
  • GitOps-safe: The operator only writes operator-owned fields (status.pausedForSwitchover and the annotation). It never changes the user-owned spec.pgbouncer.paused, so Argo CD or Flux see no drift and do not fight the operator during a switchover
  • Selective: Only poolers with automated integration are paused (poolers without the built-in integration are skipped)
  • Respects manual pause: Poolers a user has paused via spec.pgbouncer.paused are not modified
  • Safe resume: Only poolers we paused (identified by the annotation and status) are resumed (preserves user intent)
  • Per-pooler: Each pooler tracks its own pause state independently
  • Timeout safety: Force-resume after timeout (default 120s) prevents indefinite service disruption

Configuration example

  ---
  apiVersion: postgresql.cnpg.io/v1
  kind: Cluster
  metadata:
    name: test-switchover-pause
  spec:
    instances: 3
    postgresql:
      parameters:
        max_connections: "500"
    storage:
      size: 1Gi
  ---
  apiVersion: postgresql.cnpg.io/v1
  kind: Pooler
  metadata:
    name: test-switchover-pause-rw
  spec:
    cluster:
      name: test-switchover-pause
    type: rw
    pgbouncer:
      poolMode: session
      pauseDuringSwitchover: true
      pauseDuringSwitchoverTimeout: "30s"  # shorter for testing

Events

Events

Event Type Description
PoolerPaused Normal Pooler paused for switchover/failover
PoolerResumed Normal Pooler resumed after the operation is completed
PoolerPauseTimeout Warning Force resumed pooler after timeout - switchover may not have completed
successfully

How it Works

Manual Switchover (via cnpg.io/targetPrimary annotation or kubectl cnpg promote):

  1. Cluster status changes (currentPrimary != targetPrimary)
  2. Pooler controller is triggered via cluster watch predicate
  3. Each eligible pooler is marked paused via status.pausedForSwitchover + the annotation (never spec); the pooler instance manager reads that status and issues the PgBouncer PAUSE command
  4. Switchover proceeds
  5. Once complete (currentPrimary == targetPrimary), the status and annotation are cleared and the instance manager issues RESUME

Automatic Failover (primary pod failure):

  1. Cluster controller selects a new primary, updating targetPrimary
  2. Pooler controller is triggered via cluster watch predicate
  3. Each eligible pooler is marked paused via status + the annotation, and PgBouncer is paused
  4. Failover proceeds
  5. Once the new primary is healthy, each pooler resumes itself

Timeout Protection:

  1. Each reconcile checks if the pooler has been paused beyond its configured timeout, and requeues so the check runs even without a new cluster event
  2. Pooler is force-resumed to restore service
  3. Warning event emitted on the pooler

Limitations

  • Each Pooler references exactly one Cluster (spec.cluster is a single reference). Users needing poolers for multiple clusters must create separate Pooler resources.
  • Pause happens after switchover/failover is detected (when currentPrimary != targetPrimary), not before the primary change is initiated. Pausing before the switchover starts (seamless for planned switchover) is possible future work; it is not achievable for failover, where the old primary is already gone by the time the operator reacts.
  • Only poolers with automated integration are eligible. Poolers with a custom authQuery, authQuerySecret or serverTLSSecret are skipped.
  • In-flight queries on existing connections may still fail when the backend connection is severed.
  • Some transient connection errors during the switchover window are expected.
  • The pooler controller relies on the cluster watch predicate firing on status changes. If the predicate event is missed, the pooler will catch up on its next reconcile.

Testing

Automated tests

  • Unit tests pass - covers: feature disabled, non-automated poolers skipped, manually paused poolers skipped, pause on switchover, resume on completion, no double-pause, timeout force-resume (keeps a marker so it does not re-pause the same stuck switchover), resume when the feature is disabled while paused, and a partial-write leftover cleanup
  • Instance manager tests - synchronizePause pauses from status without touching spec, resumes when the status flag is cleared, and still honors a user pause via spec
  • E2E tests (tests/e2e/pgbouncer_pause_switchover_test.go):
    • Creates cluster + pooler with pauseDuringSwitchover: true, triggers a switchover, proves the pause through the persisted PoolerPaused event, and verifies the pooler resumes after completion
    • Verifies manually paused poolers are not affected by the automatic pause/resume mechanism
    • Verified on Kind: the service-connectivity suite passed
  • Each pooler independently pauses and resumes based on its own configuration
  • Events emitted on individual pooler resources (PoolerPaused, PoolerResumed, PoolerPauseTimeout)
  • make generate manifests - CRDs updated, no leftover Cluster CRD fields

Manual testing scenario

Apply the following manifests:

  ---
  apiVersion: postgresql.cnpg.io/v1
  kind: Cluster
  metadata:
    name: test-switchover-pause
  spec:
    instances: 3
    postgresql:
      parameters:
        max_connections: "500"
    storage:
      size: 1Gi

  ---
  apiVersion: postgresql.cnpg.io/v1
  kind: Pooler
  metadata:
    name: pooler-switchover-pause-rw
  spec:
    cluster:
      name: test-switchover-pause
    instances: 3
    type: rw
    pgbouncer:
      poolMode: transaction
      pauseDuringSwitchover: true
      pauseDuringSwitchoverTimeout: "30s"
      parameters:
        max_client_conn: "100"
        default_pool_size: "2"
        query_wait_timeout: "120"
        server_connect_timeout: "30"
  ---
  apiVersion: postgresql.cnpg.io/v1
  kind: Pooler
  metadata:
    name: pooler-switchover-pause-ro
  spec:
    cluster:
      name: test-switchover-pause
    instances: 3
    type: ro
    pgbouncer:
      poolMode: transaction
      pauseDuringSwitchover: true
      pauseDuringSwitchoverTimeout: "30s"
      parameters:
        max_client_conn: "100"
        default_pool_size: "2"
        query_wait_timeout: "120"
        server_connect_timeout: "30"
  • Deploy a test pod with Python on the same Kubernetes cluster to ensure you have access to the pooler endpoints (services).
  • Run the following Python script, ensure that the user password is exported as the PGPASSWORD environment variable.
  import psycopg2
  import os
  import time

  while True:
      try:
          conn = psycopg2.connect(
              host="pooler-switchover-pause-rw",
              user="app",
              password=os.environ["PGPASSWORD"],
              dbname="app",
              connect_timeout=30,
              keepalives=1,
              keepalives_idle=30,
              keepalives_interval=2,
              keepalives_count=3
          )
          cur = conn.cursor()
          cur.execute("SELECT 1")
          ts = time.strftime("%H:%M:%S")
          print(f"OK: {ts}")
          conn.close()
      except Exception as e:
          ts = time.strftime("%H:%M:%S")
          print(f"ERR: {ts} - {e}")
      time.sleep(0.5)
  • Manually trigger switchover using the CNPG plugin.
  • You should notice that the script has been frozen for the time when the switchover is happening, but none of the errors were thrown. Once the switchover is complete, the script should resume execution. Once completed, the script should continue to work.
  • Run another test by killing the primary to simulate failover.
  • The limited number of connection errors should be thrown.

Additional tests

On the same pod install Sysbench and run the following testing scenario:

Initialize a test table:

sysbench oltp_read_write \
  --db-driver=pgsql \
  --pgsql-host=pooler-switchover-pause-rw \
  --pgsql-port=5432 \
  --pgsql-user=app \
  --pgsql-password=$PGPASSWORD \
  --pgsql-db=app \
  --tables=4 \
  --table-size=10000 \
  prepare

Run benchmark that tolerates some errors rate:

sysbench oltp_read_write \
  --db-driver=pgsql \
  --pgsql-host=pooler-switchover-pause-rw \
  --pgsql-port=5432 \
  --pgsql-user=app \
  --pgsql-password=$PGPASSWORD \
  --pgsql-db=app \
  --tables=4 \
  --table-size=10000 \
  --threads=10 \
  --time=120 \
  --report-interval=5 \
  run

@jakubhajek
jakubhajek requested a review from a team February 4, 2026 12:28
@dosubot dosubot Bot added the size:XL This PR changes 500-999 lines, ignoring generated files. label Feb 4, 2026
@cnpg-bot cnpg-bot added backport-requested ◀️ This pull request should be backported to all supported releases release-1.25 release-1.28 labels Feb 4, 2026
@github-actions

github-actions Bot commented Feb 4, 2026

Copy link
Copy Markdown
Contributor

❗ By default, the pull request is configured to backport to all release branches.

  • To stop backporting this pr, remove the label: backport-requested ◀️ or add the label 'do not backport'
  • To stop backporting this pr to a certain release branch, remove the specific branch label: release-x.y

@dosubot dosubot Bot added enhancement 🪄 New feature or request ok to merge 👌 This PR can be merged labels Feb 4, 2026
@jakubhajek
jakubhajek force-pushed the add-pause-pooler branch 2 times, most recently from 205e18c to af36813 Compare February 4, 2026 14:28
@sxd sxd added the AI generated To tag PR generated by AI or declared being generated by AI label Feb 5, 2026
@ardentperf

Copy link
Copy Markdown
Contributor

nb. this feature is referenced in docs as something we want to do - https://cloudnative-pg.io/docs/1.28/connection_pooling#pausing-connections

Would be good to add some E2E tests around this

Would be good to check types (things added on cluster, should they be on pooler?) For future direction, we don't want to close the door to having multiple cnpg clusters behind single poolers. So pooler should know about clusters, versus other way around. Probably want to move logic from cluster controller to pooler controller. Should be possible to "watch" cluster and it will dispatch notices when it does switchovers.

Having pooler know more about clusters, it also knows more about pods, might enable other useful features in the future. It should also simplify E2E tests since there's a section dedicated to pooler.

Completely separate comment - there is interest in integrating sysbench this into cnpg plugin as another testing tool.

@jakubhajek
jakubhajek marked this pull request as draft February 22, 2026 19:24
@jakubhajek
jakubhajek force-pushed the add-pause-pooler branch 3 times, most recently from d89c57e to 4052b29 Compare March 18, 2026 09:06
@jakubhajek
jakubhajek marked this pull request as ready for review March 18, 2026 09:07
@dosubot dosubot Bot added size:XXL This PR changes 1000+ lines, ignoring generated files. do not backport This PR must not be backported - it will be in the next minor release and removed size:XL This PR changes 500-999 lines, ignoring generated files. labels Mar 18, 2026
@jakubhajek

Copy link
Copy Markdown
Author

@ardentperf @sxd Jeremy, Jonathan - thanks for the feedback - it seems that I have addressed all your points:

  • Moved configuration and logic from Cluster CRD/controller to Pooler CRD/controller
  • Pooler now watches Cluster via a predicate on CurrentPrimary/TargetPrimary changes
  • Added E2E tests (pause/resume + manually paused poolers not affected)
  • Updated docs (connection_pooling.md, labels_annotations.md, API reference)

Manually tested: planned switchover, pod kill failover, multiple poolers (RW + RO), timeout force-resume, and manual pause not being overwritten.

Ready for review when you get a chance. Thank you for the opportunity to contribute to the CNPG!

@jakubhajek
jakubhajek force-pushed the add-pause-pooler branch 2 times, most recently from fe93e34 to 6b9dc5a Compare March 26, 2026 09:25
@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. and removed size:XXL This PR changes 1000+ lines, ignoring generated files. labels Apr 15, 2026
@charlesomer

Copy link
Copy Markdown
  • Pause happens after switchover/failover is detected (when currentPrimary != targetPrimary), not before the primary change is initiated.
  • In-flight queries on existing connections may still fail when the backend connection is severed.
  • Some transient connection errors during the switchover window are expected.

Just curious if the longer term goal for CNPG is to do the PAUSE before the switchover is initiated to prevent disconnects - to me this would be the expected behaviour. This PR is definitely a step in the right direction though. Thank you 😄

@jakubhajek

Copy link
Copy Markdown
Author

@charlesomerThe goal is to automate the process of upgrading Kubernetes worker nodes. Currently, we manually pause and resume the nodes using an additional Ansible playbook to minimise disruption to our customers. With this feature, we can automate the process, eliminating the need for any extra steps. Simply move the primary role to a replica, and the operator will handle the entire task, reducing the number of disruptions for our customers.

@ardentperf

ardentperf commented May 16, 2026 •

Copy link
Copy Markdown
Contributor

i'm concerned with this approach. i do think that the finally merged code needs to pause connections before starting a switchover, making it seamless, and i'm worried that this code would have to be completely refactored to accomplish that

also - what is the use case for pauseDuringSwitchoverTimeout? i'm curious whats the reasoning about why we'd want the pause to timeout

@jakubhajek
jakubhajek requested a review from a team as a code owner September 15, 2026 12:19
@jakubhajek
jakubhajek force-pushed the add-pause-pooler branch 3 times, most recently from e32d369 to b1826a2 Compare September 16, 2026 16:01
@jakubhajek

Copy link
Copy Markdown
Author

@ardentperf thank you for the feedback. I reworked the design. Here is what the recent changes include.

  • The pause is now status-driven. The operator writes only the status.pausedForSwitchover fields and the cnpg.io/pausedDuringSwitchoverannotation. The operator never changes spec.pgbouncer.paused.
    The pooler instance manager reads the status and runs the PgBouncer PAUSE and RESUME commands. This keeps the feature safe for GitOps. Argo CD and Flux see no drift, so they do not revert the pause during a switchover.

  • All the logic stays on the Pooler side, in the controller and the instance manager.

  • I also added reliability fixes. The reconcile requeues at the timeout, so the force-resume always runs, even when no new cluster event arrives. The operator marks a timed-out switchover, so it does not flap between pause and resume. If you disable the feature while a pooler is paused, or a partial write leaves state behind, the operator resumes the pooler.

  • I verified the feature on Kind. The service-connectivity e2e suite passed, and the switchover test now asserts the PoolerPaused event, so it proves the pause happened and not only the resume.

  • On pause before switchover: I kept "pause after detection" for now. The pooler-side machinery here carries over. A pause-first version for planned switchover mostly adds a cluster-side signal. It does not throw this work away.

  • Failover has no "before", because the old primary is already gone when the operator reacts. So this is the best result for failover. I can sketch pause-first as a separate follow-up if you want it.

  • On pauseDuringSwitchoverTimeout: it is an auto-resume fail-safe. A paused PgBouncer queues clients for an unlimited time. The resume signal can be missed. Examples are an operator restart, a missed event, or an aborted switchover. If the resume signal never arrives, the pooler resumes itself after the timeout and emits a Warning. This is better than blocking clients forever.

@mnencia

mnencia commented Oct 15, 2026

Copy link
Copy Markdown
Member

/test

@github-actions

Copy link
Copy Markdown
Contributor

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

AI generated To tag PR generated by AI or declared being generated by AI backport-requested ◀️ This pull request should be backported to all supported releases do not backport This PR must not be backported - it will be in the next minor release enhancement 🪄 New feature or request ok to merge 👌 This PR can be merged release-1.28 release-1.30 size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature]: Unsupervised Pooler PAUSE during switchover

6 participants