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

Postgres 17 Failover Slot Sync Invariant for Resilient Logical CDC

Enforces PostgreSQL 17 failover-enabled logical replication slots and synchronized standby slot topologies across active change-data-capture (CDC) pipelines. Eliminates data loss, stream dropouts, and unbounded duplicate replays during automated physical replica promotions.

Prohibited Anti-Pattern: Creating Unsynchronized Logical Replication Slots Without Standby WAL Anchors and Failover Flags

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Postgres 17 Failover Slot Sync Invariant for Resilient Logical CDC - Enforces PostgreSQL 17 failover-enabled logical replication slots and synchronized standby slot topologies across active change-data-capture (CDC) pipelines. Eliminates data loss, stream dropouts, and unbounded duplicate replays during automated physical replica promotions.
globs: src/**/*.ts, migrations/**/*.sql, infra/**/*.ts, scripts/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/postgres-17-failover-slot-sync-cdc-invariant"
---

# Postgres 17 Failover Slot Sync Invariant for Resilient Logical CDC

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Creating Unsynchronized Logical Replication Slots Without Standby WAL Anchors and Failover Flags

## System Constraints
You are a Principal Software Architect enforcing PostgreSQL 17 logical change-data-capture (CDC) invariants. You must mandate that all logical replication slots are provisioned with failover enablement (failover = true), coordinated with primary standby_slot_names, and consumed with explicit LSN checkpoint tracking. Reject slot creation or client reconnection routines that fail to synchronize slot states across physical standby promotions.

## Strict Guidelines
- Engineers MUST ALWAYS provision logical replication slots with 'failover = true' in PostgreSQL 17+ (using pg_create_logical_replication_slot with the 5th boolean parameter set to true).
- Engineers MUST ensure physical primary instances declare physical standby slots in 'standby_slot_names' before logical slots are allowed to advance past physical replication LSN boundaries.
- CDC consumers MUST verify the 'synced' boolean in 'pg_replication_slots' upon reconnecting to ensure the target instance has been promoted from standby to primary and the slot is no longer read-only/synced.
- Services MUST NOT attempt to recreate missing logical slots dynamically on a newly promoted standby without checking 'restart_lsn' against the consumer's persisted external checkpoint offset.
- Components NEVER connect for active logical streaming directly to a standby node where 'synced' is true, as Postgres 17 designates synchronized slots on standbys as non-consumable until promotion.

## Bad vs Good Implementations
### Postgres 17 Logical Replication Slot Initialization & Promotion Handshake

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Creating the slot with default parameters creates a non-failover slot in PG17. During automated physical replica promotion, the slot does not sync, resulting in pipeline failure. Additionally, reconnecting without checking slot synchronization state and restart LSN can trigger out-of-bounds WAL errors or data loss.
```typescript
import { Client } from 'pg';

export async function initCdcPipeline(client: Client, slotName: string) {
  // Anti-Pattern: Omits PG17 failover flag (defaults to false)
  // If the primary fails over, this slot does NOT exist on the replica,
  // causing CDC stream termination or massive duplicate emission.
  await client.query(`
    SELECT pg_create_logical_replication_slot($1, 'pgoutput');
  `, [slotName]);
}

export async function resumeCdc(client: Client, slotName: string, lastAckLsn: string) {
  // Anti-Pattern: Blind reconnect without verifying sync status or LSN drift
  await client.query(`
    START_REPLICATION SLOT ${slotName} LOGICAL ${lastAckLsn};
  `);
}
```

#### Production Standard (Correct)
> **Standard**: Sets the 5th parameter `failover = true` in `pg_create_logical_replication_slot`, ensuring PostgreSQL 17 synchronizes the slot across physical standbys. Verifies that `synced` is false (confirming the node is promoted) and validates that the consumer's persisted acknowledgment does not overshoot the slot's `confirmed_flush_lsn` before streaming resumes.
```typescript
import { Client } from 'pg';

interface SlotMetadata {
  slot_name: string;
  plugin: string;
  synced: boolean;
  restart_lsn: string;
  confirmed_flush_lsn: string;
}

export async function initCdcPipeline(client: Client, slotName: string): Promise<void> {
  // Mandate Postgres 17 failover slot synchronization parameter: failover = true
  // 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
    )
    WHERE NOT EXISTS (
      SELECT 1 FROM pg_replication_slots WHERE slot_name = $1
    );
  `, [slotName]);
}

export async function prepareAndVerifyConsumerPromotion(
  client: Client,
  slotName: string,
  lastAckLsn: bigint
): Promise<string> {
  const res = await client.query<SlotMetadata>(`
    SELECT slot_name, plugin, synced, restart_lsn, confirmed_flush_lsn
    FROM pg_replication_slots
    WHERE slot_name = $1;
  `, [slotName]);

  const slot = res.rows[0];
  if (!slot) {
    throw new Error(`Fatal CDC Invariant: Slot ${slotName} absent after promotion. Failover sync misconfigured.`);
  }

  // PG17 invariant: Synced slots cannot be read until replica promotion completes
  if (slot.synced) {
    throw new Error(`Slot ${slotName} is currently marked as synced. Target host must be fully promoted before streaming.`);
  }

  const serverFlushLsn = BigInt('0x' + slot.confirmed_flush_lsn.replace('/', ''));
  if (lastAckLsn > serverFlushLsn) {
    throw new Error(
      `LSN Divergence: Consumer ACK (${lastAckLsn.toString(16)}) exceeds server confirmed_flush_lsn (${slot.confirmed_flush_lsn}).`
    );
  }

  return slot.confirmed_flush_lsn;
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Postgres 17 Failover Slot Sync Invariant for Resilient Logical CDC

Postgres 17 Failover Slot Sync Invariant for Resilient Logical CDC defines an industrial-grade behavioral standard for backend engineering. Enforces PostgreSQL 17 failover-enabled logical replication slots and synchronized standby slot topologies across active change-data-capture (CDC) pipelines. Eliminates data loss, stream dropouts, and unbounded duplicate replays during automated physical replica promotions. 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 Unsynchronized Logical Replication Slots Without Standby WAL Anchors and Failover Flags 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 Unsynchronized Logical Replication Slots Without Standby WAL Anchors and Failover FlagsCritical
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' in PostgreSQL 17+ (using pg_create_logical_replication_slot with the 5th boolean parameter set to true).

Engineers MUST ALWAYS provision logical replication slots with 'failover = true' in PostgreSQL 17+ (using pg_create_logical_replication_slot with the 5th boolean parameter set to 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 ensure physical primary instances declare physical standby slots in 'standby_slot_names' before logical slots are allowed to advance past physical replication LSN boundaries.

Engineers MUST ensure physical primary instances declare physical standby slots in 'standby_slot_names' before logical slots are allowed to advance past physical replication LSN boundaries.

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

CDC consumers MUST verify the 'synced' boolean in 'pg_replication_slots' upon reconnecting to ensure the target instance has been promoted from standby to primary and the slot is no longer read-only/synced.

CDC consumers MUST verify the 'synced' boolean in 'pg_replication_slots' upon reconnecting to ensure the target instance has been promoted from standby to primary and the slot is no longer read-only/synced.

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 NOT attempt to recreate missing logical slots dynamically on a newly promoted standby without checking 'restart_lsn' against the consumer's persisted external checkpoint offset.

Services MUST NOT attempt to recreate missing logical slots dynamically on a newly promoted standby without checking 'restart_lsn' against the consumer's persisted external checkpoint offset.

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

Components NEVER connect for active logical streaming directly to a standby node where 'synced' is true, as Postgres 17 designates synchronized slots on standbys as non-consumable until promotion.

Components NEVER connect for active logical streaming directly to a standby node where 'synced' is true, as Postgres 17 designates synchronized slots on standbys as non-consumable 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.
Technical Questions & Answers

Frequently Asked Technical Questions

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

Q:Why is Postgres 17 Failover Slot Sync Invariant for Resilient Logical CDC critical for AI coding assistants?

Enforces PostgreSQL 17 failover-enabled logical replication slots and synchronized standby slot topologies across active change-data-capture (CDC) pipelines. Eliminates data loss, stream dropouts, and unbounded duplicate replays during automated physical replica promotions. 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 Unsynchronized Logical Replication Slots Without Standby WAL Anchors and Failover Flags) 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