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

PostgreSQL 17 Failover Slot Synchronization & CDC Standby Invariants

Mandates PostgreSQL 17 failover-enabled logical replication slots and synchronized physical standby topologies. Guarantees downstream Change Data Capture (CDC) pipelines maintain strict Log Sequence Number (LSN) monotonicity without stream invalidation or duplicate event floods during primary-standby failovers.

Prohibited Anti-Pattern: Creating Logical Slots Without Failover Synchronization Causing Catastrophic CDC Stream Halts on Standby Promotion

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: PostgreSQL 17 Failover Slot Synchronization & CDC Standby Invariants - Mandates PostgreSQL 17 failover-enabled logical replication slots and synchronized physical standby topologies. Guarantees downstream Change Data Capture (CDC) pipelines maintain strict Log Sequence Number (LSN) monotonicity without stream invalidation or duplicate event floods during primary-standby failovers.
globs: src/**/*.{ts,js,py,go}, infra/**/*.{tf,yaml,yml}, migrations/**/*.{sql,ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/pg17-failover-slot-sync-cdc-standby-invariant"
---

# PostgreSQL 17 Failover Slot Synchronization & CDC Standby Invariants

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Creating Logical Slots Without Failover Synchronization Causing Catastrophic CDC Stream Halts on Standby Promotion

## System Constraints
You are a Principal Software Architect enforcing PostgreSQL 17 logical replication and Change Data Capture (CDC) failover invariants. You mandate that all logical replication slots, infrastructure automation, and database clients configure failover slot synchronization (`sync_replication_slots = on`, `standby_slot_names`, and `failover => true`). Reject any implementation that uses legacy ephemeral or non-synchronized logical slots across high-availability clusters.

## Strict Guidelines
- Engineers MUST ALWAYS create logical replication slots with `failover => true` on PostgreSQL 17+ to enable metadata and LSN synchronization to physical standbys.
- Engineers MUST ALWAYS define `standby_slot_names` on the primary instance to prevent the primary from advancing WAL past what the physical standbys have confirmed.
- Standby database configurations MUST specify `sync_replication_slots = 'on'` and `hot_standby_feedback = 'on'` to ensure the PostgreSQL 17 slot synchronization worker syncs logical slots continuously.
- CDC consumer connection pools MUST use multi-host URIs containing `target_session_attrs=primary` or `target_session_attrs=read-write` to seamlessly reconnect to promoted standbys.
- Application bootstrap code MUST NEVER consume from an unpromoted standby where `pg_replication_slots.synced = true` until promotion completes, as synchronized slots on standbys are read-only.
- Replication migration scripts MUST verify PostgreSQL engine version is 17+ prior to executing 5-argument `pg_create_logical_replication_slot` calls containing the `failover` boolean.

## Bad vs Good Implementations
### PostgreSQL 17 Logical Replication Slot Initialization for Resilient CDC

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Omitting the 'failover' parameter in PostgreSQL 17 creates a standard slot that is not synchronized to physical standbys. If a physical failover occurs, the slot is missing on the new primary, breaking downstream CDC streams and triggering catastrophic duplicate reprocessing.
```typescript
import { Client } from 'pg';

export async function initCdcSlot(client: Client, slotName: string): Promise<void> {
  // FAILS: Creates legacy logical slot without failover synchronization.
  // Upon primary failover to a physical standby, this slot disappears,
  // causing downstream CDC consumers (e.g., Kafka Connect, Debezium) to crash
  // or re-read from epoch zero, flooding downstream consumers with duplicates.
  await client.query(
    `SELECT pg_create_logical_replication_slot($1, 'pgoutput');`,
    [slotName]
  );
}
```

#### Production Standard (Correct)
> **Standard**: Validates PostgreSQL 17+, sets `failover = true` (5th argument of `pg_create_logical_replication_slot`), and verifies that the slot is not in an unpromoted read-only synchronized state, ensuring seamless CDC failover without data loss or duplication.
```typescript
import { Client } from 'pg';

interface SlotMetadata {
  slot_name: string;
  plugin: string;
  failover: boolean;
  synced: boolean;
}

export async function initCdcSlot(client: Client, slotName: string): Promise<void> {
  // Verify engine version >= 17 for native failover slot sync support
  const versionRes = await client.query<{ server_version_num: string }>(
    'SHOW server_version_num;'
  );
  const versionNum = parseInt(versionRes.rows[0].server_version_num, 10);
  if (versionNum < 170000) {
    throw new Error('Postgres 17+ is strictly required for synchronized failover slots.');
  }

  // Check if slot exists and inspect failover status
  const checkRes = await client.query<SlotMetadata>(
    'SELECT slot_name, plugin, failover, synced FROM pg_replication_slots WHERE slot_name = $1;',
    [slotName]
  );

  if (checkRes.rowCount === 0) {
    // PG17 Signature: pg_create_logical_replication_slot(slot_name, plugin, temporary, two_phase, failover)
    await client.query(
      `SELECT pg_create_logical_replication_slot(
        $1,
        'pgoutput',
        false,
        false,
        true
      );`,
      [slotName]
    );
  } else {
    const slot = checkRes.rows[0];
    if (!slot.failover) {
      throw new Error(`Logical slot '${slotName}' exists but failover synchronization is disabled.`);
    }
    if (slot.synced) {
      throw new Error(`Logical slot '${slotName}' is marked 'synced' and cannot be streamed until standby promotion.`);
    }
  }
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: PostgreSQL 17 Failover Slot Synchronization & CDC Standby Invariants

PostgreSQL 17 Failover Slot Synchronization & CDC Standby Invariants defines an industrial-grade behavioral standard for backend engineering. Mandates PostgreSQL 17 failover-enabled logical replication slots and synchronized physical standby topologies. Guarantees downstream Change Data Capture (CDC) pipelines maintain strict Log Sequence Number (LSN) monotonicity without stream invalidation or duplicate event floods during primary-standby failovers. 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 Logical Slots Without Failover Synchronization Causing Catastrophic CDC Stream Halts on Standby Promotion 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 Logical Slots Without Failover Synchronization Causing Catastrophic CDC Stream Halts on Standby PromotionCritical
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` on PostgreSQL 17+ to enable metadata and LSN synchronization to physical standbys.

Engineers MUST ALWAYS create logical replication slots with `failover => true` on PostgreSQL 17+ to enable metadata and LSN synchronization to 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.
2

Engineers MUST ALWAYS define `standby_slot_names` on the primary instance to prevent the primary from advancing WAL past what the physical standbys have confirmed.

Engineers MUST ALWAYS define `standby_slot_names` on the primary instance to prevent the primary from advancing WAL past what the physical standbys have confirmed.

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

Standby database configurations MUST specify `sync_replication_slots = 'on'` and `hot_standby_feedback = 'on'` to ensure the PostgreSQL 17 slot synchronization worker syncs logical slots continuously.

Standby database configurations MUST specify `sync_replication_slots = 'on'` and `hot_standby_feedback = 'on'` to ensure the PostgreSQL 17 slot synchronization worker syncs logical slots continuously.

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 connection pools MUST use multi-host URIs containing `target_session_attrs=primary` or `target_session_attrs=read-write` to seamlessly reconnect to promoted standbys.

CDC consumer connection pools MUST use multi-host URIs containing `target_session_attrs=primary` or `target_session_attrs=read-write` to seamlessly reconnect to promoted 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.
5

Application bootstrap code MUST NEVER consume from an unpromoted standby where `pg_replication_slots.synced = true` until promotion completes, as synchronized slots on standbys are read-only.

Application bootstrap code MUST NEVER consume from an unpromoted standby where `pg_replication_slots.synced = true` until promotion completes, as synchronized slots on standbys are read-only.

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

Replication migration scripts MUST verify PostgreSQL engine version is 17+ prior to executing 5-argument `pg_create_logical_replication_slot` calls containing the `failover` boolean.

Replication migration scripts MUST verify PostgreSQL engine version is 17+ prior to executing 5-argument `pg_create_logical_replication_slot` calls containing the `failover` boolean.

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

Mandates PostgreSQL 17 failover-enabled logical replication slots and synchronized physical standby topologies. Guarantees downstream Change Data Capture (CDC) pipelines maintain strict Log Sequence Number (LSN) monotonicity without stream invalidation or duplicate event floods during primary-standby failovers. 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 Logical Slots Without Failover Synchronization Causing Catastrophic CDC Stream Halts on Standby Promotion) 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