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

Postgres 17 Logical Replication Slot Synchronization on Physical Failover Guardrail

Enforces failover-ready logical replication slots introduced in PostgreSQL 17 to prevent duplicate emissions, dropped CDC events, and LSN divergence across physical standby failover promotions. Mandates synchronized slots via pg_create_logical_replication_slot(..., failover => true) coupled with primary-side synchronized standby slot reservations. Eliminates dual-consumer race conditions and state corruption during high-availability orchestrations.

Prohibited Anti-Pattern: Creating Logical Slots Without Failover Synchronization Causing Data Loss or Uncontrolled Event Replay Upon Primary Promotion

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Postgres 17 Logical Replication Slot Synchronization on Physical Failover Guardrail - Enforces failover-ready logical replication slots introduced in PostgreSQL 17 to prevent duplicate emissions, dropped CDC events, and LSN divergence across physical standby failover promotions. Mandates synchronized slots via pg_create_logical_replication_slot(..., failover => true) coupled with primary-side synchronized standby slot reservations. Eliminates dual-consumer race conditions and state corruption during high-availability orchestrations.
globs: src/**/*.ts, src/database/**/*.ts, src/infra/**/*.ts, migrations/**/*.sql
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/pg17-failover-logical-slot-sync-invariant"
---

# Postgres 17 Logical Replication Slot Synchronization on Physical Failover Guardrail

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Creating Logical Slots Without Failover Synchronization Causing Data Loss or Uncontrolled Event Replay Upon Primary Promotion

## System Constraints
You are a Principal Infrastructure & Database Architect enforcing Postgres 17 failover-safe logical replication standards. Mandate that every logical replication slot provisioned for change data capture (CDC), event streaming, or replica consumption explicitly declares `failover = true` (or `pg_create_logical_replication_slot(..., failover => true)`) and validates primary-side `synchronized_standby_slots` alignment. Disallow legacy, non-failover slots that do not synchronize restart_lsn across physical standby nodes. Enforce that client connection brokers gracefully handle slot promotion without emitting historical duplicates or crashing on non-advanced LSNs.

## Strict Guidelines
- Engineers MUST ALWAYS create logical replication slots with `failover => true` when provisioning CDC connectors against Postgres 17+ primary instances.
- Engineers MUST NOT rely on external replication slot synchronization scripts or manual slot recreate scripts upon primary failover in Postgres 17+ environments.
- Database orchestration scripts MUST verify that the primary's `synchronized_standby_slots` parameter includes the physical replication application_names replicating the CDC slots.
- CDC consumer initialization code MUST verify `confirmed_flush_lsn` against physical standby nodes before resuming consumption post-failover to avoid phantom duplicates.
- Services MUST NEVER configure a CDC connector using implicit temporary or non-failover persistent replication slots in production topologies.

## Bad vs Good Implementations
### Configuring Postgres 17 CDC Logical Slot with Synchronized Failover

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Legacy pg_create_logical_replication_slot without failover => true does not replicate slot metadata or restart_lsn across physical streaming replication standbys. When Patroni or cloud orchestrators promote the standby, the slot vanishes, leading to dropped CDC events or massive duplicate replay.
```typescript
import { Client } from 'pg';

export async function setupCdcReplicationSlot(client: Client, slotName: string): Promise<void> {
  // ANTI-PATTERN: Creates a legacy logical slot without the Postgres 17 failover flag.
  // During an HA failover to a physical standby, this slot will not exist on the promoted
  // replica, causing catastrophic consumer halts or re-reading from transaction zero.
  await client.query(
    `SELECT pg_create_logical_replication_slot($1, 'pgoutput');`,
    [slotName]
  );
}
```

#### Production Standard (Correct)
> **Standard**: Declaring failover => true in Postgres 17 ensures the slot's restart_lsn and confirmed_flush_lsn are actively copied to standby nodes via physical streaming replication. Upon promotion, downstream CDC consumers connect to the new primary seamlessly with zero dropped or duplicated events.
```typescript
import { Client } from 'pg';

export async function setupCdcReplicationSlot(client: Client, slotName: string, standbyAppName: string): Promise<void> {
  // INVARIANT FIX: Leverage Postgres 17 native slot synchronization.
  // 1. Ensure primary enforces standby sync to prevent advancing past un-replicated LSNs.
  // 2. Create the logical slot with failover => true.
  await client.query(
    `SELECT pg_create_logical_replication_slot(
       slot_name => $1,
       plugin => 'pgoutput',
       temporary => false,
       twophase => true,
       failover => true
     );`,
    [slotName]
  );

  // Validate that the slot is registered as failover-capable
  const { rows } = await client.query(
    `SELECT slot_name, failover, synced 
     FROM pg_replication_slots 
     WHERE slot_name = $1;`,
    [slotName]
  );

  if (!rows[0] || rows[0].failover !== true) {
    throw new Error(`CRITICAL: Logical slot ${slotName} failed to register with failover=true`);
  }
}
```

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 Slot Synchronization on Physical Failover Guardrail

Postgres 17 Logical Replication Slot Synchronization on Physical Failover Guardrail defines an industrial-grade behavioral standard for backend engineering. Enforces failover-ready logical replication slots introduced in PostgreSQL 17 to prevent duplicate emissions, dropped CDC events, and LSN divergence across physical standby failover promotions. Mandates synchronized slots via pg_create_logical_replication_slot(..., failover => true) coupled with primary-side synchronized standby slot reservations. Eliminates dual-consumer race conditions and state corruption during high-availability orchestrations. 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 Data Loss or Uncontrolled Event Replay Upon Primary 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 Data Loss or Uncontrolled Event Replay Upon Primary 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` when provisioning CDC connectors against Postgres 17+ primary instances.

Engineers MUST ALWAYS create logical replication slots with `failover => true` when provisioning CDC connectors against Postgres 17+ primary instances.

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 NOT rely on external replication slot synchronization scripts or manual slot recreate scripts upon primary failover in Postgres 17+ environments.

Engineers MUST NOT rely on external replication slot synchronization scripts or manual slot recreate scripts upon primary failover in Postgres 17+ 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.
3

Database orchestration scripts MUST verify that the primary's `synchronized_standby_slots` parameter includes the physical replication application_names replicating the CDC slots.

Database orchestration scripts MUST verify that the primary's `synchronized_standby_slots` parameter includes the physical replication application_names replicating the CDC 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

CDC consumer initialization code MUST verify `confirmed_flush_lsn` against physical standby nodes before resuming consumption post-failover to avoid phantom duplicates.

CDC consumer initialization code MUST verify `confirmed_flush_lsn` against physical standby nodes before resuming consumption post-failover to avoid phantom duplicates.

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 NEVER configure a CDC connector using implicit temporary or non-failover persistent replication slots in production topologies.

Services MUST NEVER configure a CDC connector using implicit temporary or non-failover persistent replication slots in production topologies.

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 Slot Synchronization on Physical Failover Guardrail critical for AI coding assistants?

Enforces failover-ready logical replication slots introduced in PostgreSQL 17 to prevent duplicate emissions, dropped CDC events, and LSN divergence across physical standby failover promotions. Mandates synchronized slots via pg_create_logical_replication_slot(..., failover => true) coupled with primary-side synchronized standby slot reservations. Eliminates dual-consumer race conditions and state corruption during high-availability orchestrations. 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 Data Loss or Uncontrolled Event Replay Upon Primary 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

Postgres