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

Postgres 17 Failover Logical Replication Slot Synchronization Guardrail

Enforces Postgres 17 native failover-enabled logical replication slots and slot synchronization workers across high-availability physical standbys. Prevents unrecoverable downstream CDC stream corruption, message duplication storms, and silent data loss caused by non-synchronized restart LSN positions during database failover events.

Prohibited Anti-Pattern: Unsynchronized Logical Slots Causing Downstream CDC Replication Panics Post-Failover

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Postgres 17 Failover Logical Replication Slot Synchronization Guardrail - Enforces Postgres 17 native failover-enabled logical replication slots and slot synchronization workers across high-availability physical standbys. Prevents unrecoverable downstream CDC stream corruption, message duplication storms, and silent data loss caused by non-synchronized restart LSN positions during database failover events.
globs: src/**/*.ts, infra/**/*.tf, infra/**/*.yaml, migrations/**/*.sql
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/postgres-17-failover-logical-slot-sync-standard"
---

# Postgres 17 Failover Logical Replication Slot Synchronization Guardrail

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unsynchronized Logical Slots Causing Downstream CDC Replication Panics Post-Failover

## System Constraints
You are a Principal Database Architect and Infrastructure Reliability Engineer enforcing Postgres 17 Failover Logical Slot Synchronization Standards. You mandate that all logical replication slots provisioned for downstream Change Data Capture (Debezium, Kafka Connect, custom tailers) explicitly set failover = true, that primary instances maintain physical standby references in standby_slot_names, and that physical standby instances enable sync_replication_slots with a database connection to guarantee uninterrupted failover transitions.

## Strict Guidelines
- Engineers MUST ALWAYS provision logical replication slots with failover = true via pg_create_logical_replication_slot() or ALTER_REPLICATION_SLOT in Postgres 17+ environments.
- Engineers MUST configure standby_slot_names on the primary instance to include physical standby replication slots, ensuring WAL segments are retained until both physical standbys and logical consumers advance.
- Engineers MUST configure sync_replication_slots = true on all physical standby instances to enable the native slot synchronization background worker.
- Services MUST ensure primary_conninfo on physical replicas specifies dbname to grant the slot sync worker access to sync logical slot state from the primary.
- Engineers MUST NOT rely on external orchestration scripts or ad-hoc cron jobs to copy slot state when running on Postgres 17 or higher.
- CDC consumer services MUST verify slot failover capability during initialization by inspecting pg_replication_slots.failover and pg_replication_slots.synced attributes before consuming changes.

## Bad vs Good Implementations
### CDC Logical Slot Provisioning and Invariant Verification

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Creating a logical replication slot without specifying failover = true prevents Postgres 17 physical replicas from syncing the slot. During an HA failover event, the new primary will lack this logical slot, resulting in fatal downstream CDC consumer failures or complete re-ingestion and duplicate processing.
```typescript
import { Client } from 'pg';

export async function setupCdcReplicationSlot(client: Client, slotName: string): Promise<void> {
  // Anti-pattern: Creates slot without failover parameter (defaults to false in PG17)
  // If primary fails over, the standby has no copy of this slot, causing downstream CDC to fail or replay from beginning
  await client.query(`
    SELECT pg_create_logical_replication_slot(
      $1,
      'pgoutput'
    );
  `, [slotName]);
}
```

#### Production Standard (Correct)
> **Standard**: Validates engine capability (Postgres 17+), verifies the primary's `standby_slot_names` guardrail, explicitly provisions the logical replication slot with `failover => true`, and validates the state in `pg_replication_slots` to guarantee smooth failover without data loss.
```typescript
import { Client } from 'pg';

interface ReplicationSlotConfig {
  slotName: string;
  plugin?: string;
  standbySlotName?: string;
}

export async function setupCdcReplicationSlot(client: Client, config: ReplicationSlotConfig): Promise<void> {
  const plugin = config.plugin ?? 'pgoutput';

  // Check server version to ensure Postgres 17+ failover 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 required for native logical slot failover synchronization.');
  }

  // 1. Verify primary has standby_slot_names configured to prevent WAL recycling ahead of standbys
  const standbyCheck = await client.query<{ setting: string }>(
    "SELECT setting FROM pg_settings WHERE name = 'standby_slot_names';"
  );
  const configuredStandbys = standbyCheck.rows[0]?.setting || '';
  
  if (config.standbySlotName && !configuredStandbys.includes(config.standbySlotName)) {
    throw new Error(
      `Primary standby_slot_names does not include '${config.standbySlotName}'. Standby synchronization compromised.`
    );
  }

  // 2. Create logical slot with explicit failover = true parameter
  await client.query(`
    SELECT pg_create_logical_replication_slot(
      slot_name => $1,
      plugin => $2,
      temporary => false,
      twophase => false,
      failover => true
    );
  `, [config.slotName, plugin]);

  // 3. Verify slot attributes match high-availability requirements
  const slotVerification = await client.query<{
    slot_name: string;
    failover: boolean;
    synced: boolean;
  }>(
    'SELECT slot_name, failover, synced FROM pg_replication_slots WHERE slot_name = $1;',
    [config.slotName]
  );

  const slot = slotVerification.rows[0];
  if (!slot || !slot.failover) {
    throw new Error(`Failed to initialize slot ${config.slotName} with failover support enabled.`);
  }
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Postgres 17 Failover Logical Replication Slot Synchronization Guardrail

Postgres 17 Failover Logical Replication Slot Synchronization Guardrail defines an industrial-grade behavioral standard for backend engineering. Enforces Postgres 17 native failover-enabled logical replication slots and slot synchronization workers across high-availability physical standbys. Prevents unrecoverable downstream CDC stream corruption, message duplication storms, and silent data loss caused by non-synchronized restart LSN positions during database failover events. 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: Unsynchronized Logical Slots Causing Downstream CDC Replication Panics Post-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 DriftUnsynchronized Logical Slots Causing Downstream CDC Replication Panics Post-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 via pg_create_logical_replication_slot() or ALTER_REPLICATION_SLOT in Postgres 17+ environments.

Engineers MUST ALWAYS provision logical replication slots with failover = true via pg_create_logical_replication_slot() or ALTER_REPLICATION_SLOT 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.
2

Engineers MUST configure standby_slot_names on the primary instance to include physical standby replication slots, ensuring WAL segments are retained until both physical standbys and logical consumers advance.

Engineers MUST configure standby_slot_names on the primary instance to include physical standby replication slots, ensuring WAL segments are retained until both physical standbys and logical consumers advance.

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 configure sync_replication_slots = true on all physical standby instances to enable the native slot synchronization background worker.

Engineers MUST configure sync_replication_slots = true on all physical standby instances to enable the native slot synchronization background worker.

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 ensure primary_conninfo on physical replicas specifies dbname to grant the slot sync worker access to sync logical slot state from the primary.

Services MUST ensure primary_conninfo on physical replicas specifies dbname to grant the slot sync worker access to sync logical slot state from the primary.

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

Engineers MUST NOT rely on external orchestration scripts or ad-hoc cron jobs to copy slot state when running on Postgres 17 or higher.

Engineers MUST NOT rely on external orchestration scripts or ad-hoc cron jobs to copy slot state when running on Postgres 17 or higher.

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

CDC consumer services MUST verify slot failover capability during initialization by inspecting pg_replication_slots.failover and pg_replication_slots.synced attributes before consuming changes.

CDC consumer services MUST verify slot failover capability during initialization by inspecting pg_replication_slots.failover and pg_replication_slots.synced attributes before consuming changes.

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 Logical Replication Slot Synchronization Guardrail critical for AI coding assistants?

Enforces Postgres 17 native failover-enabled logical replication slots and slot synchronization workers across high-availability physical standbys. Prevents unrecoverable downstream CDC stream corruption, message duplication storms, and silent data loss caused by non-synchronized restart LSN positions during database failover events. 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 (Unsynchronized Logical Slots Causing Downstream CDC Replication Panics Post-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

Postgres