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 Logical Replication Failover Slot Synchronization & HA Standby Alignment

Enforces failover-enabled logical replication slots and synchronized standby slot coordination introduced in PostgreSQL 17. Guarantees that physical standby replicas maintain synchronized logical decoding slots prior to failover, preventing message loss, slot invalidation, or re-consumption gaps across HA transitions.

Prohibited Anti-Pattern: Unsynchronized Logical Slots and Unconstrained LSN Forwarding Without Physical Standby Alignment

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Postgres 17 Logical Replication Failover Slot Synchronization & HA Standby Alignment - Enforces failover-enabled logical replication slots and synchronized standby slot coordination introduced in PostgreSQL 17. Guarantees that physical standby replicas maintain synchronized logical decoding slots prior to failover, preventing message loss, slot invalidation, or re-consumption gaps across HA transitions.
globs: src/**/*.{ts,js,sql}, infra/**/*.{ts,js,sql}, migrations/**/*.sql
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 Logical Replication Failover Slot Synchronization & HA Standby Alignment

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unsynchronized Logical Slots and Unconstrained LSN Forwarding Without Physical Standby Alignment

## System Constraints
You are a Principal Database Reliability Engineer enforcing PostgreSQL 17 High-Availability standards. Mandate failover slot synchronization (`sync_replication_slots = true`), proper primary slot constraint enforcement (`synchronized_standby_slots`), and explicit `failover = true` flags on all logical decoding slots. Prevent logical replication consumers from reading ahead of physical standby confirmation.

## Strict Guidelines
- Engineers MUST ALWAYS create logical replication slots with `failover => true` (or `ALTER SUBSCRIPTION ... SET (failover = true)`) in PostgreSQL 17+ environments.
- Engineers MUST ALWAYS configure `synchronized_standby_slots` on the primary instance to list physical standby slot names, ensuring logical slots never advance past physical standby flushed LSN.
- Standby replicas MUST enable `sync_replication_slots = on` and configure `hot_standby_feedback = on` to prevent vacuum cleanups of rows needed by logical consumers.
- Application logic MUST verify `sync_state = 'ready'` or `sync_state = 'synced'` on `pg_replication_slots` prior to promoting any physical replica to primary.
- Components NEVER execute unchecked logical decoding promotions without confirming the failover slot has survived and retained valid `confirmed_flush_lsn`.

## Bad vs Good Implementations
### Postgres 17 Failover Slot Creation and Standby Synchronization Check

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Creating a logical replication slot without failover => true causes the slot to be lost when a physical HA failover occurs. Without synchronized_standby_slots, logical consumers can consume WAL changes not yet flushed by physical standbys, making seamless replica promotion impossible.
```typescript
import { Client } from 'pg';

// ANTI-PATTERN: Pre-Postgres 17 pattern without failover flag or standby synchronization
export async function registerLogicalConsumer(client: Client, slotName: string): Promise<void> {
  // Creates an ephemeral or unsynchronized slot that disappears upon physical HA failover
  await client.query(
    `SELECT pg_create_logical_replication_slot($1, 'pgoutput');`,
    [slotName]
  );
  // Subscriber connects immediately without verifying standby slot alignment,
  // leading to silent data-loss or subscriber failure if the primary dies.
}
```

#### Production Standard (Correct)
> **Standard**: Leverages Postgres 17 native failover slot capabilities by specifying failover => true, enforcing synchronized_standby_slots alignment, and validating slot state so standby replicas synchronize logical positions seamlessly across failovers.
```typescript
import { Client } from 'pg';

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

// PRODUCTION INVARIANT: Native Postgres 17 HA slot failover coordination
export async function registerFailoverLogicalSlot(
  primaryClient: Client,
  slotName: string,
  physicalStandbySlot: string
): Promise<ReplicationSlotStatus> {
  // 1. Verify synchronized_standby_slots contains the physical standby
  const { rows: configRows } = await primaryClient.query<{
    setting: string;
  }>("SELECT setting FROM pg_settings WHERE name = 'synchronized_standby_slots';");

  const syncSlots = configRows[0]?.setting?.split(',').map((s) => s.trim()) ?? [];
  if (!syncSlots.includes(physicalStandbySlot)) {
    throw new Error(
      `HA Invariant Violated: physical standby '${physicalStandbySlot}' is missing from synchronized_standby_slots.`
    );
  }

  // 2. Provision logical slot with PG17 failover => true enabled
  await primaryClient.query(
    `SELECT pg_create_logical_replication_slot(
       slot_name => $1,
       plugin => 'pgoutput',
       temporary => false,
       twophase => true,
       failover => true
     );`,
    [slotName]
  );

  // 3. Confirm slot state and failover readiness
  const { rows: slotRows } = await primaryClient.query<{
    slot_name: string;
    plugin: string;
    failover: boolean;
    synced: boolean;
    confirmed_flush_lsn: string;
  }>(
    `SELECT slot_name, plugin, failover, synced, confirmed_flush_lsn
     FROM pg_replication_slots
     WHERE slot_name = $1;`,
    [slotName]
  );

  const created = slotRows[0];
  if (!created || !created.failover) {
    throw new Error(`Logical slot '${slotName}' failed to initialize with failover enabled.`);
  }

  return {
    slotName: created.slot_name,
    plugin: created.plugin,
    failover: created.failover,
    synced: created.synced,
    confirmedFlushLsn: created.confirmed_flush_lsn,
  };
}
```

Recommended MCP Servers (mcp-serverlist.com)

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

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Postgres 17 Logical Replication Failover Slot Synchronization & HA Standby Alignment

Postgres 17 Logical Replication Failover Slot Synchronization & HA Standby Alignment defines an industrial-grade behavioral standard for backend engineering. Enforces failover-enabled logical replication slots and synchronized standby slot coordination introduced in PostgreSQL 17. Guarantees that physical standby replicas maintain synchronized logical decoding slots prior to failover, preventing message loss, slot invalidation, or re-consumption gaps across HA transitions. 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 and Unconstrained LSN Forwarding Without Physical Standby Alignment 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 and Unconstrained LSN Forwarding Without Physical Standby AlignmentCritical
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 => true` (or `ALTER SUBSCRIPTION ... SET (failover = true)`) in PostgreSQL 17+ environments.

Engineers MUST ALWAYS create logical replication slots with `failover => true` (or `ALTER SUBSCRIPTION ... SET (failover = true)`) in PostgreSQL 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 ALWAYS configure `synchronized_standby_slots` on the primary instance to list physical standby slot names, ensuring logical slots never advance past physical standby flushed LSN.

Engineers MUST ALWAYS configure `synchronized_standby_slots` on the primary instance to list physical standby slot names, ensuring logical slots never advance past physical standby flushed LSN.

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 replicas MUST enable `sync_replication_slots = on` and configure `hot_standby_feedback = on` to prevent vacuum cleanups of rows needed by logical consumers.

Standby replicas MUST enable `sync_replication_slots = on` and configure `hot_standby_feedback = on` to prevent vacuum cleanups of rows needed by logical consumers.

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

Application logic MUST verify `sync_state = 'ready'` or `sync_state = 'synced'` on `pg_replication_slots` prior to promoting any physical replica to primary.

Application logic MUST verify `sync_state = 'ready'` or `sync_state = 'synced'` on `pg_replication_slots` prior to promoting any physical replica to 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

Components NEVER execute unchecked logical decoding promotions without confirming the failover slot has survived and retained valid `confirmed_flush_lsn`.

Components NEVER execute unchecked logical decoding promotions without confirming the failover slot has survived and retained valid `confirmed_flush_lsn`.

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 & HA Standby Alignment critical for AI coding assistants?

Enforces failover-enabled logical replication slots and synchronized standby slot coordination introduced in PostgreSQL 17. Guarantees that physical standby replicas maintain synchronized logical decoding slots prior to failover, preventing message loss, slot invalidation, or re-consumption gaps across HA transitions. 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 and Unconstrained LSN Forwarding Without Physical Standby Alignment) 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