Skip to content

[Bug]: Replica enters crash/restart loop after restart with overloaded primary checkpointer #11024

Closed

Description

@ardentperf

Is there an existing issue already for this bug?

  • I have searched for an existing issue, and could not find anything. I believe this is a new bug.

I have read the troubleshooting guide

  • I have read the troubleshooting guide and I think this is a new bug.

I am running a supported version of CloudNativePG

  • I have read the troubleshooting guide and I think this is a new bug.

Contact Details

[email protected]

Version

older minor (unsupported)

What version of Kubernetes are you using?

1.34

What is your Kubernetes environment?

Cloud: Azure AKS

How did you install the operator?

Helm

What happened?

We issued kubectl cnpg restart <cluster>. The first replica was restarted, but it never came back online.

The primary database was overloaded (disk at 100% write IOPS) and checkpoints fell significantly behind. At the time we issued kubectl cnpg restart the primary database had just completed a 52 minute checkpoint, and was currently struggling on the next checkpoint.

The WAL records are generated by many connections in parallel, but crash recovery needs to replay the records single-threaded. From an initial pass of postgres recovery code, I think that a replica doesn't write its first restartpoint until it encouters its second checkpoint record in the WAL stream.

CreateRestartPoint() (line 7680) returns false immediately if:

if (XLogRecPtrIsInvalid(lastCheckPointRecPtr) ||
   lastCheckPoint.redo <= ControlFile->checkPointCopy.redo)
{
   ereport(DEBUG2,
           (errmsg_internal("skipping restartpoint, already performed at %X/%X",
                            LSN_FORMAT_ARGS(lastCheckPoint.redo))));
   ...
   return false;
}

General rule: when a standby starts from a restartpoint, the first checkpoint record it decodes during replay will always have redo == ControlFile->checkPointCopy.redo (by definition — that checkpoint IS what the restartpoint was based on). So the first checkpoint record never enables a new restartpoint. Only the next primary checkpoint record (with a strictly higher redo) unlocks it.

Because of the overloaded checkpointer, reaching the second checkpoint from the restartpoint required replaying ~328 GB total. With a 60-minute startup probe timeout and disk I/O still saturated, that was unreachable.

A CNPG startup probe with a ~60-minute timeout killed and restarted the pod if it didn't reach hot standby. This produced a loop: the standby was killed at 18:11 UTC, 19:11, 20:11, 21:11, 22:12, 23:12, 00:12, 01:12 — eight restarts. Every hourly session decoded the same 128.6 GB of WAL, preserved none of it across restarts, and terminated at the same position.

Cluster resource

Relevant log output

Code of Conduct

  • I agree to follow this project's Code of Conduct

Activity

  1. added
    bug 🐛
    triage
    on Jun 24, 2026
  2. changed the title [-][Bug]: Replica enters crash/restart loop after restart with overloaded primary checkpointer[/-] [+][Bug]: Replica enters startup-probe-induced crash/restart loop after restart with overloaded primary checkpointer[/+] on Jun 24, 2026
  3. changed the title [-][Bug]: Replica enters startup-probe-induced crash/restart loop after restart with overloaded primary checkpointer[/-] [+][Bug]: Replica enters crash/restart loop after restart with overloaded primary checkpointer[/+] on Jun 24, 2026
  4. dosubot commented on Jun 24, 2026

    @dosubot

    This is a well-analyzed report. The behavior you're describing — the startup probe killing the pod before it can complete WAL replay, causing a loop where no progress is preserved — is a known gap in how CloudNativePG handles long recovery scenarios.

    How the startup probe works here: By default, CNPG uses pg_isready for the startup probe with a default startDelay of 3600 seconds (1 hour) and a periodSeconds of 10, giving a failure threshold of 360 [1]. The pg_isready strategy treats PostgreSQL "rejecting connections" (exit code 1) as a valid state during WAL replay [2], so the probe should pass while the instance is replaying WAL but not yet accepting connections.

    However, if PostgreSQL hasn't even started the postmaster process yet (e.g., still in crash recovery before accepting any socket connections), pg_isready would return "no response" (exit code 2), which would count as a probe failure. That's likely what's happening here — with 328 GB of WAL to replay single-threaded, the instance never reaches the point where PostgreSQL is listening on the socket within the 1-hour window.

    Immediate mitigation options:

    1. Increase startDelay to give the replica more time:

      spec:
        startDelay: 36000  # 10 hours

      [3]

    2. Override the startup probe directly via .spec.probes.startup for finer control:

      spec:
        probes:
          startup:
            periodSeconds: 10
            failureThreshold: 3600  # ~10 hours

      [4]

    Deeper issue: As you noted, each restart loses all WAL replay progress because no restartpoint can be written until the second checkpoint record is encountered. The startup probe and the /startupz endpoint have a bypass for pg_rewind and MightBeUnavailable() states [5], but there's no equivalent mechanism to detect that crash recovery is actively making progress. Issue #10678 discusses this gap — current probes use read-only queries and have no infrastructure for tracking LSN advancement or recovery progress across restarts [6].

    A more robust solution might involve the instance manager detecting active crash recovery (e.g., monitoring recovery progress via pg_controldata or process activity) and keeping the startup probe alive, similar to how it already handles pg_rewind. That could be worth proposing as an enhancement.

    To reply, just mention @dosu.


    Share context across your team and agents. Try Dosu.

    Leave Feedback Learn about cloudnative-pg with Dosu Add Dosu to your team

  5. ardentperf commented on Jun 24, 2026

    @ardentperf
    ContributorAuthor

    Existing bypass pattern

    The /startupz endpoint (pkg/management/postgres/webserver/remote.go) already bypasses the startup probe for two known-legitimate long-running states:

    func (ws *remoteWebserverEndpoints) isServerStartedUp(w http.ResponseWriter, req *http.Request) {
        if ws.instance.PgRewindIsRunning || ws.instance.MightBeUnavailable() {
            log.Trace("Startup probe skipped")
            _, _ = fmt.Fprint(w, "Skipped")
            return
        }
        ws.startupChecker.IsHealthy(req.Context(), w)
    }
    • PgRewindIsRunning: set true/false around pg_rewind execution — a known long-running operation the instance-manager initiates
    • MightBeUnavailable(): atomic bool set true/false around fencing and internal restart operations

    Both cases share the same pattern: the instance-manager has positive knowledge that postgres is doing a legitimate long-running operation and bypasses the probe for its duration.

    Active archive WAL recovery is the same category: postgres is not hung, it is replaying WAL toward a consistent state. The probe should not fire until recovery has genuinely stalled.

    Proposed change

    1. Progress signal: poll pg_controldata for LSN advancement

    pg_controldata exposes Minimum recovery ending location, which PostgreSQL advances during recovery replay (via UpdateMinRecoveryPoint()) and writes back to pg_control on disk. It is readable without a database connection and CNPG already calls GetPgControldata() elsewhere in instance.go.

    Polling this field every N seconds and comparing to the previous value gives a direct, connection-free measure of whether WAL replay is advancing.

    func (i *Instance) IsActivelyReplaying() bool {
        current := i.getPgControlMinRecoveryPoint()
        prev := i.lastObservedMinRecoveryPoint.Swap(current)
        return current > prev
    }

    lastObservedMinRecoveryPoint is an atomic updated on each poll; no LSN advancement within the polling window → returns false → probe is allowed to fire.

    2. Correct probe ordering: health check first, bypass second

    The bypass must not suppress the probe after postgres has opened for connections. The correct order:

    func (ws *remoteWebserverEndpoints) isServerStartedUp(w http.ResponseWriter, req *http.Request) {
        // Existing bypasses for intentional downtime
        if ws.instance.PgRewindIsRunning || ws.instance.MightBeUnavailable() {
            log.Trace("Startup probe skipped")
            _, _ = fmt.Fprint(w, "Skipped")
            return
        }
    
        // Try real health check first — if postgres is accepting connections, use it
        if ws.startupChecker.IsHealthy(req.Context(), w) {
            return
        }
    
        // Postgres not yet connectable: bypass only if actively replaying WAL
        if ws.instance.IsActivelyReplaying() {
            log.Debug("Startup probe skipped: active WAL recovery in progress")
            _, _ = fmt.Fprint(w, "Skipped")
            return
        }
    
        // Not connectable and not making progress — let probe fail
        http.Error(w, "not started", http.StatusInternalServerError)
    }

    IsHealthy() runs first. Once postgres reaches hot standby and accepts connections, the real health check succeeds and the LSN bypass is never consulted. The bypass only applies in the gap between "postgres process running" and "accepting connections" — exactly where the restart loop problem lives.

    Relationship to startDelay

    This change enables a significant reduction in the startDelay default. The current default of 3600s exists precisely because archive recovery can take over an hour — without a progress signal, any smaller value risks killing a replica that is legitimately replaying WAL. The large default is a workaround for the absence of this bypass.

    With the bypass in place, startDelay only needs to cover the initial boot phase: container start, instance-manager initialization, postgres process launch, and the first LSN poll interval. A default of 60–300s would be sufficient.

    The operational consequence of reducing startDelay is significant: a genuinely broken replica — corrupted data directory, missing WAL, misconfigured recovery target — currently takes up to 3600s before the probe fires and triggers a restart. With a smaller startDelay and the LSN bypass handling the recovery tail, genuine failures are caught in ~1-5 minutes instead of ~60.

    Prior art

    The pg_rewind bypass (PgRewindIsRunning) already demonstrates that CNPG distinguishes "postgres is legitimately unavailable due to a known long-running operation" from "postgres is unexpectedly unavailable." This proposal extends that distinction to archive WAL recovery.

  6. ardentperf commented on Jul 6, 2026

    @ardentperf
    ContributorAuthor

    giving this some more thought, i dont think the control file is guaranteed to see any updates between restore points. minRecoveryPoint in particular is a consistency point; i dont think watching that is a particularly useful indicator of progress.

    checking https://www.postgresql.org/docs/18/functions-info.html#FUNCTIONS-INFO-CONTROLDATA and i'm not sure there's another field that helps either

    however an alternate idea that might work is builing a "wal progress detector" based on the pattern in #11135 (as a logpipe) and watching for progress in the logs?

  7. ardentperf commented on Jul 7, 2026

    @ardentperf
    ContributorAuthor

    This was fairly straightforward when building on top of #11135 - reference the final commit in #11138 (its pretty minimal). The first two commits in that PR or just the commits from 11135

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

Metadata

Metadata

Assignees

Labels

bug 🐛triage

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions