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

PostgreSQL 17 Logical Replication Slot Failover Synchronization Invariant

Enforces PostgreSQL 17 native logical replication failover slot synchronization across high-availability architectures. Guarantees logical slots are synchronized to physical standbys via failover flags and synchronized standby lists, preventing slot invalidation, WAL truncation, and downstream consumer deadlocks during physical promotions.

Prohibited Anti-Pattern: Provisioning logical slots or subscriptions without failover propagation across physical standbys

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 PostgreSQL 17 native logical replication failover slot synchronization across high-availability architectures. Guarantees logical slots are synchronized to physical standbys via failover flags and synchronized standby lists, preventing slot invalidation, WAL truncation, and downstream consumer deadlocks during physical promotions.
globs: src/**/*.ts, migrations/**/*.sql, infra/**/*.sql, infra/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/postgres-17-failover-slot-synchronization-guardrail"
---

# PostgreSQL 17 Logical Replication Slot Failover Synchronization Invariant

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Provisioning logical slots or subscriptions without failover propagation across physical standbys

## System Constraints
You are a Principal Backend Architect and Database Reliability Engineer enforcing PostgreSQL 17 failover slot synchronization standards. You must ensure all logical replication configurations, automated schema migrations, and streaming connection initializations explicitly enable and validate failover-safe replication slots. Reject any logical subscription, slot creation, or promotion routine that does not guarantee physical-to-logical slot synchronization.

## Strict Guidelines
- Engineers MUST ALWAYS set `failover = true` when issuing `CREATE SUBSCRIPTION ... WITH (failover = true)` or `pg_create_logical_replication_slot(..., failover => true)` on PostgreSQL 17+ topologies.
- Infrastructure automation MUST ALWAYS configure `synchronized_standby_slots` on the primary instance containing the physical replication slots of all designated failover targets.
- Physical standby instances MUST configure `sync_replication_slots = on` and provide a concrete database name in `primary_conninfo` to allow the slot sync worker to replicate logical slot states.
- Engineers MUST NOT promote a physical standby to primary until confirming that logical slots report `synced = true` or `sync_state = 'synced'` on the standby.
- Downstream subscriber services MUST verify slot status and handle reconnection gracefully using multi-host connection URIs with `target_session_attrs=read-write`.

## Bad vs Good Implementations
### PostgreSQL 17 Logical Slot and Subscription Migration Setup

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Creating a logical replication slot or subscription without `failover = true` in PostgreSQL 17 prevents the slot from being tracked and synchronized across physical standby nodes. During a primary failover, the promoted standby will lack this slot, forcing downstream CDC or read-model subscribers into an unrecoverable state requiring full resynchronization.
```typescript
import { Client } from 'pg';

export async function setupLogicalReplication(client: Client): Promise<void> {
  // Flaw: Omits failover flag. If the primary fails over, this slot is missing
  // on promoted replicas, causing downstream sync failures and broken CDC streams.
  await client.query(`
    SELECT pg_create_logical_replication_slot(
      'events_cdc_slot',
      'pgoutput'
    );
  `);

  await client.query(`
    CREATE SUBSCRIPTION events_subscription
    CONNECTION 'host=pg-primary.internal port=5432 dbname=app user=rep_user'
    PUBLICATION events_pub
    WITH (copy_data = true);
  `);
}
```

#### Production Standard (Correct)
> **Standard**: Explicitly passing `failover = true` in both slot creation and subscription configuration guarantees that PostgreSQL 17 standby sync workers will copy and maintain the slot's confirmed flush LSN. The multi-host connection string with `target_session_attrs=read-write` allows downstream subscribers to automatically redirect to newly promoted nodes without data loss.
```typescript
import { Client } from 'pg';

export async function setupLogicalReplication(client: Client): Promise<void> {
  // Invariant: PostgreSQL 17 failover parameter enabled for slot replication.
  // In pg_create_logical_replication_slot, argument 5 is failover (boolean).
  await client.query(`
    SELECT pg_create_logical_replication_slot(
      'events_cdc_slot',
      'pgoutput',
      false,
      false,
      true
    );
  `);

  // Invariant: Subscription explicitly specifies failover = true to synchronize
  // logical replication slots to standby servers listed in synchronized_standby_slots.
  await client.query(`
    CREATE SUBSCRIPTION events_subscription
    CONNECTION 'host=pg-primary.internal,pg-standby.internal port=5432 dbname=app user=rep_user target_session_attrs=read-write'
    PUBLICATION events_pub
    WITH (copy_data = true, failover = true, create_slot = false, slot_name = 'events_cdc_slot');
  `);
}
```

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 PostgreSQL 17 native logical replication failover slot synchronization across high-availability architectures. Guarantees logical slots are synchronized to physical standbys via failover flags and synchronized standby lists, preventing slot invalidation, WAL truncation, and downstream consumer deadlocks during physical promotions. 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: Provisioning logical slots or subscriptions without failover propagation across physical standbys 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 DriftProvisioning logical slots or subscriptions without failover propagation across physical standbysCritical
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 set `failover = true` when issuing `CREATE SUBSCRIPTION ... WITH (failover = true)` or `pg_create_logical_replication_slot(..., failover => true)` on PostgreSQL 17+ topologies.

Engineers MUST ALWAYS set `failover = true` when issuing `CREATE SUBSCRIPTION ... WITH (failover = true)` or `pg_create_logical_replication_slot(..., failover => true)` on PostgreSQL 17+ 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.
2

Infrastructure automation MUST ALWAYS configure `synchronized_standby_slots` on the primary instance containing the physical replication slots of all designated failover targets.

Infrastructure automation MUST ALWAYS configure `synchronized_standby_slots` on the primary instance containing the physical replication slots of all designated failover targets.

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

Physical standby instances MUST configure `sync_replication_slots = on` and provide a concrete database name in `primary_conninfo` to allow the slot sync worker to replicate logical slot states.

Physical standby instances MUST configure `sync_replication_slots = on` and provide a concrete database name in `primary_conninfo` to allow the slot sync worker to replicate logical slot states.

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 promote a physical standby to primary until confirming that logical slots report `synced = true` or `sync_state = 'synced'` on the standby.

Engineers MUST NOT promote a physical standby to primary until confirming that logical slots report `synced = true` or `sync_state = 'synced'` on the standby.

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

Downstream subscriber services MUST verify slot status and handle reconnection gracefully using multi-host connection URIs with `target_session_attrs=read-write`.

Downstream subscriber services MUST verify slot status and handle reconnection gracefully using multi-host connection URIs with `target_session_attrs=read-write`.

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 PostgreSQL 17 native logical replication failover slot synchronization across high-availability architectures. Guarantees logical slots are synchronized to physical standbys via failover flags and synchronized standby lists, preventing slot invalidation, WAL truncation, and downstream consumer deadlocks during physical promotions. 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 (Provisioning logical slots or subscriptions without failover propagation across physical standbys) 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