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

Postgres 17 Logical Replication Failover Slot Synchronization Boundary

Enforces strict failover configuration and synchronization boundaries for logical replication slots in PostgreSQL 17. Guarantees zero data loss and prevents duplicated change data capture (CDC) streaming events during physical replica failover by requiring failover-enabled slots and synchronized standby slot verification before consumer consumption.

Prohibited Anti-Pattern: Unsynchronized Standby Failovers Causing Slot Dropping, Re-Streaming Storms, or Data Gaps

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Postgres 17 Logical Replication Failover Slot Synchronization Boundary - Enforces strict failover configuration and synchronization boundaries for logical replication slots in PostgreSQL 17. Guarantees zero data loss and prevents duplicated change data capture (CDC) streaming events during physical replica failover by requiring failover-enabled slots and synchronized standby slot verification before consumer consumption.
globs: src/infra/db/**/*.ts, src/replication/**/*.ts, src/services/cdc/**/*.ts, src/services/outbox/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/postgres-17-logical-failover-slot-sync-production-standard"
---

# Postgres 17 Logical Replication Failover Slot Synchronization Boundary

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unsynchronized Standby Failovers Causing Slot Dropping, Re-Streaming Storms, or Data Gaps

## System Constraints
You are a Principal Database Architect and Infrastructure Reliability Engineer enforcing Postgres 17 Logical Replication Failover Slot Synchronization Boundaries. Mandate that all logical replication slots utilize failover-enabled semantics (`failover = true`), standby synchronization checks, and strict LSN validation during cluster transitions to prevent silent event loss and massive re-ingestion storms.

## Strict Guidelines
- Engineers MUST ALWAYS create logical replication slots with `failover: true` (PostgreSQL 17+) when downstream consumers require uninterrupted CDC across HA failovers.
- Engineers MUST NOT allow CDC consumers to acknowledge LSN progression without transactional deduplication boundaries and verified slot sync states on physical standbys.
- Database connection orchestrators MUST verify that `pg_replication_slots.sync_state` is 'synced' or 'stream' before allowing consumer reconnects following a physical primary promotion.
- Infrastructure configurations MUST guarantee that the primary database specifies physical standby replication slots within `synchronized_standby_slots` before advancing logical subscribers.
- Services MUST gracefully reject failover transitions if a promoted replica's `confirmed_flush_lsn` is behind consumer processed state without explicit idempotent deduplication handling.

## Bad vs Good Implementations
### PostgreSQL 17 Logical Replication Slot Initialization & Verification

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Creating a logical slot without the Postgres 17 `failover` parameter means the slot will not sync to physical standbys. When the standby is promoted, the slot ceases to exist, leading to unrecoverable ingestion gaps or event replay floods.
```typescript
import { Client } from 'pg';

export async function initReplicationSlot(client: Client, slotName: string): Promise<void> {
  // Anti-pattern: Pre-PG17 style slot creation lacks failover synchronization.
  // In a cluster failover, this slot will not exist on the promoted physical standby,
  // causing consumers to either fail fatally or re-stream from beginning of WAL, generating duplicates.
  await client.query(
    `SELECT pg_create_logical_replication_slot($1, 'pgoutput');`,
    [slotName]
  );
}
```

#### Production Standard (Correct)
> **Standard**: Explicitly passes the 5th boolean parameter `failover = true` in `pg_create_logical_replication_slot`, and introduces an assertion utility ensuring the slot is recognized and synchronized across physical cluster transitions before consumer startup.
```typescript
import { Client } from 'pg';

interface ReplicationSlotConfig {
  slotName: string;
  plugin?: string;
  isFailoverEnabled?: boolean;
}

export async function initPostgres17LogicalSlot(
  client: Client,
  config: ReplicationSlotConfig
): Promise<{ slotName: string; consistentPoint: string }> {
  const { slotName, plugin = 'pgoutput', isFailoverEnabled = true } = config;

  // Assert PostgreSQL 17+ server version
  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('Failover-synchronized logical slots require PostgreSQL 17 or higher.');
  }

  // PG17: pg_create_logical_replication_slot(slot_name, plugin, temporary, two_phase, failover)
  const slotQuery = `
    SELECT slot_name, consistent_point 
    FROM pg_create_logical_replication_slot(
      $1::name, 
      $2::name, 
      false, 
      false, 
      $3::boolean
    );
  `;
  const result = await client.query(slotQuery, [slotName, plugin, isFailoverEnabled]);

  return {
    slotName: result.rows[0].slot_name,
    consistentPoint: result.rows[0].consistent_point,
  };
}

export async function assertFailoverSlotReady(
  client: Client,
  slotName: string
): Promise<boolean> {
  const query = `
    SELECT slot_name, failover, sync_state 
    FROM pg_replication_slots 
    WHERE slot_name = $1;
  `;
  const res = await client.query(query, [slotName]);
  const slot = res.rows[0];
  
  if (!slot) {
    throw new Error(`Logical replication slot ${slotName} not found.`);
  }

  // When connecting to a standby or newly promoted node, ensure slot is failover-enabled
  // and not stuck in an un-synced state
  return slot.failover === true && (slot.sync_state === null || slot.sync_state === 'synced');
}
```

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 Synchronization Boundary

Postgres 17 Logical Replication Failover Slot Synchronization Boundary defines an industrial-grade behavioral standard for backend engineering. Enforces strict failover configuration and synchronization boundaries for logical replication slots in PostgreSQL 17. Guarantees zero data loss and prevents duplicated change data capture (CDC) streaming events during physical replica failover by requiring failover-enabled slots and synchronized standby slot verification before consumer consumption. 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 Standby Failovers Causing Slot Dropping, Re-Streaming Storms, or Data Gaps 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 Standby Failovers Causing Slot Dropping, Re-Streaming Storms, or Data GapsCritical
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

Engineers MUST ALWAYS create logical replication slots with `failover: true` (PostgreSQL 17+) when downstream consumers require uninterrupted CDC across HA failovers.

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 CDC consumers to acknowledge LSN progression without transactional deduplication boundaries and verified slot sync states on physical standbys.

Engineers MUST NOT allow CDC consumers to acknowledge LSN progression without transactional deduplication boundaries and verified slot sync states on 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.
3

Database connection orchestrators MUST verify that `pg_replication_slots.sync_state` is 'synced' or 'stream' before allowing consumer reconnects following a physical primary promotion.

Database connection orchestrators MUST verify that `pg_replication_slots.sync_state` is 'synced' or 'stream' before allowing consumer reconnects following a physical primary 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.
4

Infrastructure configurations MUST guarantee that the primary database specifies physical standby replication slots within `synchronized_standby_slots` before advancing logical subscribers.

Infrastructure configurations MUST guarantee that the primary database specifies physical standby replication slots within `synchronized_standby_slots` before advancing logical subscribers.

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 gracefully reject failover transitions if a promoted replica's `confirmed_flush_lsn` is behind consumer processed state without explicit idempotent deduplication handling.

Services MUST gracefully reject failover transitions if a promoted replica's `confirmed_flush_lsn` is behind consumer processed state without explicit idempotent deduplication handling.

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 Synchronization Boundary critical for AI coding assistants?

Enforces strict failover configuration and synchronization boundaries for logical replication slots in PostgreSQL 17. Guarantees zero data loss and prevents duplicated change data capture (CDC) streaming events during physical replica failover by requiring failover-enabled slots and synchronized standby slot verification before consumer consumption. 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 Standby Failovers Causing Slot Dropping, Re-Streaming Storms, or Data Gaps) 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