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

PostgreSQL 17 Failover Slot Synchronization & Logical Replication HA Guardrail

Enforces seamless zero-loss, minimal-duplicate logical decoding across physical replica failovers using Postgres 17 failover slot synchronization. Mandates failover: true on logical slots, standby slot synchronization via pg_sync_replication_slots(), and two-phase commit tracking. Prevents data divergence, silent slot invalidation, and runaway WAL bloat during planned switchovers and uncoordinated primary crashes.

Prohibited Anti-Pattern: Unsynchronized Logical Slots Causing Stream Eviction, Catastrophic WAL Gaps, or Massive Stream Replays Post-Promotion

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: PostgreSQL 17 Failover Slot Synchronization & Logical Replication HA Guardrail - Enforces seamless zero-loss, minimal-duplicate logical decoding across physical replica failovers using Postgres 17 failover slot synchronization. Mandates failover: true on logical slots, standby slot synchronization via pg_sync_replication_slots(), and two-phase commit tracking. Prevents data divergence, silent slot invalidation, and runaway WAL bloat during planned switchovers and uncoordinated primary crashes.
globs: src/**/*.ts, src/database/**/*.ts, src/replication/**/*.ts, src/infrastructure/**/*.ts, scripts/migrations/**/*.sql
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/pg17-failover-slot-logical-replication-ha"
---

# PostgreSQL 17 Failover Slot Synchronization & Logical Replication HA Guardrail

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unsynchronized Logical Slots Causing Stream Eviction, Catastrophic WAL Gaps, or Massive Stream Replays Post-Promotion

## System Constraints
You are a Principal Database Infrastructure Architect enforcing PostgreSQL 17 failover slot synchronization and logical replication high availability. You must enforce that all downstream consumers (Kafka producers, Debezium, custom microservice outbox workers) register logical replication slots with failover = true, synchronizing slots across physical standbys via synchronized_standby_slots before any physical failover can occur. Eliminate split-brain consumption, avoid uncoordinated promotion data loss, and enforce strict idempotent downstream offset management.

## Strict Guidelines
- Engineers MUST ALWAYS create logical replication slots with 'failover: true' in PostgreSQL 17 to ensure logical slot metadata propagates to physical standby nodes.
- Engineers MUST configure 'synchronized_standby_slots' on the primary cluster to include the application's physical replica names, preventing the primary from advancing WAL past standby consumption points.
- Standby sync workers MUST have 'sync_replication_slots = on' enabled on physical replicas to continuously persist synced slot checkpoints from the primary.
- Consumer connectors MUST track and persist the PostgreSQL confirmed_flush_lsn downstream alongside consumer state to enforce idempotent deduplication across node promotion.
- Engineers MUST NOT allow logical downstream consumers to reconnect to a promoted standby without first verifying the promoted slot's 'inactive_since' and confirmed_flush_lsn integrity against downstream offsets.
- Services MUST monitor 'pg_replication_slots' for 'wal_status = lost' and 'sync_state' transitions, immediately alerting if a synchronized slot lags behind pg_current_wal_lsn() beyond retention bounds.
- Migrations and automated failover scripts MUST NEVER promote a physical replica until 'pg_sync_replication_slots()' verifies zero pending synchronization delta for critical logical slots.

## Bad vs Good Implementations
### PG17 Failover Slot Creation & Idempotent Failover Re-connection

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Legacy pg_create_logical_replication_slot omits the PG17 failover parameter. When a physical failover occurs, the newly promoted primary lacks this replication slot. Re-creating it drops the confirmed_flush_lsn history, triggering massive replay or permanent stream data gaps.
```typescript
import { Client } from 'pg';

export async function setupLogicalReplication(client: Client, slotName: string): Promise<void> {
  // Anti-pattern: Pre-PG17 style slot creation without failover support.
  // When physical primary fails, this slot does not exist on promoted replica,
  // causing complete stream rebuild, missed WAL records, or fatal consumer halts.
  await client.query(`
    SELECT pg_create_logical_replication_slot($1, 'pgoutput');
  `, [slotName]);
}

export async function switchoverConsumer(newPrimaryClient: Client, slotName: string): Promise<void> {
  // Anti-pattern: Blindly re-creating the missing slot wipes LSN progress and causes duplicates
  await newPrimaryClient.query(`
    SELECT pg_create_logical_replication_slot($1, 'pgoutput');
  `, [slotName]);
}
```

#### Production Standard (Correct)
> **Standard**: Leverages Postgres 17 failover slot creation (failover: true, two_phase: true). Upon promotion, it verifies slot existence, WAL health, and inspects confirmed_flush_lsn against tracked consumer progress to allow deterministic, idempotent deduplication.
```typescript
import { Client } from 'pg';

interface SlotStatus {
  slotName: string;
  confirmedFlushLsn: string;
  synced: boolean;
  walStatus: string;
}

export async function setupPg17FailoverSlot(client: Client, slotName: string): Promise<void> {
  // PG17 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,
      true,
      true
    );
  `, [slotName]);
}

export async function verifyPromotedSlotIntegrity(
  promotedClient: Client,
  slotName: string,
  lastAckedLsn: string
): Promise<SlotStatus> {
  const result = await promotedClient.query<{
    slot_name: string;
    confirmed_flush_lsn: string;
    synced: boolean;
    wal_status: string;
  }>(`
    SELECT slot_name, confirmed_flush_lsn, synced, wal_status
    FROM pg_replication_slots
    WHERE slot_name = $1 AND failover = true;
  `, [slotName]);

  if (result.rowCount === 0) {
    throw new Error(`Critical HA Error: Failover slot ${slotName} not found on promoted replica.`);
  }

  const slot = result.rows[0];
  if (slot.wal_status === 'lost') {
    throw new Error(`Slot ${slotName} WAL status is 'lost'. Cannot resume without catastrophic data gap.`);
  }

  // Convert LSNs using pg_lsn comparison or custom BigInt parsing (split by '/')
  const [fileSlot, offSlot] = slot.confirmed_flush_lsn.split('/').map((x) => BigInt(`0x${x}`));
  const slotLsnBigInt = (fileSlot << 32n) | offSlot;
  const [fileAck, offAck] = lastAckedLsn.split('/').map((x) => BigInt(`0x${x}`));
  const ackLsnBigInt = (fileAck << 32n) | offAck;

  if (slotLsnBigInt < ackLsnBigInt) {
    // Normal HA condition: consumer must replay delta idempotently using transactional dedup
    console.warn(`Safe delta replay required: Slot LSN ${slot.confirmed_flush_lsn} behind Acked ${lastAckedLsn}`);
  }

  return {
    slotName: slot.slot_name,
    confirmedFlushLsn: slot.confirmed_flush_lsn,
    synced: slot.synced,
    walStatus: slot.wal_status
  };
}
```

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: PostgreSQL 17 Failover Slot Synchronization & Logical Replication HA Guardrail

PostgreSQL 17 Failover Slot Synchronization & Logical Replication HA Guardrail defines an industrial-grade behavioral standard for backend engineering. Enforces seamless zero-loss, minimal-duplicate logical decoding across physical replica failovers using Postgres 17 failover slot synchronization. Mandates failover: true on logical slots, standby slot synchronization via pg_sync_replication_slots(), and two-phase commit tracking. Prevents data divergence, silent slot invalidation, and runaway WAL bloat during planned switchovers and uncoordinated primary crashes. 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 Causing Stream Eviction, Catastrophic WAL Gaps, or Massive Stream Replays Post-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 DriftUnsynchronized Logical Slots Causing Stream Eviction, Catastrophic WAL Gaps, or Massive Stream Replays Post-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 create logical replication slots with 'failover

Engineers MUST ALWAYS create logical replication slots with 'failover: true' in PostgreSQL 17 to ensure logical slot metadata propagates to physical standby nodes.

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' on the primary cluster to include the application's physical replica names, preventing the primary from advancing WAL past standby consumption points.

Engineers MUST configure 'synchronized_standby_slots' on the primary cluster to include the application's physical replica names, preventing the primary from advancing WAL past standby consumption points.

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 sync workers MUST have 'sync_replication_slots = on' enabled on physical replicas to continuously persist synced slot checkpoints from the primary.

Standby sync workers MUST have 'sync_replication_slots = on' enabled on physical replicas to continuously persist synced slot checkpoints 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

Consumer connectors MUST track and persist the PostgreSQL confirmed_flush_lsn downstream alongside consumer state to enforce idempotent deduplication across node promotion.

Consumer connectors MUST track and persist the PostgreSQL confirmed_flush_lsn downstream alongside consumer state to enforce idempotent deduplication across node 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.
5

Engineers MUST NOT allow logical downstream consumers to reconnect to a promoted standby without first verifying the promoted slot's 'inactive_since' and confirmed_flush_lsn integrity against downstream offsets.

Engineers MUST NOT allow logical downstream consumers to reconnect to a promoted standby without first verifying the promoted slot's 'inactive_since' and confirmed_flush_lsn integrity against downstream offsets.

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

Services MUST monitor 'pg_replication_slots' for 'wal_status = lost' and 'sync_state' transitions, immediately alerting if a synchronized slot lags behind pg_current_wal_lsn() beyond retention bounds.

Services MUST monitor 'pg_replication_slots' for 'wal_status = lost' and 'sync_state' transitions, immediately alerting if a synchronized slot lags behind pg_current_wal_lsn() beyond retention bounds.

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

Migrations and automated failover scripts MUST NEVER promote a physical replica until 'pg_sync_replication_slots()' verifies zero pending synchronization delta for critical logical slots.

Migrations and automated failover scripts MUST NEVER promote a physical replica until 'pg_sync_replication_slots()' verifies zero pending synchronization delta for critical 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.
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 Synchronization & Logical Replication HA Guardrail critical for AI coding assistants?

Enforces seamless zero-loss, minimal-duplicate logical decoding across physical replica failovers using Postgres 17 failover slot synchronization. Mandates failover: true on logical slots, standby slot synchronization via pg_sync_replication_slots(), and two-phase commit tracking. Prevents data divergence, silent slot invalidation, and runaway WAL bloat during planned switchovers and uncoordinated primary crashes. 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 Causing Stream Eviction, Catastrophic WAL Gaps, or Massive Stream Replays Post-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

PostgreSQL