This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: postgres-17-failover-slot-synchronization-invariants

Postgres 17 Logical Replication Failover Slot Synchronization & Zero-Loss CDC Guarantees

Enforces failover-enabled logical replication slots and synchronized standby invariants in Postgres 17+ to guarantee zero-data-loss Change Data Capture (CDC) during physical standby promotion. Mandates explicit failover slot registration, physical standby alignment via synchronized_standby_slots, and verified slot sync states during failover cutovers.

Prohibited Anti-Pattern: Creating unflagged logical replication slots and dropping/recreating slots across node promotions, inducing silent CDC data loss.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Postgres 17 Logical Replication Failover Slot Synchronization & Zero-Loss CDC Guarantees - Enforces failover-enabled logical replication slots and synchronized standby invariants in Postgres 17+ to guarantee zero-data-loss Change Data Capture (CDC) during physical standby promotion. Mandates explicit failover slot registration, physical standby alignment via synchronized_standby_slots, and verified slot sync states during failover cutovers.
globs: src/**/*.{ts,js,py,go}, infra/**/*.sql, config/**/*.{yaml,json}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/postgres-17-failover-slot-synchronization-invariants"
---

# Postgres 17 Logical Replication Failover Slot Synchronization & Zero-Loss CDC Guarantees

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Creating unflagged logical replication slots and dropping/recreating slots across node promotions, inducing silent CDC data loss.

## System Constraints
You are a Principal Database Infrastructure Engineer enforcing Postgres 17 Logical Replication Failover Slot Synchronization. In Postgres 17, logical replication slots can be synchronized to physical standbys using `failover = true` and `sync_replication_slots`. You must mandate that every logical replication slot intended for CDC or stream processing explicitly specifies failover enablement, ensures the primary specifies `synchronized_standby_slots`, and prevents CDC consumers from blindly recreating dropped slots upon failover cutover.

## Strict Guidelines
- Engineers MUST ALWAYS set `failover => true` when provisioning logical replication slots via `pg_create_logical_replication_slot` in Postgres 17+ environments.
- Engineers MUST NOT drop and recreate a logical replication slot when encountering a failover cutover, as recreation moves `confirmed_flush_lsn` forward and discards intermediate WAL records.
- Primary database configurations MUST declare physical standby replication slot names in `synchronized_standby_slots` to prevent the primary from recycling WAL before the standby synchronizes logical slots.
- Physical standby instances MUST enable `sync_replication_slots = true` in `postgresql.conf` to periodically sync failover-enabled logical slots from the primary.
- CDC consumer initialization code MUST verify the slot's `synced` and `failover` attributes in `pg_replication_slots` prior to attaching streaming readers.
- Connection failover handlers MUST query `pg_is_in_recovery()` and assert slot existence on the promoted target before resuming streaming, handling transience with exponential backoff.

## Bad vs Good Implementations
### Postgres 17 CDC Logical Slot Initialization & Failover Handshake

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Creates a logical replication slot without `failover => true`, leaving physical standbys unaware of the slot. When the standby is promoted, the slot is missing. Catching the replication failure and blindly recreating the slot advances the LSN, silently dropping all changes that occurred between primary failure and client reconnection.
```typescript
import { Client } from 'pg';

export async function initCdcSlot(client: Client, slotName: string): Promise<void> {
  // ANTI-PATTERN: Creates legacy logical slot without PG17 failover support.
  // If the primary fails over, this slot does not exist on the promoted replica.
  const check = await client.query('SELECT 1 FROM pg_replication_slots WHERE slot_name = $1', [slotName]);
  if (check.rowCount === 0) {
    await client.query(
      "SELECT pg_create_logical_replication_slot($1, 'pgoutput')",
      [slotName]
    );
  }
}

export async function reconnectCdc(client: Client, slotName: string): Promise<void> {
  // CATASTROPHIC ANTI-PATTERN: Recreating missing slot on failover loses all unconsumed WAL changes
  try {
    await client.query('START_REPLICATION SLOT ' + slotName + ' LOGICAL 0/0');
  } catch (err) {
    await client.query("SELECT pg_create_logical_replication_slot($1, 'pgoutput')", [slotName]);
    await client.query('START_REPLICATION SLOT ' + slotName + ' LOGICAL 0/0');
  }
}
```

#### Production Standard (Correct)
> **Standard**: Leverages Postgres 17's native `failover => true` slot configuration, forbids slot initialization directly on standbys, verifies that the slot on the promoted node retains historical `confirmed_flush_lsn`, and refuses to silently recreate missing slots, ensuring strict zero-data-loss guarantees.
```typescript
import { Client } from 'pg';

interface ReplicationSlotMetadata {
  slot_name: string;
  plugin: string;
  slot_type: string;
  failover: boolean;
  synced: boolean;
  confirmed_flush_lsn: string | null;
}

export async function ensureFailoverEnabledSlot(
  client: Client,
  slotName: string,
  plugin = 'pgoutput'
): Promise<void> {
  const res = await client.query<ReplicationSlotMetadata>(
    `SELECT slot_name, plugin, slot_type, failover, synced, confirmed_flush_lsn
     FROM pg_replication_slots
     WHERE slot_name = $1`,
    [slotName]
  );

  if (res.rowCount === 0) {
    const recoveryCheck = await client.query<{ pg_is_in_recovery: boolean }>('SELECT pg_is_in_recovery()');
    if (recoveryCheck.rows[0].pg_is_in_recovery) {
      throw new Error(`Cannot create failover slot '${slotName}' on a standby node; must originate on primary.`);
    }

    // Postgres 17+: explicitly pass failover => true (5th argument in pg_create_logical_replication_slot)
    await client.query(
      `SELECT pg_create_logical_replication_slot(
        slot_name => $1,
        plugin => $2,
        temporary => false,
        twophase => false,
        failover => true
      )`,
      [slotName, plugin]
    );
    return;
  }

  const slot = res.rows[0];
  if (!slot.failover) {
    throw new Error(
      `Slot '${slotName}' exists but failover synchronization is disabled (failover=false). Required for PG17 zero-loss HA.`
    );
  }
}

export async function verifyPromotedSlotReady(
  client: Client,
  slotName: string
): Promise<string> {
  const recoveryCheck = await client.query<{ pg_is_in_recovery: boolean }>('SELECT pg_is_in_recovery()');
  if (recoveryCheck.rows[0].pg_is_in_recovery) {
    throw new Error('Target node is still in recovery. Promotion incomplete.');
  }

  const res = await client.query<ReplicationSlotMetadata>(
    `SELECT slot_name, failover, synced, confirmed_flush_lsn
     FROM pg_replication_slots
     WHERE slot_name = $1`,
    [slotName]
  );

  if (res.rowCount === 0) {
    throw new Error(`Slot '${slotName}' was not synchronized to promoted target. Check standby sync_replication_slots.`);
  }

  const slot = res.rows[0];
  if (!slot.confirmed_flush_lsn) {
    throw new Error(`Slot '${slotName}' on promoted node lacks confirmed_flush_lsn.`);
  }

  return slot.confirmed_flush_lsn;
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Postgres 17 Logical Replication Failover Slot Synchronization & Zero-Loss CDC Guarantees

Postgres 17 Logical Replication Failover Slot Synchronization & Zero-Loss CDC Guarantees defines an industrial-grade behavioral standard for backend engineering. Enforces failover-enabled logical replication slots and synchronized standby invariants in Postgres 17+ to guarantee zero-data-loss Change Data Capture (CDC) during physical standby promotion. Mandates explicit failover slot registration, physical standby alignment via synchronized_standby_slots, and verified slot sync states during failover cutovers. Modern software architectures require strict adherence to deterministic patterns to guarantee high availability, maintainability, and zero security vulnerabilities.

Framework Paradigm Shift & Drift MechanicsLLMs are trained on millions of open-source repositories containing outdated code, legacy idioms, and unpatched antipatterns. When coding assistants generate implementations for this stack, they default to common statistical tokens: Creating unflagged logical replication slots and dropping/recreating slots across node promotions, inducing silent CDC data loss. Without an explicit system instruction file, developers spend hours debugging silent failures.
Failure Modes & Production Blast Radius

Hazard Analysis: What Breaks Without This Rule

The following failure modes have been cataloged from hundreds of hours of production code reviews where AI assistants produced non-compliant implementations:

Failure ModeAI Symptom (The Anti-Pattern)SeverityProduction Impact & Remedy
AI Hallucination & Deprecation DriftCreating unflagged logical replication slots and dropping/recreating slots across node promotions, inducing silent CDC data loss.Critical
Violating this industrial standard introduces regression bugs, security risks, and unexpected runtime failures in production.
Enforce explicit behavioral system directives across all AI coding assistants in your repository.
Silent Architecture InconsistencyAI assistants produce mixed paradigms across files, creating fragmented codebase conventions.Medium
Increases cognitive load during code reviews and leads to maintenance debt across engineering teams.
Pin project conventions in .cursor/rules, CLAUDE.md, and AGENTS.md so all team agents follow identical guardrails.
Architectural Directives in Detail

Step-by-Step Production Directives

Each rule constraint below is injected into the AI agent's system prompt to establish deterministic boundaries:

1

Engineers MUST ALWAYS set `failover => true` when provisioning logical replication slots via `pg_create_logical_replication_slot` in Postgres 17+ environments.

Engineers MUST ALWAYS set `failover => true` when provisioning logical replication slots via `pg_create_logical_replication_slot` in Postgres 17+ environments.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
2

Engineers MUST NOT drop and recreate a logical replication slot when encountering a failover cutover, as recreation moves `confirmed_flush_lsn` forward and discards intermediate WAL records.

Engineers MUST NOT drop and recreate a logical replication slot when encountering a failover cutover, as recreation moves `confirmed_flush_lsn` forward and discards intermediate WAL records.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
3

Primary database configurations MUST declare physical standby replication slot names in `synchronized_standby_slots` to prevent the primary from recycling WAL before the standby synchronizes logical slots.

Primary database configurations MUST declare physical standby replication slot names in `synchronized_standby_slots` to prevent the primary from recycling WAL before the standby synchronizes logical slots.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
4

Physical standby instances MUST enable `sync_replication_slots = true` in `postgresql.conf` to periodically sync failover-enabled logical slots from the primary.

Physical standby instances MUST enable `sync_replication_slots = true` in `postgresql.conf` to periodically sync failover-enabled logical slots from the primary.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
5

CDC consumer initialization code MUST verify the slot's `synced` and `failover` attributes in `pg_replication_slots` prior to attaching streaming readers.

CDC consumer initialization code MUST verify the slot's `synced` and `failover` attributes in `pg_replication_slots` prior to attaching streaming readers.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
6

Connection failover handlers MUST query `pg_is_in_recovery()` and assert slot existence on the promoted target before resuming streaming, handling transience with exponential backoff.

Connection failover handlers MUST query `pg_is_in_recovery()` and assert slot existence on the promoted target before resuming streaming, handling transience with exponential backoff.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is Postgres 17 Logical Replication Failover Slot Synchronization & Zero-Loss CDC Guarantees critical for AI coding assistants?

Enforces failover-enabled logical replication slots and synchronized standby invariants in Postgres 17+ to guarantee zero-data-loss Change Data Capture (CDC) during physical standby promotion. Mandates explicit failover slot registration, physical standby alignment via synchronized_standby_slots, and verified slot sync states during failover cutovers. Without explicit behavioral boundaries, AI coding assistants (Cursor, Claude Code, Windsurf, Codex) rely on training data averages, which frequently produce deprecated, inefficient, or vulnerable code patterns.

Q:How does adopting this rule prevent AI hallucinations?

This rule explicitly declares what the AI must avoid (Creating unflagged logical replication slots and dropping/recreating slots across node promotions, inducing silent CDC data loss.) and prescribes verified positive examples. Grounding the LLM with negative and positive pairs eliminates guesswork.

Q:Which AI coding environments are supported?

This specification is multi-platform compatible: Cursor (.cursor/rules/*.mdc & .cursorrules), Anthropic Claude Code (CLAUDE.md), Windsurf (.windsurfrules), Codex / Cline (AGENTS.md), and GitHub Copilot (.github/copilot-instructions.md).

Q:Can I combine this rule with other technology stacks?

Yes. Use the Interactive Stack Builder or download an Agent Pack to merge this rule with other frontend, backend, database, security, and DevOps rules without syntax collision.

Open Specification · CC BY 4.0·Free for Personal, Team & Commercial In-Repo Use

Citation & Open Source Attribution Guidelines

This specification is licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). You are completely free to adapt and share this rule in your workspace. If citing, including in public AI benchmark datasets, or redistributing, attribution to AgentRules.org is required.

1 Rule in Stack

Postgres