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

Postgres 17 Logical Replication Failover Slot Sync Standard

Enforces Postgres 17 native logical replication slot synchronization across physical standbys using 'failover = true' and 'sync_replication_slots'. Eliminates LSN divergence, silent data loss, and downstream message replay storms in Change Data Capture (CDC) architectures during automated high-availability failover events.

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

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Postgres 17 Logical Replication Failover Slot Sync Standard - Enforces Postgres 17 native logical replication slot synchronization across physical standbys using 'failover = true' and 'sync_replication_slots'. Eliminates LSN divergence, silent data loss, and downstream message replay storms in Change Data Capture (CDC) architectures during automated high-availability failover events.
globs: src/**/*.ts, src/**/*.sql, migrations/**/*.sql, infra/**/*.tf, infra/**/*.conf
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/postgres-17-logical-replication-failover-slot-sync-postgres-17-logi-326"
---

# Postgres 17 Logical Replication Failover Slot Sync Standard

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

## System Constraints
You are a Principal Software Architect enforcing the Postgres 17 Logical Replication Failover Slot Sync Standard. Mandate that all logical replication slots used by downstream consumers (e.g., Debezium, custom CDC daemons, audit pipelines) are created with 'failover = true' and that physical standbys enable 'sync_replication_slots = on' alongside primary slot coordination via 'synchronized_standby_slots'. Forbid legacy PG16-style manual slot copy hacks or unflagged logical slot creation in production architectures.

## Strict Guidelines
- Engineers MUST ALWAYS set failover = true when invoking pg_create_logical_replication_slot() or creating replication slots via client libraries on Postgres 17+.
- Engineers MUST NOT allow logical replication consumers to connect to physical standbys unless the slot has synced status verified via pg_replication_slots.
- Database infrastructure configurations MUST define synchronized_standby_slots on the primary to prevent the primary's WAL truncation before physical standbys consume and advance the logical slot position.
- Standby configurations MUST enable sync_replication_slots = on with a valid primary_conninfo containing dbname to permit the slotsync worker to run.
- CDC consumer initialization code MUST verify confirmed_flush_lsn and synchronization flags prior to acknowledging ingestion boundaries after a cluster failover or connection redirection.

## Bad vs Good Implementations
### Configuring Postgres 17 Logical Replication Slot with Failover Protection in CDC Driver

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Creating a logical replication slot without specifying failover = true prevents Postgres 17 physical standbys from synchronizing the slot metadata and LSN progress. If the primary node fails, promoted standbys will either miss the slot entirely or contain a stale state, forcing an unbounded replay storm or complete pipeline failure.
```typescript
import { Client } from 'pg';

export async function initCdcPipeline(client: Client, slotName: string): Promise<void> {
  // Flaw: Omits PG17 failover flag. Slot will NOT be synchronized to physical standbys.
  // Upon cluster failover, the slot vanishes or falls behind, causing catastrophic message replay.
  await client.query(`
    SELECT * FROM pg_create_logical_replication_slot(
      $1,
      'pgoutput'
    );
  `, [slotName]);
}
```

#### Production Standard (Correct)
> **Standard**: Explicitly passes failover => true during slot creation in Postgres 17, and uses pg_alter_replication_slot() to correct existing slots. This ensures the physical standby's slotsync worker synchronizes the confirmed_flush_lsn, allowing smooth zero-loss, minimal-replay reconnections upon automated failovers.
```typescript
import { Client } from 'pg';

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

export async function initCdcPipeline(client: Client, slotName: string): Promise<void> {
  // Invariant: Verify Postgres version supports native slot synchronization (>= 170000)
  const versionRes = await client.query<{ server_version_num: string }>('SHOW server_version_num;');
  const version = parseInt(versionRes.rows[0].server_version_num, 10);
  if (version < 170000) {
    throw new Error(`Postgres 17+ required for failover slot sync. Found: ${version}`);
  }

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

  if (existing.rowCount && existing.rowCount > 0) {
    const slot = existing.rows[0];
    if (!slot.failover) {
      // Invariant: Alter existing slot to enable failover persistence
      await client.query('SELECT pg_alter_replication_slot($1, failover => true);', [slotName]);
    }
    return;
  }

  // Invariant: Explicitly create logical replication slot with failover enabled in PG17
  await client.query(`
    SELECT * FROM pg_create_logical_replication_slot(
      slot_name => $1,
      plugin => 'pgoutput',
      temporary => false,
      two_phase => false,
      failover => true
    );
  `, [slotName]);
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Postgres 17 Logical Replication Failover Slot Sync Standard

Postgres 17 Logical Replication Failover Slot Sync Standard defines an industrial-grade behavioral standard for backend engineering. Enforces Postgres 17 native logical replication slot synchronization across physical standbys using 'failover = true' and 'sync_replication_slots'. Eliminates LSN divergence, silent data loss, and downstream message replay storms in Change Data Capture (CDC) architectures during automated high-availability 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: Creating Logical Slots Without Failover Synchronization Causing Catastrophic CDC Replay on 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 Replay on 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 set failover = true when invoking pg_create_logical_replication_slot() or creating replication slots via client libraries on Postgres 17+.

Engineers MUST ALWAYS set failover = true when invoking pg_create_logical_replication_slot() or creating replication slots via client libraries on Postgres 17+.

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 allow logical replication consumers to connect to physical standbys unless the slot has synced status verified via pg_replication_slots.

Engineers MUST NOT allow logical replication consumers to connect to physical standbys unless the slot has synced status verified via pg_replication_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.
3

Database infrastructure configurations MUST define synchronized_standby_slots on the primary to prevent the primary's WAL truncation before physical standbys consume and advance the logical slot position.

Database infrastructure configurations MUST define synchronized_standby_slots on the primary to prevent the primary's WAL truncation before physical standbys consume and advance the logical slot position.

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

Standby configurations MUST enable sync_replication_slots = on with a valid primary_conninfo containing dbname to permit the slotsync worker to run.

Standby configurations MUST enable sync_replication_slots = on with a valid primary_conninfo containing dbname to permit the slotsync worker to run.

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

CDC consumer initialization code MUST verify confirmed_flush_lsn and synchronization flags prior to acknowledging ingestion boundaries after a cluster failover or connection redirection.

CDC consumer initialization code MUST verify confirmed_flush_lsn and synchronization flags prior to acknowledging ingestion boundaries after a cluster failover or connection redirection.

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 Failover Slot Sync Standard critical for AI coding assistants?

Enforces Postgres 17 native logical replication slot synchronization across physical standbys using 'failover = true' and 'sync_replication_slots'. Eliminates LSN divergence, silent data loss, and downstream message replay storms in Change Data Capture (CDC) architectures during automated high-availability 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 (Creating Logical Slots Without Failover Synchronization Causing Catastrophic CDC Replay on 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