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

PostgreSQL 17 Logical Replication Failover Slot Synchronization Invariants

Enforces deterministic configuration and client-side failover guards for PostgreSQL 17 synchronized logical replication slots. Prevents silent data stream dropouts, unbounded WAL accumulation, and duplicate event ingestion during physical standby promotion across multi-region HA clusters. Mandates failover-enabled slot creation, primary synchronized_standby_slots gating, and strict post-promotion LSN boundary reconciliation.

Prohibited Anti-Pattern: Unsynchronized Logical Slot Provisioning and Blind Consumer Reconnection During Physical Standby Promotion

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: PostgreSQL 17 Logical Replication Failover Slot Synchronization Invariants - Enforces deterministic configuration and client-side failover guards for PostgreSQL 17 synchronized logical replication slots. Prevents silent data stream dropouts, unbounded WAL accumulation, and duplicate event ingestion during physical standby promotion across multi-region HA clusters. Mandates failover-enabled slot creation, primary synchronized_standby_slots gating, and strict post-promotion LSN boundary reconciliation.
globs: src/database/**/*.ts, src/replication/**/*.ts, src/services/**/*.ts, migrations/**/*.sql
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/pg17-logical-replication-failover-slot-sync-postgresql-17-lo-730"
---

# PostgreSQL 17 Logical Replication Failover Slot Synchronization Invariants

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unsynchronized Logical Slot Provisioning and Blind Consumer Reconnection During Physical Standby Promotion

## System Constraints
You are a Principal Database Infrastructure Architect enforcing PostgreSQL 17 logical replication invariants. In PostgreSQL 17, logical replication slots can synchronize seamlessly to physical standbys to support failover, but this requires strict adherence to slot configuration invariants (failover: true, synchronized_standby_slots on the primary, sync_replication_slots on the standby) and consumer checkpoint continuity. You must reject any slot creation or consumer client logic that does not explicitly configure and verify failover slot properties, assert standby sync status, and safeguard against split-brain LSN regressions.

## Strict Guidelines
- Engineers MUST ALWAYS provision logical replication slots in PostgreSQL 17 with `failover => true` using `pg_create_logical_replication_slot(slot_name, plugin, false, false, true)` to ensure slot metadata is propagated to physical standbys.
- Engineers MUST ensure that the primary server `synchronized_standby_slots` configuration parameter includes the physical standby's replication slot name before client consumers attach to the logical slot.
- Engineers MUST NOT allow logical replication consumers to connect to a promoted standby until verifying that the slot has transitioned out of `synced = true` status into an active, local slot state.
- Database consumers MUST verify that the promoted target node's `confirmed_flush_lsn` matches or precedes the consumer's persisted checkpoint LSN, preventing catastrophic forward skips in event streams.
- Services MUST monitor `pg_replication_slots` for `wal_status = 'lost'` or unconsumed LSN divergence, raising critical alerts before transaction log bloat saturates primary or standby storage pools.
- Client reconnection logic MUST NEVER drop and recreate a missing or delayed synchronized slot on failover; it must fail fast until standby synchronization completes or intentional operator-driven recovery is confirmed.

## Bad vs Good Implementations
### PostgreSQL 17 Failover Slot Provisioning and Resilient Consumer Attaching

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The legacy creation query omits PG17's failover parameter, so the slot will disappear if the primary crashes. On failover, the client fails to verify synchronization invariants, blindly attempts to recreate missing slots, and causes catastrophic event loss and stream corruption.
```typescript
import { Client } from 'pg';

export async function setupConsumerSlot(client: Client, slotName: string): Promise<void> {
  // FAILS: Creates legacy logical slot without PG17 failover flag.
  // This slot will NOT synchronize to physical standbys, breaking HA failover.
  await client.query(
    `SELECT pg_create_logical_replication_slot($1, 'pgoutput');`,
    [slotName]
  );
}

export async function reconnectAfterFailover(client: Client, slotName: string, lastProcessedLsn: string): Promise<void> {
  // FAILS: Blindly starts consuming on promoted standby without asserting slot state,
  // sync status, or confirming that the promoted standby's LSN satisfies our checkpoint.
  const res = await client.query('SELECT confirmed_flush_lsn FROM pg_replication_slots WHERE slot_name = $1', [slotName]);
  if (res.rows.length === 0) {
    // DANGEROUS: Recreates slot from scratch, causing data loss!
    await client.query(`SELECT pg_create_logical_replication_slot($1, 'pgoutput');`, [slotName]);
  }
  console.log(`Resuming consumption from ${slotName}`);
}
```

#### Production Standard (Correct)
> **Standard**: Uses PostgreSQL 17's native `failover => true` slot creation argument. Upon reconnecting after standby promotion, it strictly validates that the slot exists, failover was enabled, WAL status is healthy, `synced` has flipped to false indicating successful promotion, and LSN boundaries remain continuous without silent re-creation.
```typescript
import { Client } from 'pg';

interface ReplicationSlotRecord {
  slot_name: string;
  plugin: string;
  slot_type: string;
  active: boolean;
  failover: boolean;
  synced: boolean;
  confirmed_flush_lsn: string | null;
  wal_status: string;
}

export async function setupConsumerSlotPG17(
  client: Client,
  slotName: string,
  plugin: string = 'pgoutput'
): Promise<void> {
  // PG17: pg_create_logical_replication_slot(slot_name, plugin, temporary, two_phase, failover)
  await client.query(
    `SELECT pg_create_logical_replication_slot(
      $1::name,
      $2::name,
      false,
      false,
      true -- failover enabled for standby synchronization
    );`,
    [slotName, plugin]
  );
}

export async function validateAndAttachSlotAfterFailover(
  client: Client,
  slotName: string,
  lastCommittedLsn: string
): Promise<string> {
  const result = await client.query<ReplicationSlotRecord>(
    `SELECT slot_name, plugin, slot_type, active, failover, synced, confirmed_flush_lsn, wal_status
     FROM pg_replication_slots
     WHERE slot_name = $1;`,
    [slotName]
  );

  if (result.rows.length === 0) {
    throw new Error(
      `Invariant Violation: Logical slot '${slotName}' not found on promoted node. Failover slot sync failed or was incomplete.`
    );
  }

  const slot = result.rows[0];

  if (!slot.failover) {
    throw new Error(`Configuration Invariant Failure: Slot '${slotName}' was not created with failover=true.`);
  }

  if (slot.wal_status === 'lost') {
    throw new Error(`Data Loss Invariant Violation: WAL records for slot '${slotName}' have been removed on standby.`);
  }

  // On a promoted standby, synced must become false (promoted to a local primary slot)
  if (slot.synced) {
    throw new Error(
      `Promotion Invariant Incomplete: Slot '${slotName}' is still marked as synced=true. Node has not completed promotion.`
    );
  }

  if (slot.active) {
    throw new Error(`Concurrency Violation: Slot '${slotName}' is already actively held by another consumer.`);
  }

  // Verify LSN continuity: Client checkpoint must not be arbitrarily ahead of target flush LSN
  if (slot.confirmed_flush_lsn && slot.confirmed_flush_lsn > lastCommittedLsn) {
    throw new Error(
      `LSN Invariant Divergence: Standby slot confirmed LSN (${slot.confirmed_flush_lsn}) is ahead of client last known committed LSN (${lastCommittedLsn}).`
    );
  }

  return slot.confirmed_flush_lsn ?? lastCommittedLsn;
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: PostgreSQL 17 Logical Replication Failover Slot Synchronization Invariants

PostgreSQL 17 Logical Replication Failover Slot Synchronization Invariants defines an industrial-grade behavioral standard for backend engineering. Enforces deterministic configuration and client-side failover guards for PostgreSQL 17 synchronized logical replication slots. Prevents silent data stream dropouts, unbounded WAL accumulation, and duplicate event ingestion during physical standby promotion across multi-region HA clusters. Mandates failover-enabled slot creation, primary synchronized_standby_slots gating, and strict post-promotion LSN boundary reconciliation. 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 Slot Provisioning and Blind Consumer Reconnection During 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 DriftUnsynchronized Logical Slot Provisioning and Blind Consumer Reconnection During 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 in PostgreSQL 17 with `failover => true` using `pg_create_logical_replication_slot(slot_name, plugin, false, false, true)` to ensure slot metadata is propagated to physical standbys.

Engineers MUST ALWAYS provision logical replication slots in PostgreSQL 17 with `failover => true` using `pg_create_logical_replication_slot(slot_name, plugin, false, false, true)` to ensure slot metadata is propagated to 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.
2

Engineers MUST ensure that the primary server `synchronized_standby_slots` configuration parameter includes the physical standby's replication slot name before client consumers attach to the logical slot.

Engineers MUST ensure that the primary server `synchronized_standby_slots` configuration parameter includes the physical standby's replication slot name before client consumers attach to the logical slot.

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 NOT allow logical replication consumers to connect to a promoted standby until verifying that the slot has transitioned out of `synced = true` status into an active, local slot state.

Engineers MUST NOT allow logical replication consumers to connect to a promoted standby until verifying that the slot has transitioned out of `synced = true` status into an active, local slot 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.
4

Database consumers MUST verify that the promoted target node's `confirmed_flush_lsn` matches or precedes the consumer's persisted checkpoint LSN, preventing catastrophic forward skips in event streams.

Database consumers MUST verify that the promoted target node's `confirmed_flush_lsn` matches or precedes the consumer's persisted checkpoint LSN, preventing catastrophic forward skips in event streams.

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 monitor `pg_replication_slots` for `wal_status = 'lost'` or unconsumed LSN divergence, raising critical alerts before transaction log bloat saturates primary or standby storage pools.

Services MUST monitor `pg_replication_slots` for `wal_status = 'lost'` or unconsumed LSN divergence, raising critical alerts before transaction log bloat saturates primary or standby storage pools.

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

Client reconnection logic MUST NEVER drop and recreate a missing or delayed synchronized slot on failover

Client reconnection logic MUST NEVER drop and recreate a missing or delayed synchronized slot on failover; it must fail fast until standby synchronization completes or intentional operator-driven recovery is confirmed.

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

Enforces deterministic configuration and client-side failover guards for PostgreSQL 17 synchronized logical replication slots. Prevents silent data stream dropouts, unbounded WAL accumulation, and duplicate event ingestion during physical standby promotion across multi-region HA clusters. Mandates failover-enabled slot creation, primary synchronized_standby_slots gating, and strict post-promotion LSN boundary reconciliation. 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 Slot Provisioning and Blind Consumer Reconnection During 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

PostgreSQL