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

PostgreSQL 17 Native Failover Slot Synchronization for Zero-Downtime CDC Continuity

Mandates PostgreSQL 17 native logical failover slots and physical standby synchronization for change-data-capture (CDC) pipelines. Prevents catastrophic LSN divergence, stream recreations, and data loss during physical standby promotion by enforcing failover-enabled logical slots and physical standby slot coordination.

Prohibited Anti-Pattern: Creating uncoordinated logical slots on primary nodes without failover enablement or standby slot dependencies.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: PostgreSQL 17 Native Failover Slot Synchronization for Zero-Downtime CDC Continuity - Mandates PostgreSQL 17 native logical failover slots and physical standby synchronization for change-data-capture (CDC) pipelines. Prevents catastrophic LSN divergence, stream recreations, and data loss during physical standby promotion by enforcing failover-enabled logical slots and physical standby slot coordination.
globs: src/**/*.ts, src/cdc/**/*.ts, src/db/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/pg17-failover-logical-slot-synchronization"
---

# PostgreSQL 17 Native Failover Slot Synchronization for Zero-Downtime CDC Continuity

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Creating uncoordinated logical slots on primary nodes without failover enablement or standby slot dependencies.

## System Constraints
You are a Principal Database Architect enforcing PostgreSQL 17 failover slot synchronization standards. In distributed architectures utilizing Change Data Capture (CDC) or logical replication across high-availability physical replicas, you MUST ensure that all logical replication slots are created with `failover = true` and that primary instances configure `standby_slot_names` matching physical replicas. You MUST prevent any implementation that provisions logical slots without failover flags or connects consumers without validating slot sync state across failover events.

## Strict Guidelines
- Engineers MUST ALWAYS provision logical replication slots with `failover = true` using PostgreSQL 17+ native syntax (`pg_create_logical_replication_slot(..., failover => true)`).
- Engineers MUST ALWAYS verify that the primary PostgreSQL 17 server registers the physical replica in `standby_slot_names` before streaming from dependent logical replication slots to ensure WAL retention on physical standbys.
- Engineers MUST NOT create logical replication slots with legacy commands that omit the `failover` parameter when targeting PostgreSQL 17 high-availability environments.
- CDC consumer services MUST query `pg_replication_slots.sync_state` and ensure the slot is synchronized (`sync_state = 's'` or locally persistent) before resuming ingestion following a cluster failover.
- Database migration scripts and bootstrap workers MUST NEVER execute `pg_drop_replication_slot` automatically on consumer reconnect failures; they MUST inspect `confirmed_flush_lsn` against candidate nodes.

## Bad vs Good Implementations
### Configuring PG17 CDC Slot with Failover Synchronization vs Legacy Insecure Slot

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Omits the PostgreSQL 17 `failover` argument and does not validate `standby_slot_names`. If the primary fails over to a physical standby, the logical replication slot is lost, breaking CDC pipelines and risking permanent data omission or expensive resync operations.
```typescript
import { Client } from 'pg';

export async function setupCdcPipeline(client: Client, slotName: string, plugin: string = 'pgoutput'): Promise<void> {
  // FAILS: Creates legacy slot without failover=true; cannot sync to physical standby
  // When primary fails over, this slot does not exist on the promoted replica,
  // causing CDC stream failure and requiring a complete snapshot rebuild.
  const query = `
    SELECT slot_name, consistent_point, snapshot_name, output_plugin
    FROM pg_create_logical_replication_slot($1, $2);
  `;
  await client.query(query, [slotName, plugin]);
}
```

#### Production Standard (Correct)
> **Standard**: Enforces PostgreSQL 17+ runtime version, validates that the physical replication slot is registered in `standby_slot_names` to prevent primary WAL truncation ahead of the standby, and provisions the logical slot with `failover => true` for seamless replica failover continuity.
```typescript
import { Client } from 'pg';

interface SlotCreationResult {
  slotName: string;
  consistentPoint: string;
  snapshotName: string;
}

export async function setupCdcPipeline(
  client: Client,
  slotName: string,
  physicalStandbySlot: string,
  plugin: string = 'pgoutput'
): Promise<SlotCreationResult> {
  // 1. Verify PostgreSQL 17+ environment and standby slot coordination
  const preflight = await client.query<{
    server_version_num: string;
    standby_slots: string;
  }>(`
    SELECT 
      current_setting('server_version_num') AS server_version_num,
      current_setting('standby_slot_names') AS standby_slots;
  `);

  const version = parseInt(preflight.rows[0].server_version_num, 10);
  if (version < 170000) {
    throw new Error(`PostgreSQL 17+ required for native failover slot sync. Found: ${version}`);
  }

  const configuredStandbys = preflight.rows[0].standby_slots.split(',').map(s => s.trim());
  if (!configuredStandbys.includes(physicalStandbySlot)) {
    throw new Error(
      `Primary standby_slot_names ('${preflight.rows[0].standby_slots}') must include '${physicalStandbySlot}'`
    );
  }

  // 2. Provision logical slot with failover => true
  const createSlotQuery = `
    SELECT slot_name, consistent_point, snapshot_name
    FROM pg_create_logical_replication_slot(
      slot_name => $1,
      plugin => $2,
      temporary => false,
      twophase => false,
      failover => true
    );
  `;
  const { rows } = await client.query<{ slot_name: string; consistent_point: string; snapshot_name: string }>(
    createSlotQuery,
    [slotName, plugin]
  );

  return {
    slotName: rows[0].slot_name,
    consistentPoint: rows[0].consistent_point,
    snapshotName: rows[0].snapshot_name,
  };
}
```

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 Native Failover Slot Synchronization for Zero-Downtime CDC Continuity

PostgreSQL 17 Native Failover Slot Synchronization for Zero-Downtime CDC Continuity defines an industrial-grade behavioral standard for backend engineering. Mandates PostgreSQL 17 native logical failover slots and physical standby synchronization for change-data-capture (CDC) pipelines. Prevents catastrophic LSN divergence, stream recreations, and data loss during physical standby promotion by enforcing failover-enabled logical slots and physical standby slot coordination. 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 uncoordinated logical slots on primary nodes without failover enablement or standby slot dependencies. 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 uncoordinated logical slots on primary nodes without failover enablement or standby slot dependencies.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 provision logical replication slots with `failover = true` using PostgreSQL 17+ native syntax (`pg_create_logical_replication_slot(..., failover => true)`).

Engineers MUST ALWAYS provision logical replication slots with `failover = true` using PostgreSQL 17+ native syntax (`pg_create_logical_replication_slot(..., failover => true)`).

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 ALWAYS verify that the primary PostgreSQL 17 server registers the physical replica in `standby_slot_names` before streaming from dependent logical replication slots to ensure WAL retention on physical standbys.

Engineers MUST ALWAYS verify that the primary PostgreSQL 17 server registers the physical replica in `standby_slot_names` before streaming from dependent logical replication slots to ensure WAL retention on physical standbys.

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 create logical replication slots with legacy commands that omit the `failover` parameter when targeting PostgreSQL 17 high-availability environments.

Engineers MUST NOT create logical replication slots with legacy commands that omit the `failover` parameter when targeting PostgreSQL 17 high-availability 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.
4

CDC consumer services MUST query `pg_replication_slots.sync_state` and ensure the slot is synchronized (`sync_state = 's'` or locally persistent) before resuming ingestion following a cluster failover.

CDC consumer services MUST query `pg_replication_slots.sync_state` and ensure the slot is synchronized (`sync_state = 's'` or locally persistent) before resuming ingestion following a cluster failover.

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

Database migration scripts and bootstrap workers MUST NEVER execute `pg_drop_replication_slot` automatically on consumer reconnect failures

Database migration scripts and bootstrap workers MUST NEVER execute `pg_drop_replication_slot` automatically on consumer reconnect failures; they MUST inspect `confirmed_flush_lsn` against candidate nodes.

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 Native Failover Slot Synchronization for Zero-Downtime CDC Continuity critical for AI coding assistants?

Mandates PostgreSQL 17 native logical failover slots and physical standby synchronization for change-data-capture (CDC) pipelines. Prevents catastrophic LSN divergence, stream recreations, and data loss during physical standby promotion by enforcing failover-enabled logical slots and physical standby slot coordination. 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 uncoordinated logical slots on primary nodes without failover enablement or standby slot dependencies.) 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