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

PostgreSQL 17 Failover Slot Logical Replication High-Availability Standard

Enforces PostgreSQL 17 failover slot logical replication topologies to guarantee zero data loss, prevent downstream consumer divergence, and eliminate full-table resynchronizations during primary failover. Mandates synchronized slots across streaming physical standbys, explicit pg_sync_replication_slots sync mechanics, coordinated LSN tracking, and verified failover validation before promoting standby targets.

Prohibited Anti-Pattern: Creating unmanaged logical replication slots without pg_create_logical_replication_slot(failover => true) and synchronized standby slots

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: PostgreSQL 17 Failover Slot Logical Replication High-Availability Standard - Enforces PostgreSQL 17 failover slot logical replication topologies to guarantee zero data loss, prevent downstream consumer divergence, and eliminate full-table resynchronizations during primary failover. Mandates synchronized slots across streaming physical standbys, explicit pg_sync_replication_slots sync mechanics, coordinated LSN tracking, and verified failover validation before promoting standby targets.
globs: src/database/**/*.{ts,js,sql}, infrastructure/**/*.{ts,js,tf,sql}, migrations/**/*.{ts,js,sql}, scripts/**/*.{ts,js,sh}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/pg17-failover-slot-logical-replication-standard"
---

# PostgreSQL 17 Failover Slot Logical Replication High-Availability Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Creating unmanaged logical replication slots without pg_create_logical_replication_slot(failover => true) and synchronized standby slots

## System Constraints
You are a Principal Database Architect enforcing PostgreSQL 17 failover-enabled logical replication standards. In PostgreSQL 17, logical replication failover is natively supported through failover-enabled replication slots (`failover = true`) and slot synchronization (`synchronized_standby_slots`, `sync_replication_slots = true`). You must ensure that applications, migration scripts, orchestration controllers, and database provisioning logic never create standalone logical slots that disconnect or corrupt subscriber state upon failover. Mandate proper failover parameter enablement on primary and standby instances, verify synchronized LSN progression, require subscriber connection string updates to point to newly promoted standbys without recreation of subscriptions, and reject unsafe slot drops.

## Strict Guidelines
- Engineers MUST ALWAYS provision logical replication slots with `failover => true` on PostgreSQL 17 primaries (e.g., `SELECT pg_create_logical_replication_slot('slot_name', 'pgoutput', false, false, true)`).
- Engineers MUST configure `synchronized_standby_slots` in `postgresql.conf` on the primary to include all physical streaming standby application names before allowing subscribers to advance.
- Engineers MUST configure `sync_replication_slots = on` on physical standby nodes to ensure standby instances continuously sync logical slot metadata and confirmed_flush_lsn from the primary.
- Engineers MUST NOT drop, re-create, or issue `ALTER SUBSCRIPTION ... REFRESH PUBLICATION` without verifying that the downstream subscriber's confirmed LSN has been synchronized to the newly promoted standby.
- Database orchestration scripts MUST verify `pg_replication_slots.failover = true` and `pg_replication_slots.synced = true` on the target standby prior to issuing promotion (`pg_ctl promote` or `SELECT pg_promote()`).
- Subscribers MUST connect with `failover_states` or configure connection retries across primary/standby pools via modern libpq connection strings (`target_session_attrs=read-write`) without dropping logical subscription state.

## Bad vs Good Implementations
### Configuring PostgreSQL 17 Failover Slot Logical Replication Orchestration

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Creating a logical replication slot without explicitly setting failover=true means the slot's metadata and confirmed LSN are not tracked by physical standbys. If the primary crashes and a standby is promoted, the slot disappears, corrupting downstream replication progress and forcing costly WAL re-ingestion or full-table copies.
```typescript
import { Client } from 'pg';

// Anti-pattern: Creates legacy non-failover slot and subscribes without standby coordination
export async function setupLogicalReplication(primaryClient: Client, subscriberClient: Client) {
  // Creates legacy slot without failover flag (default failover = false in PG 17)
  await primaryClient.query(`
    SELECT pg_create_logical_replication_slot('analytics_slot', 'pgoutput');
  `);

  // Subscriber directly consumes; on primary failover, analytics_slot does not exist on standby
  // causing subscriber crash and necessitating full table re-sync
  await subscriberClient.query(`
    CREATE SUBSCRIPTION analytics_sub
    CONNECTION 'host=primary.internal dbname=app user=rep'
    PUBLICATION app_events
    WITH (create_slot = false, slot_name = 'analytics_slot');
  `);
}
```

#### Production Standard (Correct)
> **Standard**: Explicitly passes failover => true to pg_create_logical_replication_slot, validates that the physical standby is configured in synchronized_standby_slots, verifies synced = true on the standby node, and leverages a multi-host connection string so subscriber seamlessly fails over without LSN drift or duplicate events.
```typescript
import { Client } from 'pg';

export async function setupLogicalReplication(primaryClient: Client, standbyClient: Client, subscriberClient: Client) {
  // 1. Verify primary includes physical standby in synchronized_standby_slots
  const syncSlotsRes = await primaryClient.query<{ synchronized_standby_slots: string }>(
    `SHOW synchronized_standby_slots;`
  );
  if (!syncSlotsRes.rows[0].synchronized_standby_slots.includes('standby_node_1')) {
    throw new Error('standby_node_1 must be present in synchronized_standby_slots on primary');
  }

  // 2. Create failover-enabled logical slot on PG17 primary
  // signature: pg_create_logical_replication_slot(slot_name, plugin, temporary, two_phase, failover)
  await primaryClient.query(`
    SELECT pg_create_logical_replication_slot(
      'analytics_slot',
      'pgoutput',
      false,
      false,
      true
    );
  `);

  // 3. Confirm slot synchronization state on physical standby
  const standbySlotRes = await standbyClient.query<{ slot_name: string; failover: boolean; synced: boolean }>(
    `SELECT slot_name, failover, synced FROM pg_replication_slots WHERE slot_name = 'analytics_slot';`
  );
  if (!standbySlotRes.rows[0]?.synced) {
    throw new Error('Logical replication slot is not yet synced on standby');
  }

  // 4. Create subscription connecting via multi-host connection string targeting read-write master
  await subscriberClient.query(`
    CREATE SUBSCRIPTION analytics_sub
    CONNECTION 'postgresql://[email protected]:5432,standby.internal:5432/app?target_session_attrs=read-write'
    PUBLICATION app_events
    WITH (create_slot = false, slot_name = 'analytics_slot', failover = true);
  `);
}
```

Recommended MCP Servers (mcp-serverlist.com)

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

Architectural Specification & Invariant Rationale

Architectural Invariant Design: PostgreSQL 17 Failover Slot Logical Replication High-Availability Standard

PostgreSQL 17 Failover Slot Logical Replication High-Availability Standard defines an industrial-grade behavioral standard for backend engineering. Enforces PostgreSQL 17 failover slot logical replication topologies to guarantee zero data loss, prevent downstream consumer divergence, and eliminate full-table resynchronizations during primary failover. Mandates synchronized slots across streaming physical standbys, explicit pg_sync_replication_slots sync mechanics, coordinated LSN tracking, and verified failover validation before promoting standby targets. 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 unmanaged logical replication slots without pg_create_logical_replication_slot(failover => true) and synchronized standby slots 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 unmanaged logical replication slots without pg_create_logical_replication_slot(failover => true) and synchronized standby slotsCritical
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` on PostgreSQL 17 primaries (e.g., `SELECT pg_create_logical_replication_slot('slot_name', 'pgoutput', false, false, true)`).

Engineers MUST ALWAYS provision logical replication slots with `failover => true` on PostgreSQL 17 primaries (e.g., `SELECT pg_create_logical_replication_slot('slot_name', 'pgoutput', false, false, true)`).

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 `synchronized_standby_slots` in `postgresql.conf` on the primary to include all physical streaming standby application names before allowing subscribers to advance.

Engineers MUST configure `synchronized_standby_slots` in `postgresql.conf` on the primary to include all physical streaming standby application names before allowing subscribers to 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 = on` on physical standby nodes to ensure standby instances continuously sync logical slot metadata and confirmed_flush_lsn from the primary.

Engineers MUST configure `sync_replication_slots = on` on physical standby nodes to ensure standby instances continuously sync logical slot metadata and confirmed_flush_lsn 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.
4

Engineers MUST NOT drop, re-create, or issue `ALTER SUBSCRIPTION ... REFRESH PUBLICATION` without verifying that the downstream subscriber's confirmed LSN has been synchronized to the newly promoted standby.

Engineers MUST NOT drop, re-create, or issue `ALTER SUBSCRIPTION ... REFRESH PUBLICATION` without verifying that the downstream subscriber's confirmed LSN has been synchronized to the newly promoted standby.

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

Database orchestration scripts MUST verify `pg_replication_slots.failover = true` and `pg_replication_slots.synced = true` on the target standby prior to issuing promotion (`pg_ctl promote` or `SELECT pg_promote()`).

Database orchestration scripts MUST verify `pg_replication_slots.failover = true` and `pg_replication_slots.synced = true` on the target standby prior to issuing promotion (`pg_ctl promote` or `SELECT pg_promote()`).

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

Subscribers MUST connect with `failover_states` or configure connection retries across primary/standby pools via modern libpq connection strings (`target_session_attrs=read-write`) without dropping logical subscription state.

Subscribers MUST connect with `failover_states` or configure connection retries across primary/standby pools via modern libpq connection strings (`target_session_attrs=read-write`) without dropping logical subscription state.

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 PostgreSQL 17 Failover Slot Logical Replication High-Availability Standard critical for AI coding assistants?

Enforces PostgreSQL 17 failover slot logical replication topologies to guarantee zero data loss, prevent downstream consumer divergence, and eliminate full-table resynchronizations during primary failover. Mandates synchronized slots across streaming physical standbys, explicit pg_sync_replication_slots sync mechanics, coordinated LSN tracking, and verified failover validation before promoting standby targets. 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 unmanaged logical replication slots without pg_create_logical_replication_slot(failover => true) and synchronized standby slots) 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

PostgreSQL