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

Postgres 17 Logical Replication Failover Slot Synchronization & CDC Invariants

Enforces failover-enabled logical replication slots and synchronized standby slots introduced in PostgreSQL 17 for CDC consumers and cache synchronizers. Prevents silent data divergence, dropped CDC events, and catastrophic WAL bloat during failover transitions by ensuring physical standbys retain and mirror logical replication state in lockstep before primary advance.

Prohibited Anti-Pattern: Unsynchronized Logical Replication Slots Causing Data Loss or Consumer Desynchronization Upon HA Failover

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Postgres 17 Logical Replication Failover Slot Synchronization & CDC Invariants - Enforces failover-enabled logical replication slots and synchronized standby slots introduced in PostgreSQL 17 for CDC consumers and cache synchronizers. Prevents silent data divergence, dropped CDC events, and catastrophic WAL bloat during failover transitions by ensuring physical standbys retain and mirror logical replication state in lockstep before primary advance.
globs: src/**/*.ts, src/**/*.sql, deploy/**/*.sql, infra/**/*.tf, src/services/cdc/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/postgres-17-logical-replication-failover-slot-sync-guardrail"
---

# Postgres 17 Logical Replication Failover Slot Synchronization & CDC Invariants

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unsynchronized Logical Replication Slots Causing Data Loss or Consumer Desynchronization Upon HA Failover

## System Constraints
You are a Principal Engineer enforcing Postgres 17 Logical Replication Failover Slot Sync Guardrail. Mandate invariants across slot creation, primary-standby synchronization, and CDC consumer reconnection. Ensure all logical slots used by application CDC pipelines enforce failover flags, align with physical standby slot tracking, and perform transactional restart LSN validations during node failovers.

## Strict Guidelines
- Engineers MUST ALWAYS create logical replication slots with `failover => true` using Postgres 17's extended slot creation API when consumers require high availability.
- Engineers MUST configure `standby_slot_names` on the primary instance to include physical replication standbys, guaranteeing that primary logical replication slots do not advance past standby physical replay positions.
- Engineers MUST enable `sync_replication_slots = on` in standby configurations so that physical standbys periodically sync logical slot metadata from the primary via pg_sync_replication_slots().
- Services MUST verify slot existence and inspect `confirmed_flush_lsn` before streaming CDC events post-failover, reconciling with their internal offset state store.
- Engineers MUST NOT allow logical replication slots to be provisioned without monitoring slot lag (`pg_replication_slots.pg_wal_lsn_diff(pg_current_wal_lsn(), confirmed_flush_lsn)`), preventing catastrophic WAL disk exhaustion.
- CDC consumer reconnection logic MUST gracefully handle transient connection drops during failover and verify that the target node's `pg_is_in_recovery()` returns false before resuming logical stream consumption.

## Bad vs Good Implementations
### Postgres 17 Logical Slot Provisioning and Failover Verification

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Creating a logical slot without failover parameters means that physical standbys have no knowledge of this slot. When the primary fails over, the new primary will lack the slot entirely, causing the CDC consumer to either crash, recreate the slot from current WAL (resulting in silent data loss), or cause race conditions.
```typescript
import { Client } from 'pg';

export async function setupCdcReplicationSlot(client: Client, slotName: string): Promise<void> {
  // ANTI-PATTERN: Creates legacy logical slot without Postgres 17 failover support.
  // Standby nodes will NOT inherit or synchronize this slot, causing replication failure upon failover.
  await client.query(`
    SELECT pg_create_logical_replication_slot($1, 'pgoutput');
  `, [slotName]);
}

export async function consumeCdcStream(client: Client, slotName: string): Promise<void> {
  // Naively assumes slot is ready without verifying standby sync or failover status
  await client.query(`START_REPLICATION SLOT ${slotName} LOGICAL 0/0`);
}
```

#### Production Standard (Correct)
> **Standard**: Ensures the logical replication slot is provisioned with Postgres 17's `failover => true` option or altered in place. It also verifies that the target instance is a promoted primary before starting CDC ingestion, preventing split-brain or consumption desynchronization.
```typescript
import { Client } from 'pg';

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

export async function ensureFailoverEnabledLogicalSlot(
  client: Client,
  slotName: string,
  plugin: string = 'pgoutput'
): Promise<SlotMetadata> {
  // INVARIANT: Postgres 17 allows failover => true in pg_create_logical_replication_slot
  const checkResult = await client.query<SlotMetadata>(`
    SELECT slot_name, plugin, slot_type, failover, synced, confirmed_flush_lsn
    FROM pg_replication_slots
    WHERE slot_name = $1;
  `, [slotName]);

  if (checkResult.rows.length === 0) {
    // Create logical slot with failover=true (Postgres 17: slot_name, plugin, temporary, two_phase, failover)
    await client.query(`
      SELECT pg_create_logical_replication_slot(
        $1,
        $2,
        false,
        false,
        true
      );
    `, [slotName, plugin]);
  } else {
    const slot = checkResult.rows[0];
    if (!slot.failover) {
      // Postgres 17 allows altering existing slots for failover enablement
      await client.query(`
        SELECT pg_alter_replication_slot($1, failover => true);
      `, [slotName]);
    }
  }

  // Verify node is writable and not in recovery before consumer binding
  const nodeState = await client.query<{ in_recovery: boolean }>('SELECT pg_is_in_recovery() AS in_recovery');
  if (nodeState.rows[0].in_recovery) {
    throw new Error(`Cannot bind CDC consumer: connected node is an unpromoted standby.`);
  }

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

  return verified.rows[0];
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Postgres 17 Logical Replication Failover Slot Synchronization & CDC Invariants

Postgres 17 Logical Replication Failover Slot Synchronization & CDC Invariants defines an industrial-grade behavioral standard for backend engineering. Enforces failover-enabled logical replication slots and synchronized standby slots introduced in PostgreSQL 17 for CDC consumers and cache synchronizers. Prevents silent data divergence, dropped CDC events, and catastrophic WAL bloat during failover transitions by ensuring physical standbys retain and mirror logical replication state in lockstep before primary advance. 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: Unsynchronized Logical Replication Slots Causing Data Loss or Consumer Desynchronization Upon HA Failover 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 DriftUnsynchronized Logical Replication Slots Causing Data Loss or Consumer Desynchronization Upon HA FailoverCritical
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 create logical replication slots with `failover => true` using Postgres 17's extended slot creation API when consumers require high availability.

Engineers MUST ALWAYS create logical replication slots with `failover => true` using Postgres 17's extended slot creation API when consumers require high availability.

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 configure `standby_slot_names` on the primary instance to include physical replication standbys, guaranteeing that primary logical replication slots do not advance past standby physical replay positions.

Engineers MUST configure `standby_slot_names` on the primary instance to include physical replication standbys, guaranteeing that primary logical replication slots do not advance past standby physical replay positions.

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

Engineers MUST enable `sync_replication_slots = on` in standby configurations so that physical standbys periodically sync logical slot metadata from the primary via pg_sync_replication_slots().

Engineers MUST enable `sync_replication_slots = on` in standby configurations so that physical standbys periodically sync logical slot metadata from the primary via pg_sync_replication_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

Services MUST verify slot existence and inspect `confirmed_flush_lsn` before streaming CDC events post-failover, reconciling with their internal offset state store.

Services MUST verify slot existence and inspect `confirmed_flush_lsn` before streaming CDC events post-failover, reconciling with their internal offset state store.

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

Engineers MUST NOT allow logical replication slots to be provisioned without monitoring slot lag (`pg_replication_slots.pg_wal_lsn_diff(pg_current_wal_lsn(), confirmed_flush_lsn)`), preventing catastrophic WAL disk exhaustion.

Engineers MUST NOT allow logical replication slots to be provisioned without monitoring slot lag (`pg_replication_slots.pg_wal_lsn_diff(pg_current_wal_lsn(), confirmed_flush_lsn)`), preventing catastrophic WAL disk exhaustion.

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

CDC consumer reconnection logic MUST gracefully handle transient connection drops during failover and verify that the target node's `pg_is_in_recovery()` returns false before resuming logical stream consumption.

CDC consumer reconnection logic MUST gracefully handle transient connection drops during failover and verify that the target node's `pg_is_in_recovery()` returns false before resuming logical stream consumption.

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 & CDC Invariants critical for AI coding assistants?

Enforces failover-enabled logical replication slots and synchronized standby slots introduced in PostgreSQL 17 for CDC consumers and cache synchronizers. Prevents silent data divergence, dropped CDC events, and catastrophic WAL bloat during failover transitions by ensuring physical standbys retain and mirror logical replication state in lockstep before primary advance. 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 (Unsynchronized Logical Replication Slots Causing Data Loss or Consumer Desynchronization Upon HA Failover) 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