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-slots-guardrail

PostgreSQL 17 Deterministic Failover Slot Synchronization Guardrail

Enforces deterministic configuration and validation of PostgreSQL 17 logical replication failover slots across physical standbys. Prevents silent downstream subscriber divergence, double-processing, and WAL disk exhaustion caused by uncoordinated primary promotions or unsynchronized LSN markers.

Prohibited Anti-Pattern: Unsynchronized Ephemeral Logical Slots Leading to Replay Divergence or WAL Disk Exhaustion Post-Failover

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: PostgreSQL 17 Deterministic Failover Slot Synchronization Guardrail - Enforces deterministic configuration and validation of PostgreSQL 17 logical replication failover slots across physical standbys. Prevents silent downstream subscriber divergence, double-processing, and WAL disk exhaustion caused by uncoordinated primary promotions or unsynchronized LSN markers.
globs: src/database/**/*.ts, src/infra/**/*.ts, src/services/replication/**/*.ts, migrations/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/postgres-17-logical-replication-failover-slots-guardrail"
---

# PostgreSQL 17 Deterministic Failover Slot Synchronization Guardrail

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unsynchronized Ephemeral Logical Slots Leading to Replay Divergence or WAL Disk Exhaustion Post-Failover

## System Constraints
You are a Principal Database Architect and Infrastructure Guardrail Engine. You strictly enforce PostgreSQL 17 logical replication failover slot requirements. You must ensure that any logical replication slot creation explicitly specifies failover = true, that physical standbys run sync_replication_slots = on, that primary nodes configure standby_slot_names to synchronize slot forward progress, and that client promotion scripts affirmatively verify slot synchronization state prior to redirecting CDC/subscriber workloads.

## Strict Guidelines
- Engineers MUST ALWAYS provision logical replication slots with failover = true via pg_create_logical_replication_slot() or ALTER_REPLICATION_SLOT in PostgreSQL 17+ environments.
- Engineers MUST ALWAYS configure standby_slot_names on the primary instance to include physical standby slots, preventing the primary from discarding WAL segments before downstream physical standbys confirm them.
- Services MUST verify pg_replication_slots.synced = true and monitor confirmed_flush_lsn lag on the target standby prior to issuing trigger-based or Patroni-driven primary promotions.
- Engineers MUST NOT allow logical replication slots without failover = true in architectures utilizing streaming physical standbys for disaster recovery.
- Automation scripts SHOULD explicitly poll pg_sync_replication_slots() or verify the slot synchronization worker process status before routing subscriber consumers to newly promoted clusters.
- Database orchestrators MUST monitor wal_keep_size and pg_replication_slots.active to prevent runaway disk saturation caused by stalled inactive synced slots on standbys.

## Bad vs Good Implementations
### Configuring and Validating PG17 Failover Logical Replication Slots

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Creating a logical replication slot without failover => true causes the slot to exist solely on the local primary. Upon primary failover, the promoted standby lacks the slot or its confirmed_flush_lsn position, resulting in catastrophic subscriber desynchronization or replay duplicates.
```typescript
import { Client } from 'pg';

export async function setupConsumerSlot(client: Client, slotName: string): Promise<void> {
  // Anti-Pattern: Creates a legacy logical slot without failover synchronization.
  // During standby promotion, this slot vanishes or falls behind, causing CDC subscribers
  // to diverge silently or fail with missing WAL segment errors.
  await client.query(
    `SELECT pg_create_logical_replication_slot($1, 'pgoutput');`,
    [slotName]
  );
}
```

#### Production Standard (Correct)
> **Standard**: Explicitly passes failover => true to pg_create_logical_replication_slot and asserts that the slot exists with failover enabled in pg_replication_slots, ensuring seamless physical standby synchronization and zero-loss consumer transition upon promotion.
```typescript
import { Client } from 'pg';

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

export async function setupFailoverLogicalSlot(
  client: Client,
  slotName: string,
  plugin = 'pgoutput'
): Promise<ReplicationSlotStatus> {
  // Invariant: Enforce PostgreSQL 17 failover flag on logical slot creation
  await client.query(
    `SELECT pg_create_logical_replication_slot(
      slot_name => $1,
      plugin => $2,
      temporary => false,
      twophase => true,
      failover => true
    );`,
    [slotName, plugin]
  );

  // Verify slot properties match critical failover requirements
  const result = await client.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 slot = result.rows[0];
  if (!slot || !slot.failover) {
    throw new Error(`Critical: Slot ${slotName} was not initialized with failover enabled.`);
  }

  return {
    slotName: slot.slot_name,
    plugin: slot.plugin,
    failover: slot.failover,
    synced: slot.synced,
    confirmedFlushLsn: slot.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: PostgreSQL 17 Deterministic Failover Slot Synchronization Guardrail

PostgreSQL 17 Deterministic Failover Slot Synchronization Guardrail defines an industrial-grade behavioral standard for backend engineering. Enforces deterministic configuration and validation of PostgreSQL 17 logical replication failover slots across physical standbys. Prevents silent downstream subscriber divergence, double-processing, and WAL disk exhaustion caused by uncoordinated primary promotions or unsynchronized LSN markers. 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 Ephemeral Logical Slots Leading to Replay Divergence or WAL Disk Exhaustion Post-Failover 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 Ephemeral Logical Slots Leading to Replay Divergence or WAL Disk Exhaustion Post-FailoverCritical
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 via pg_create_logical_replication_slot() or ALTER_REPLICATION_SLOT in PostgreSQL 17+ environments.

Engineers MUST ALWAYS provision logical replication slots with failover = true via pg_create_logical_replication_slot() or ALTER_REPLICATION_SLOT 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 standby_slot_names on the primary instance to include physical standby slots, preventing the primary from discarding WAL segments before downstream physical standbys confirm them.

Engineers MUST ALWAYS configure standby_slot_names on the primary instance to include physical standby slots, preventing the primary from discarding WAL segments before downstream physical standbys confirm them.

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

Services MUST verify pg_replication_slots.synced = true and monitor confirmed_flush_lsn lag on the target standby prior to issuing trigger-based or Patroni-driven primary promotions.

Services MUST verify pg_replication_slots.synced = true and monitor confirmed_flush_lsn lag on the target standby prior to issuing trigger-based or Patroni-driven primary promotions.

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 allow logical replication slots without failover = true in architectures utilizing streaming physical standbys for disaster recovery.

Engineers MUST NOT allow logical replication slots without failover = true in architectures utilizing streaming physical standbys for disaster recovery.

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

Automation scripts SHOULD explicitly poll pg_sync_replication_slots() or verify the slot synchronization worker process status before routing subscriber consumers to newly promoted clusters.

Automation scripts SHOULD explicitly poll pg_sync_replication_slots() or verify the slot synchronization worker process status before routing subscriber consumers to newly promoted clusters.

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

Database orchestrators MUST monitor wal_keep_size and pg_replication_slots.active to prevent runaway disk saturation caused by stalled inactive synced slots on standbys.

Database orchestrators MUST monitor wal_keep_size and pg_replication_slots.active to prevent runaway disk saturation caused by stalled inactive synced slots on 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.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is PostgreSQL 17 Deterministic Failover Slot Synchronization Guardrail critical for AI coding assistants?

Enforces deterministic configuration and validation of PostgreSQL 17 logical replication failover slots across physical standbys. Prevents silent downstream subscriber divergence, double-processing, and WAL disk exhaustion caused by uncoordinated primary promotions or unsynchronized LSN markers. 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 Ephemeral Logical Slots Leading to Replay Divergence or WAL Disk Exhaustion Post-Failover) 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