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-control

Postgres 17 Synchronized Logical Replication Slot Failover Protocol

Enforces Postgres 17 native failover-enabled logical replication slots and synchronized standby slot topologies across high-availability clusters. Guarantees that physical standby nodes maintain synchronized logical replication slot state (confirmed_flush_lsn) prior to cluster failovers. Eliminates message data loss, catastrophic duplicate streaming replays, and downstream consumer corruption during automated Patroni or Kubernetes orchestrator promotions.

Prohibited Anti-Pattern: Provisioning Logical Replication Slots Without Failover Capabilities and Uncoordinated Physical Standby Promotion

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Postgres 17 Synchronized Logical Replication Slot Failover Protocol - Enforces Postgres 17 native failover-enabled logical replication slots and synchronized standby slot topologies across high-availability clusters. Guarantees that physical standby nodes maintain synchronized logical replication slot state (confirmed_flush_lsn) prior to cluster failovers. Eliminates message data loss, catastrophic duplicate streaming replays, and downstream consumer corruption during automated Patroni or Kubernetes orchestrator promotions.
globs: src/**/*.{ts,js,py,go,sql}, infra/**/*.{tf,yaml,yml,sql}, migrations/**/*.{sql,ts}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/postgres-17-logical-replication-failover-control"
---

# Postgres 17 Synchronized Logical Replication Slot Failover Protocol

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Provisioning Logical Replication Slots Without Failover Capabilities and Uncoordinated Physical Standby Promotion

## System Constraints
You are a Principal Database Architect and Distributed Systems Engineer enforcing Postgres 17 High-Throughput Logical Replication Failover Invariants. PostgreSQL 17 introduces native support for synchronized logical replication slots between primary and physical standby servers (`sync_replication_slots = true`, `failover = true` parameter in slot creation, and `synchronized_standby_slots`). You MUST eliminate obsolete legacy workarounds, prevent uncoordinated CDC stream processing, and enforce exact replication slot configuration to guarantee zero message loss and minimize replay windows during failover.

## Strict Guidelines
- Engineers MUST ALWAYS provision logical replication slots with the Postgres 17 `failover` parameter set to `true` via `pg_create_logical_replication_slot(slot_name, plugin, temporary, two_phase, failover)`.
- Engineers MUST ALWAYS configure `synchronized_standby_slots` on the primary instance to include physical standby replication slots before publishing downstream logical changes.
- Standby database configurations MUST enable `sync_replication_slots = on` and `hot_standby_feedback = on` in postgresql.conf to allow automatic background synchronization of logical slots.
- Downstream logical consumers and CDC agents MUST NEVER connect to a logical replication slot on a promoted replica until verifying that `pg_replication_slots.synced` is true or the node has completed promotion without slot rewind.
- Consumers MUST maintain deterministic, idempotent state offsets (e.g., commit LSN and transactional sequence bounds) to absorb inevitable replay bounded between `confirmed_flush_lsn` and `restart_lsn` upon failover promotion.
- Engineers MUST NOT allow logical replication slots to be created on primary nodes without monitoring `pg_replication_slots.sync_state` to prevent lag accumulation from blocking primary WAL cleanup.

## Bad vs Good Implementations
### Postgres 17 Logical Replication Slot Provisioning & Consumer Failover Orchestration

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Creating the slot with legacy signatures defaults 'failover' to false. Physical standbys will not synchronize the slot, leaving downstream consumers stranded with missing slots upon failover, forcing manual rewinds or resulting in catastrophic message duplication and lost consumer state.
```typescript
import { Client } from 'pg';

export async function setupLogicalReplication(client: Client, slotName: string): Promise<void> {
  // Flaw 1: Legacy slot creation without PG17 failover parameter
  // When primary fails over, this slot does not exist on the promoted standby
  await client.query(`
    SELECT pg_create_logical_replication_slot($1, 'pgoutput');
  `, [slotName]);

  // Flaw 2: Initiating consumer connection without validating cluster slot synchronization status
  console.log(`Logical replication slot ${slotName} created without standby sync.`);
}
```

#### Production Standard (Correct)
> **Standard**: Leverages Postgres 17 native failover control: checks that physical standby slots are tracked in synchronized_standby_slots, creates the slot with failover=true (5th parameter), and validates runtime replication slot state before streaming.
```typescript
import { Client } from 'pg';

export interface SlotSyncStatus {
  slotName: string;
  plugin: string;
  synced: boolean;
  failover: boolean;
  confirmedFlushLsn: string;
}

export async function setupFailoverSafeReplicationSlot(
  client: Client,
  slotName: string,
  physicalStandbySlotName: string
): Promise<void> {
  // Step 1: Verify primary has physical standby configured in synchronized_standby_slots
  const syncSettingRes = await client.query<{ setting: string }>(
    "SELECT current_setting('synchronized_standby_slots') AS setting;"
  );
  
  const configuredSlots = syncSettingRes.rows[0]?.setting?.split(',').map((s: string) => s.trim()) ?? [];
  if (!configuredSlots.includes(physicalStandbySlotName) && !configuredSlots.includes('*')) {
    throw new Error(
      `Primary synchronized_standby_slots does not contain '${physicalStandbySlotName}'. Failover safety compromised.`
    );
  }

  // Step 2: Create logical replication slot with Postgres 17 failover parameter enabled
  // 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
     );`,
    [slotName]
  );

  // Step 3: Validate slot metadata guarantees failover readiness
  const slotCheck = await client.query<SlotSyncStatus>(
    `SELECT slot_name AS "slotName",
            plugin,
            failover,
            confirmed_flush_lsn AS "confirmedFlushLsn"
     FROM pg_replication_slots
     WHERE slot_name = $1;`,
    [slotName]
  );

  const slot = slotCheck.rows[0];
  if (!slot || !slot.failover) {
    throw new Error(`Failed to initialize Postgres 17 failover-capable slot for '${slotName}'.`);
  }
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Postgres 17 Synchronized Logical Replication Slot Failover Protocol

Postgres 17 Synchronized Logical Replication Slot Failover Protocol defines an industrial-grade behavioral standard for backend engineering. Enforces Postgres 17 native failover-enabled logical replication slots and synchronized standby slot topologies across high-availability clusters. Guarantees that physical standby nodes maintain synchronized logical replication slot state (confirmed_flush_lsn) prior to cluster failovers. Eliminates message data loss, catastrophic duplicate streaming replays, and downstream consumer corruption during automated Patroni or Kubernetes orchestrator 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: Provisioning Logical Replication Slots Without Failover Capabilities and Uncoordinated Physical Standby 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 DriftProvisioning Logical Replication Slots Without Failover Capabilities and Uncoordinated Physical Standby 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 provision logical replication slots with the Postgres 17 `failover` parameter set to `true` via `pg_create_logical_replication_slot(slot_name, plugin, temporary, two_phase, failover)`.

Engineers MUST ALWAYS provision logical replication slots with the Postgres 17 `failover` parameter set to `true` via `pg_create_logical_replication_slot(slot_name, plugin, temporary, two_phase, failover)`.

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 ALWAYS configure `synchronized_standby_slots` on the primary instance to include physical standby replication slots before publishing downstream logical changes.

Engineers MUST ALWAYS configure `synchronized_standby_slots` on the primary instance to include physical standby replication slots before publishing downstream logical 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.
3

Standby database configurations MUST enable `sync_replication_slots = on` and `hot_standby_feedback = on` in postgresql.conf to allow automatic background synchronization of logical slots.

Standby database configurations MUST enable `sync_replication_slots = on` and `hot_standby_feedback = on` in postgresql.conf to allow automatic background synchronization of logical 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

Downstream logical consumers and CDC agents MUST NEVER connect to a logical replication slot on a promoted replica until verifying that `pg_replication_slots.synced` is true or the node has completed promotion without slot rewind.

Downstream logical consumers and CDC agents MUST NEVER connect to a logical replication slot on a promoted replica until verifying that `pg_replication_slots.synced` is true or the node has completed promotion without slot rewind.

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

Consumers MUST maintain deterministic, idempotent state offsets (e.g., commit LSN and transactional sequence bounds) to absorb inevitable replay bounded between `confirmed_flush_lsn` and `restart_lsn` upon failover promotion.

Consumers MUST maintain deterministic, idempotent state offsets (e.g., commit LSN and transactional sequence bounds) to absorb inevitable replay bounded between `confirmed_flush_lsn` and `restart_lsn` upon failover 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.
6

Engineers MUST NOT allow logical replication slots to be created on primary nodes without monitoring `pg_replication_slots.sync_state` to prevent lag accumulation from blocking primary WAL cleanup.

Engineers MUST NOT allow logical replication slots to be created on primary nodes without monitoring `pg_replication_slots.sync_state` to prevent lag accumulation from blocking primary WAL cleanup.

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 Synchronized Logical Replication Slot Failover Protocol critical for AI coding assistants?

Enforces Postgres 17 native failover-enabled logical replication slots and synchronized standby slot topologies across high-availability clusters. Guarantees that physical standby nodes maintain synchronized logical replication slot state (confirmed_flush_lsn) prior to cluster failovers. Eliminates message data loss, catastrophic duplicate streaming replays, and downstream consumer corruption during automated Patroni or Kubernetes orchestrator 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 (Provisioning Logical Replication Slots Without Failover Capabilities and Uncoordinated Physical Standby 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