This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: pg17-cdc-failover-slot-sync-production-standard

PostgreSQL 17 Logical Replication Failover Slot Synchronization for Zero-Data-Loss CDC

Enforces PostgreSQL 17 native failover-enabled logical replication slots (`failover = true`) and primary standby synchronization (`synchronized_standby_slots`). This guarantees logical replication slots persist across HA failovers, preventing CDC stream destruction, missing change events, and catastrophic rewind loops.

Prohibited Anti-Pattern: Provisioning Unsynced Logical Replication Slots That Disappear or Desynchronize During HA Failover

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: PostgreSQL 17 Logical Replication Failover Slot Synchronization for Zero-Data-Loss CDC - Enforces PostgreSQL 17 native failover-enabled logical replication slots (`failover = true`) and primary standby synchronization (`synchronized_standby_slots`). This guarantees logical replication slots persist across HA failovers, preventing CDC stream destruction, missing change events, and catastrophic rewind loops.
globs: src/**/*.{ts,tsx}, infra/**/*.ts, migrations/**/*.sql
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/pg17-cdc-failover-slot-sync-production-standard"
---

# PostgreSQL 17 Logical Replication Failover Slot Synchronization for Zero-Data-Loss CDC

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Provisioning Unsynced Logical Replication Slots That Disappear or Desynchronize During HA Failover

## System Constraints
You are a Principal Software Architect enforcing zero-data-loss CDC standards for PostgreSQL 17+. You must mandate failover-enabled logical replication slots (`failover => true`) and guarantee that CDC slots are registered in `synchronized_standby_slots` on the primary instance. Reject any slot creation, migration, or client connection strategy that does not account for standby slot synchronization.

## Strict Guidelines
- Engineers MUST ALWAYS provision logical replication slots with `failover => true` on PostgreSQL 17+ clusters to enable physical standby mirroring.
- Engineers MUST verify that primary configurations define `synchronized_standby_slots` covering all active physical replication standbys before activating consumer pipelines.
- Engineers MUST NOT allow CDC ingestion services to consume from read-only physical standbys using synchronized slots before failover occurs (synchronized slots are read-only until promotion).
- Code SHOULD validate PostgreSQL major version (>= 17) and confirm that `sync_replication_slots = on` and `hot_standby_feedback = on` are active on replica candidates.
- Services MUST query `pg_replication_slots` to ensure `failover = true` and `synced = false` on primary, or assert `synced = true` on hot standby prior to failover cutover.

## Bad vs Good Implementations
### PostgreSQL 17 Failover-Enabled Logical Slot Initialization

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Legacy `pg_create_logical_replication_slot(slot_name, plugin)` defaults `failover` to `false` in PostgreSQL 17. The slot is not tracked by physical standbys, leading to complete slot abandonment or severe consumer rewind when the primary fails over.
```typescript
import { Client } from 'pg';

export async function registerCdcPipelineSlot(client: Client, slotName: string): Promise<void> {
  // FAILS: Creates legacy logical slot without failover preservation.
  // When HA failover occurs, this slot is not mirrored on standby nodes,
  // causing CDC engine to permanently fail and lose unconsumed WAL data.
  await client.query(
    'SELECT pg_create_logical_replication_slot($1, $2);',
    [slotName, 'pgoutput']
  );
}
```

#### Production Standard (Correct)
> **Standard**: Verifies engine version compatibility, validates that the primary database is enforcing standby synchronization barriers, and explicitly creates the logical replication slot with `failover => true` to guarantee persistence across cluster failovers.
```typescript
import { Client } from 'pg';

export async function registerCdcPipelineSlot(client: Client, slotName: string): Promise<void> {
  // 1. Verify PostgreSQL version is >= 170000
  const versionRes = await client.query<{ server_version_num: string }>(
    'SHOW server_version_num;'
  );
  const versionNum = parseInt(versionRes.rows[0]?.server_version_num ?? '0', 10);
  if (versionNum < 170000) {
    throw new Error(`PostgreSQL 17+ required for failover slots. Detected: ${versionNum}`);
  }

  // 2. Assert synchronized_standby_slots is actively configured on Primary
  const syncCheck = await client.query<{ synchronized_standby_slots: string }>(
    'SHOW synchronized_standby_slots;'
  );
  if (!syncCheck.rows[0]?.synchronized_standby_slots) {
    throw new Error('HA Invariant Violated: synchronized_standby_slots must be non-empty.');
  }

  // 3. Provision slot with failover => true (PostgreSQL 17 explicit parameter)
  await client.query(
    `SELECT pg_create_logical_replication_slot(
       slot_name => $1,
       plugin => $2,
       temporary => false,
       twophase => false,
       failover => true
     );`,
    [slotName, 'pgoutput']
  );
}
```

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: PostgreSQL 17 Logical Replication Failover Slot Synchronization for Zero-Data-Loss CDC

PostgreSQL 17 Logical Replication Failover Slot Synchronization for Zero-Data-Loss CDC defines an industrial-grade behavioral standard for backend engineering. Enforces PostgreSQL 17 native failover-enabled logical replication slots (`failover = true`) and primary standby synchronization (`synchronized_standby_slots`). This guarantees logical replication slots persist across HA failovers, preventing CDC stream destruction, missing change events, and catastrophic rewind loops. 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: Provisioning Unsynced Logical Replication Slots That Disappear or Desynchronize During 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 DriftProvisioning Unsynced Logical Replication Slots That Disappear or Desynchronize During 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 provision logical replication slots with `failover => true` on PostgreSQL 17+ clusters to enable physical standby mirroring.

Engineers MUST ALWAYS provision logical replication slots with `failover => true` on PostgreSQL 17+ clusters to enable physical standby mirroring.

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 verify that primary configurations define `synchronized_standby_slots` covering all active physical replication standbys before activating consumer pipelines.

Engineers MUST verify that primary configurations define `synchronized_standby_slots` covering all active physical replication standbys before activating consumer pipelines.

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 NOT allow CDC ingestion services to consume from read-only physical standbys using synchronized slots before failover occurs (synchronized slots are read-only until promotion).

Engineers MUST NOT allow CDC ingestion services to consume from read-only physical standbys using synchronized slots before failover occurs (synchronized slots are read-only until promotion).

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

Code SHOULD validate PostgreSQL major version (>= 17) and confirm that `sync_replication_slots = on` and `hot_standby_feedback = on` are active on replica candidates.

Code SHOULD validate PostgreSQL major version (>= 17) and confirm that `sync_replication_slots = on` and `hot_standby_feedback = on` are active on replica candidates.

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

Services MUST query `pg_replication_slots` to ensure `failover = true` and `synced = false` on primary, or assert `synced = true` on hot standby prior to failover cutover.

Services MUST query `pg_replication_slots` to ensure `failover = true` and `synced = false` on primary, or assert `synced = true` on hot standby prior to failover cutover.

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 PostgreSQL 17 Logical Replication Failover Slot Synchronization for Zero-Data-Loss CDC critical for AI coding assistants?

Enforces PostgreSQL 17 native failover-enabled logical replication slots (`failover = true`) and primary standby synchronization (`synchronized_standby_slots`). This guarantees logical replication slots persist across HA failovers, preventing CDC stream destruction, missing change events, and catastrophic rewind loops. 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 (Provisioning Unsynced Logical Replication Slots That Disappear or Desynchronize During 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

PostgreSQL