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

PostgreSQL 17 Failover Slot Synchronization and Invalidation Protocol

Enforces PostgreSQL 17 native failover-capable logical replication slot management, physical standby alignment via standby_slot_names, and strict monitoring of slot invalidation states. Guarantees zero logical data divergence and prevents silent consumer stalls during high-availability primary failover events.

Prohibited Anti-Pattern: Creating Non-Failover Logical Replication Slots Without Physical Standby Alignment and Invalidation Auditing

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: PostgreSQL 17 Failover Slot Synchronization and Invalidation Protocol - Enforces PostgreSQL 17 native failover-capable logical replication slot management, physical standby alignment via standby_slot_names, and strict monitoring of slot invalidation states. Guarantees zero logical data divergence and prevents silent consumer stalls during high-availability primary failover events.
globs: src/database/**/*.ts, src/replication/**/*.ts, src/infra/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/pg17-failover-slot-synchronization-protocol"
---

# PostgreSQL 17 Failover Slot Synchronization and Invalidation Protocol

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Creating Non-Failover Logical Replication Slots Without Physical Standby Alignment and Invalidation Auditing

## System Constraints
You are a Principal Software Architect enforcing the PostgreSQL 17 Failover Slot Synchronization and Invalidation Protocol. In PostgreSQL 17, logical replication failover requires physical-to-logical replication slot alignment via native failover slot syncing. Mandate that every logical replication slot provisioned for high-availability topologies explicitly enables `failover = true` on the primary, physical standbys define `sync_replication_slots = on`, and the primary restricts logical progression behind standby physical replication slots using `standby_slot_names`. Invalidate and alert immediately upon detecting non-null `invalidated` columns in `pg_replication_slots` to avert consumer deadlocks and data divergence.

## Strict Guidelines
- Engineers MUST ALWAYS create logical replication slots with `failover => true` in PostgreSQL 17 (`pg_create_logical_replication_slot(slot_name, plugin, false, false, true)`).
- Engineers MUST NOT allow logical replication slots to advance without confirming that the physical standby slot name is registered in primary's `standby_slot_names` configuration.
- Code MUST verify `sync_replication_slots = 'on'` on all standby instances to maintain identical logical slot state and LSN replay alignment.
- Services MUST monitor `pg_replication_slots.invalidated` and alert immediately if a slot is invalidated by `wal_removed` or `max_slot_wal_keep_size` breaches.
- Components NEVER execute failover switchover orchestrations without querying standby `pg_replication_slots` to ensure `synced = true` for target logical slots.

## Bad vs Good Implementations
### PostgreSQL 17 Logical Replication Slot Provisioning & Validation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Creating a logical replication slot in PostgreSQL 17 without setting the `failover` argument to `true` prevents physical standby nodes from synchronizing the slot via `sync_replication_slots`. Upon primary failover, the promoted standby will lack the logical slot, causing downstream subscriptions to permanently stall or lose transactional continuity.
```typescript
import { Client } from 'pg';

export async function provisionReplicationSlot(client: Client, slotName: string): Promise<void> {
  // Anti-Pattern: Omits PG17 failover parameter; slot will NOT sync to standbys
  await client.query(
    `SELECT pg_create_logical_replication_slot($1, 'pgoutput');`,
    [slotName]
  );

  // Ignores verification of standby_slot_names or slot invalidation readiness
  console.log(`Slot ${slotName} created without failover support.`);
}
```

#### Production Standard (Correct)
> **Standard**: Enforces PostgreSQL 17 failover slot semantics: verifies that `standby_slot_names` tracks the standby physical slot, explicitly creates the slot with `failover => true`, and asserts the health and non-invalidated status from `pg_replication_slots`.
```typescript
import { Client } from 'pg';

interface SlotHealthRecord {
  slot_name: string;
  plugin: string;
  failover: boolean;
  synced: boolean;
  invalidated: string | null;
}

export async function provisionFailoverSafeSlot(
  primaryClient: Client,
  slotName: string,
  expectedStandbySlot: string
): Promise<void> {
  // Invariant 1: Ensure primary aligns logical progress with physical standby
  const standbyCheck = await primaryClient.query<{ setting: string }>(
    `SELECT setting FROM pg_settings WHERE name = 'standby_slot_names';`
  );
  const configuredStandbys = standbyCheck.rows[0]?.setting.split(',').map((s) => s.trim()) ?? [];
  
  if (!configuredStandbys.includes(expectedStandbySlot)) {
    throw new Error(
      `Primary standby_slot_names does not include '${expectedStandbySlot}'. Slot '${slotName}' will lead to desync.`
    );
  }

  // Invariant 2: Create logical slot with PG17 failover => true parameter
  // Signature: pg_create_logical_replication_slot(slot_name, plugin, temporary, two_phase, failover)
  await primaryClient.query(
    `SELECT pg_create_logical_replication_slot($1, 'pgoutput', false, false, true);`,
    [slotName]
  );

  // Invariant 3: Verify slot health and failover flag
  const verification = await primaryClient.query<SlotHealthRecord>(
    `SELECT slot_name, plugin, failover, synced, invalidated 
     FROM pg_replication_slots 
     WHERE slot_name = $1;`,
    [slotName]
  );

  const slot = verification.rows[0];
  if (!slot || !slot.failover || slot.invalidated !== null) {
    throw new Error(
      `Failed to verify failover-safe replication slot: ${JSON.stringify(slot)}`
    );
  }
}
```

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 and Invalidation Protocol

PostgreSQL 17 Failover Slot Synchronization and Invalidation Protocol defines an industrial-grade behavioral standard for backend engineering. Enforces PostgreSQL 17 native failover-capable logical replication slot management, physical standby alignment via standby_slot_names, and strict monitoring of slot invalidation states. Guarantees zero logical data divergence and prevents silent consumer stalls during high-availability primary failover events. 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 Non-Failover Logical Replication Slots Without Physical Standby Alignment and Invalidation Auditing 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 Non-Failover Logical Replication Slots Without Physical Standby Alignment and Invalidation AuditingCritical
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` in PostgreSQL 17 (`pg_create_logical_replication_slot(slot_name, plugin, false, false, true)`).

Engineers MUST ALWAYS create logical replication slots with `failover => true` in PostgreSQL 17 (`pg_create_logical_replication_slot(slot_name, plugin, 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 NOT allow logical replication slots to advance without confirming that the physical standby slot name is registered in primary's `standby_slot_names` configuration.

Engineers MUST NOT allow logical replication slots to advance without confirming that the physical standby slot name is registered in primary's `standby_slot_names` configuration.

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

Code MUST verify `sync_replication_slots = 'on'` on all standby instances to maintain identical logical slot state and LSN replay alignment.

Code MUST verify `sync_replication_slots = 'on'` on all standby instances to maintain identical logical slot state and LSN replay alignment.

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

Services MUST monitor `pg_replication_slots.invalidated` and alert immediately if a slot is invalidated by `wal_removed` or `max_slot_wal_keep_size` breaches.

Services MUST monitor `pg_replication_slots.invalidated` and alert immediately if a slot is invalidated by `wal_removed` or `max_slot_wal_keep_size` breaches.

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 failover switchover orchestrations without querying standby `pg_replication_slots` to ensure `synced = true` for target logical slots.

Components NEVER execute failover switchover orchestrations without querying standby `pg_replication_slots` to ensure `synced = true` for target 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 and Invalidation Protocol critical for AI coding assistants?

Enforces PostgreSQL 17 native failover-capable logical replication slot management, physical standby alignment via standby_slot_names, and strict monitoring of slot invalidation states. Guarantees zero logical data divergence and prevents silent consumer stalls during high-availability primary failover events. 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 Non-Failover Logical Replication Slots Without Physical Standby Alignment and Invalidation Auditing) 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