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

PostgreSQL 17 Failover Logical Slot Synchronization & Standby Persistence Invariant

Mandates standard configuration and programmatic slot creation semantics introduced in PostgreSQL 17 for zero-data-loss logical replication failover. Enforces the use of the failover flag during slot instantiation and validates primary/standby coordination through synchronized_standby_slots and sync_replication_slots. Prevents subscriber desynchronization, replay stream divergence, and downstream message corruption during physical primary failovers.

Prohibited Anti-Pattern: Uncoordinated Logical Slots Lacking Failover Propagation and Standby Sync Gating

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: PostgreSQL 17 Failover Logical Slot Synchronization & Standby Persistence Invariant - Mandates standard configuration and programmatic slot creation semantics introduced in PostgreSQL 17 for zero-data-loss logical replication failover. Enforces the use of the failover flag during slot instantiation and validates primary/standby coordination through synchronized_standby_slots and sync_replication_slots. Prevents subscriber desynchronization, replay stream divergence, and downstream message corruption during physical primary failovers.
globs: src/**/*.ts, migrations/**/*.sql, infra/**/*.tf, scripts/**/*.sh
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/postgres-17-failover-slot-synchronization-standard"
---

# PostgreSQL 17 Failover Logical Slot Synchronization & Standby Persistence Invariant

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Uncoordinated Logical Slots Lacking Failover Propagation and Standby Sync Gating

## System Constraints
You are a Principal Database Architect enforcing the PostgreSQL 17 Failover Slot Synchronization Standard. Mandate that all logical replication slots configured or programmatically managed in PostgreSQL 17+ environments enable the native failover attribute (failover => true). Ensure physical primary instances gate logical WAL advancement behind physical standbys via synchronized_standby_slots, and standby instances enable the slot synchronization background worker (sync_replication_slots = on). Reject any schema migration, database provisioning script, or connection pool setup that initiates uncoordinated, non-failover-safe logical slots.

## Strict Guidelines
- Engineers MUST ALWAYS supply the `failover => true` named parameter when calling `pg_create_logical_replication_slot()` or executing `CREATE SUBSCRIPTION ... WITH (failover = true)` in PostgreSQL 17+.
- Engineers MUST NOT create logical replication slots on the primary without verifying that targeted physical standby application names are explicitly enumerated in `synchronized_standby_slots`.
- Code SHOULD dynamically assert database cluster version and verify `pg_replication_slots.failover` status prior to initiating Change Data Capture (CDC) consumption streams.
- Services MUST configure physical standby nodes with `sync_replication_slots = on` to activate the `slotsync` background worker and retain valid LSN synchronization before node promotion.
- Components NEVER issue manual LSN mutations, drop-and-recreate commands, or uncoordinated catalog updates to synchronized slots on promoted replicas.

## Bad vs Good Implementations
### PostgreSQL 17 Slot Provisioning with Failover Guardrails

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Omitting the 'failover' parameter creates a legacy logical replication slot that the standby slotsync worker ignores. If the primary crashes, the promoted standby will lack this slot, leading to subscriber failure or catastrophic data inconsistency requiring full resynchronization.
```typescript
import { Client } from 'pg';

export async function setupLogicalReplicationSlot(client: Client, slotName: string): Promise<void> {
  // ANTI-PATTERN: Pre-PG17 syntax or omitting failover flag.
  // This slot will NOT synchronize to physical standbys, causing subscriber desynchronization on failover.
  await client.query(`
    SELECT pg_create_logical_replication_slot($1, 'pgoutput');
  `, [slotName]);
}
```

#### Production Standard (Correct)
> **Standard**: Validates engine capability (PG 17+), verifies cluster failover safety settings (synchronized_standby_slots), and invokes pg_create_logical_replication_slot with failover => true, ensuring slot metadata and LSN progress are mirrored to standbys.
```typescript
import { Client } from 'pg';

export async function setupLogicalReplicationSlot(client: Client, slotName: string): Promise<void> {
  // Verify Postgres 17+ cluster capability
  const { rows: versionRows } = await client.query<{ server_version_num: string }>(
    'SHOW server_version_num;'
  );
  const versionNum = parseInt(versionRows[0].server_version_num, 10);
  if (versionNum < 170000) {
    throw new Error('PostgreSQL 17 or higher is required for synchronized failover slots.');
  }

  // Verify primary instance has standby synchronization configured
  const { rows: syncSettings } = await client.query<{ synchronized_standby_slots: string }>(
    'SHOW synchronized_standby_slots;'
  );
  if (!syncSettings[0]?.synchronized_standby_slots || syncSettings[0].synchronized_standby_slots === '') {
    throw new Error('Primary must define synchronized_standby_slots before creating failover slots.');
  }

  // INVARIANT: Explicitly declare failover => true using PG17 named parameter
  await client.query(`
    SELECT pg_create_logical_replication_slot(
      slot_name => $1,
      plugin => 'pgoutput',
      temporary => false,
      twophase => false,
      failover => true
    );
  `, [slotName]);
}
```

Recommended MCP Servers (mcp-serverlist.com)

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

Architectural Specification & Invariant Rationale

Architectural Invariant Design: PostgreSQL 17 Failover Logical Slot Synchronization & Standby Persistence Invariant

PostgreSQL 17 Failover Logical Slot Synchronization & Standby Persistence Invariant defines an industrial-grade behavioral standard for backend engineering. Mandates standard configuration and programmatic slot creation semantics introduced in PostgreSQL 17 for zero-data-loss logical replication failover. Enforces the use of the failover flag during slot instantiation and validates primary/standby coordination through synchronized_standby_slots and sync_replication_slots. Prevents subscriber desynchronization, replay stream divergence, and downstream message corruption during physical primary failovers. 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: Uncoordinated Logical Slots Lacking Failover Propagation and Standby Sync Gating 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 DriftUncoordinated Logical Slots Lacking Failover Propagation and Standby Sync GatingCritical
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 supply the `failover => true` named parameter when calling `pg_create_logical_replication_slot()` or executing `CREATE SUBSCRIPTION ... WITH (failover = true)` in PostgreSQL 17+.

Engineers MUST ALWAYS supply the `failover => true` named parameter when calling `pg_create_logical_replication_slot()` or executing `CREATE SUBSCRIPTION ... WITH (failover = true)` in PostgreSQL 17+.

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 create logical replication slots on the primary without verifying that targeted physical standby application names are explicitly enumerated in `synchronized_standby_slots`.

Engineers MUST NOT create logical replication slots on the primary without verifying that targeted physical standby application names are explicitly enumerated in `synchronized_standby_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.
3

Code SHOULD dynamically assert database cluster version and verify `pg_replication_slots.failover` status prior to initiating Change Data Capture (CDC) consumption streams.

Code SHOULD dynamically assert database cluster version and verify `pg_replication_slots.failover` status prior to initiating Change Data Capture (CDC) consumption 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.
4

Services MUST configure physical standby nodes with `sync_replication_slots = on` to activate the `slotsync` background worker and retain valid LSN synchronization before node promotion.

Services MUST configure physical standby nodes with `sync_replication_slots = on` to activate the `slotsync` background worker and retain valid LSN synchronization before 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

Components NEVER issue manual LSN mutations, drop-and-recreate commands, or uncoordinated catalog updates to synchronized slots on promoted replicas.

Components NEVER issue manual LSN mutations, drop-and-recreate commands, or uncoordinated catalog updates to synchronized slots on promoted replicas.

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 Logical Slot Synchronization & Standby Persistence Invariant critical for AI coding assistants?

Mandates standard configuration and programmatic slot creation semantics introduced in PostgreSQL 17 for zero-data-loss logical replication failover. Enforces the use of the failover flag during slot instantiation and validates primary/standby coordination through synchronized_standby_slots and sync_replication_slots. Prevents subscriber desynchronization, replay stream divergence, and downstream message corruption during physical primary failovers. 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 (Uncoordinated Logical Slots Lacking Failover Propagation and Standby Sync Gating) 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