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-slot-sync-postgresql-17-lo-524

PostgreSQL 17 Logical Replication Slot Failover Synchronization Invariant

Enforces failover-enabled logical replication slots and physical standby synchronization invariants introduced in PostgreSQL 17. Guarantees that logical replication slots are synchronized to hot standbys before WAL retirement, preventing downstream CDC stream corruption, message drops, or mass duplication during automated cluster failovers.

Prohibited Anti-Pattern: Creating unmanaged logical replication slots without failover capability or synchronized standby coordination, causing stream loss or massive duplicates on failover.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: PostgreSQL 17 Logical Replication Slot Failover Synchronization Invariant - Enforces failover-enabled logical replication slots and physical standby synchronization invariants introduced in PostgreSQL 17. Guarantees that logical replication slots are synchronized to hot standbys before WAL retirement, preventing downstream CDC stream corruption, message drops, or mass duplication during automated cluster failovers.
globs: src/**/*.ts, migrations/**/*.sql, deploy/**/*.ts, infra/**/*.ts, scripts/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/postgres-17-logical-replication-failover-slot-sync-postgresql-17-lo-524"
---

# PostgreSQL 17 Logical Replication Slot Failover Synchronization Invariant

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Creating unmanaged logical replication slots without failover capability or synchronized standby coordination, causing stream loss or massive duplicates on failover.

## System Constraints
You are a Principal Database Reliability Engineer enforcing PostgreSQL 17 Logical Replication Failover Slot Sync Invariants. Mandate that all logical replication slots and subscriptions explicitly configure failover synchronization, that primary instances mandate synchronized standby slots, and that consuming services handle cluster promotion without WAL divergence.

## Strict Guidelines
- Engineers MUST ALWAYS create logical replication slots with `failover => true` on PostgreSQL 17+ (`pg_create_logical_replication_slot('slot_name', 'plugin_name', false, false, false, true)`).
- Engineers MUST configure `ALTER SUBSCRIPTION ... SET (failover = true)` when creating or updating logical subscriptions targeting PostgreSQL 17+ primaries.
- Engineers MUST NOT allow logical replication slots to progress ahead of physical standbys; primary configurations MUST include active standbys in `synchronized_standby_slots`.
- Services MUST verify `sync_replication_slots = on` and monitor `pg_replication_slots.synced` on physical standbys prior to promoting any standby to primary in HA topologies.
- Components NEVER assume a promoted standby can resume CDC/streaming safely without asserting the slot's `confirmed_flush_lsn` and `failover` status.

## Bad vs Good Implementations
### Provisioning Logical Replication Slots with PostgreSQL 17 Failover Sync

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Omits the `failover` parameter available in PG 17. The slot is excluded from standby slot sync workers (`sync_replication_slots`), breaking stream continuity if the primary fails over.
```typescript
import { Client } from 'pg';

export async function initLogicalReplicationSlot(client: Client, slotName: string): Promise<void> {
  // ANTI-PATTERN: Creates legacy logical slot without failover parameter.
  // On PG 17, this slot will NOT sync to physical standbys via slot sync worker.
  // Automated primary failover will result in missing slot or stale restart_lsn,
  // causing message loss or massive duplicate replays on downstream subscribers.
  await client.query(
    `SELECT pg_create_logical_replication_slot($1, 'pgoutput');`,
    [slotName]
  );
}
```

#### Production Standard (Correct)
> **Standard**: Validates PG17+ runtime, verifies primary standby slot coordination (`synchronized_standby_slots`), and passes `failover => true` to guarantee continuous synchronization across physical hot standbys.
```typescript
import { Client } from 'pg';

export async function initLogicalReplicationSlot(client: Client, slotName: string): Promise<void> {
  // 1. Assert PostgreSQL version >= 17
  const versionRes = await client.query<{ server_version_num: string }>(
    'SHOW server_version_num;'
  );
  const versionNum = parseInt(versionRes.rows[0].server_version_num, 10);
  if (versionNum < 170000) {
    throw new Error('PostgreSQL 17.0+ is required for failover slot synchronization.');
  }

  // 2. Assert synchronized_standby_slots is actively configured on primary
  const syncSlotsRes = await client.query<{ setting: string }>(
    "SHOW synchronized_standby_slots;"
  );
  if (!syncSlotsRes.rows[0]?.setting || syncSlotsRes.rows[0].setting === '') {
    throw new Error('synchronized_standby_slots must be configured on primary before creating failover slots.');
  }

  // 3. Create logical slot with failover = true to synchronize with standbys
  await client.query(
    `SELECT pg_create_logical_replication_slot(
      slot_name => $1,
      plugin => 'pgoutput',
      temporary => false,
      two_phase => 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 Logical Replication Slot Failover Synchronization Invariant

PostgreSQL 17 Logical Replication Slot Failover Synchronization Invariant defines an industrial-grade behavioral standard for backend engineering. Enforces failover-enabled logical replication slots and physical standby synchronization invariants introduced in PostgreSQL 17. Guarantees that logical replication slots are synchronized to hot standbys before WAL retirement, preventing downstream CDC stream corruption, message drops, or mass duplication during automated cluster 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: Creating unmanaged logical replication slots without failover capability or synchronized standby coordination, causing stream loss or massive duplicates on 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 DriftCreating unmanaged logical replication slots without failover capability or synchronized standby coordination, causing stream loss or massive duplicates on failover.Critical
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` on PostgreSQL 17+ (`pg_create_logical_replication_slot('slot_name', 'plugin_name', false, false, false, true)`).

Engineers MUST ALWAYS create logical replication slots with `failover => true` on PostgreSQL 17+ (`pg_create_logical_replication_slot('slot_name', 'plugin_name', false, 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 configure `ALTER SUBSCRIPTION ... SET (failover = true)` when creating or updating logical subscriptions targeting PostgreSQL 17+ primaries.

Engineers MUST configure `ALTER SUBSCRIPTION ... SET (failover = true)` when creating or updating logical subscriptions targeting PostgreSQL 17+ primaries.

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 slots to progress ahead of physical standbys

Engineers MUST NOT allow logical replication slots to progress ahead of physical standbys; primary configurations MUST include active standbys 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.
4

Services MUST verify `sync_replication_slots = on` and monitor `pg_replication_slots.synced` on physical standbys prior to promoting any standby to primary in HA topologies.

Services MUST verify `sync_replication_slots = on` and monitor `pg_replication_slots.synced` on physical standbys prior to promoting any standby to primary in HA topologies.

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 assume a promoted standby can resume CDC/streaming safely without asserting the slot's `confirmed_flush_lsn` and `failover` status.

Components NEVER assume a promoted standby can resume CDC/streaming safely without asserting the slot's `confirmed_flush_lsn` and `failover` status.

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

Enforces failover-enabled logical replication slots and physical standby synchronization invariants introduced in PostgreSQL 17. Guarantees that logical replication slots are synchronized to hot standbys before WAL retirement, preventing downstream CDC stream corruption, message drops, or mass duplication during automated cluster 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 (Creating unmanaged logical replication slots without failover capability or synchronized standby coordination, causing stream loss or massive duplicates on 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