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

PostgreSQL 17 Failover Slot Sync & Logical Replication Invariants

Enforces failover-safe logical replication slots introduced in PostgreSQL 17 to prevent message loss or unbounded re-streaming during high-availability switchovers. Mandates `failover = true` on logical slots, strict synchronization across physical standbys via `synchronized_standby_slots`, and downstream LSN tracking to uphold exactly-once or at-least-once CDC processing invariants.

Prohibited Anti-Pattern: Creating unmanaged logical replication slots that are dropped or rewound upon physical standby failover

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: PostgreSQL 17 Failover Slot Sync & Logical Replication Invariants - Enforces failover-safe logical replication slots introduced in PostgreSQL 17 to prevent message loss or unbounded re-streaming during high-availability switchovers. Mandates `failover = true` on logical slots, strict synchronization across physical standbys via `synchronized_standby_slots`, and downstream LSN tracking to uphold exactly-once or at-least-once CDC processing invariants.
globs: src/database/**/*.{ts,js,sql}, src/infrastructure/**/*.{ts,js}, src/cdc/**/*.{ts,js}, migrations/**/*.{sql,ts}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/postgres-17-failover-slot-sync-cdc-invariant-postgres-17-fail-186"
---

# PostgreSQL 17 Failover Slot Sync & Logical Replication Invariants

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Creating unmanaged logical replication slots that are dropped or rewound upon physical standby failover

## System Constraints
You are a Principal Database Architect enforcing PostgreSQL 17 logical slot synchronization guardrails. You must reject any ad-hoc creation of logical replication slots that omit failover flags, ignore physical standby confirmation, or bypass client-side LSN commit tracking. Ensure all CDC consumers and migrations implement synchronized slot guarantees and idempotent consumer semantics.

## Strict Guidelines
- Engineers MUST ALWAYS set `failover = true` when invoking `pg_create_logical_replication_slot()` in PostgreSQL 17+ environments.
- Engineers MUST NEVER permit CDC consumers to advance logical slots past the LSN confirmed by all entries in `synchronized_standby_slots` on the primary instance.
- Code MUST explicitly handle reconnects by querying `pg_replication_slots.sync_state` to ensure the slot is promoted and ready following a failover event.
- Services MUST persist committed downstream consumer offsets idempotently alongside transaction boundaries to prevent duplicate processing on slot rewind.
- Components NEVER assume physical replication slot names correspond to logical slots without verifying `sync_state = 'synced'` on the standby replica.

## Bad vs Good Implementations
### Configuring PG17 Failover Slot and Synchronous Standby Tracking

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Creating a logical slot without PostgreSQL 17's `failover` parameter causes the slot to remain local to the primary. When a physical failover occurs, the promoted replica lacks the slot, breaking downstream CDC and causing event loss or unrecoverable lag.
```typescript
import { Client } from 'pg';

export async function initCdcSlot(client: Client, slotName: string): Promise<void> {
  // Anti-pattern: Missing failover parameter and physical standby sync check;
  // on primary failover to standby, this slot will be missing or corrupted,
  // forcing a full table rescan or silent data drop.
  await client.query(`
    SELECT pg_create_logical_replication_slot($1, 'pgoutput');
  `, [slotName]);
}
```

#### Production Standard (Correct)
> **Standard**: Verifies that the target physical standby replication slot is registered in `synchronized_standby_slots` and creates the logical slot with `failover => true`, guaranteeing the standby replica continuously syncs the slot state before consumer acknowledgement.
```typescript
import { Client } from 'pg';

export interface ReplicationSlotConfig {
  slotName: string;
  plugin?: string;
  syncStandbySlotName: string;
}

export async function initCdcSlot(client: Client, config: ReplicationSlotConfig): Promise<void> {
  const plugin = config.plugin ?? 'pgoutput';

  // Validate synchronized_standby_slots includes physical replica slot
  const gucRes = await client.query<{ synchronized_standby_slots: string }>(
    `SHOW synchronized_standby_slots;`
  );
  const configuredSlots = gucRes.rows[0]?.synchronized_standby_slots?.split(',').map((s) => s.trim()) ?? [];
  
  if (!configuredSlots.includes(config.syncStandbySlotName)) {
    throw new Error(
      `Physical slot '${config.syncStandbySlotName}' is not in synchronized_standby_slots. ` +
      `Failover slot sync cannot guarantee persistence.`
    );
  }

  // PG17 invariant: failover = true preserves slot across physical standby failover
  await client.query(`
    SELECT pg_create_logical_replication_slot(
      slot_name => $1,
      plugin => $2,
      temporary => false,
      twophase => true,
      failover => true
    );
  `, [config.slotName, plugin]);
}
```

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 Slot Sync & Logical Replication Invariants

PostgreSQL 17 Failover Slot Sync & Logical Replication Invariants defines an industrial-grade behavioral standard for backend engineering. Enforces failover-safe logical replication slots introduced in PostgreSQL 17 to prevent message loss or unbounded re-streaming during high-availability switchovers. Mandates `failover = true` on logical slots, strict synchronization across physical standbys via `synchronized_standby_slots`, and downstream LSN tracking to uphold exactly-once or at-least-once CDC processing invariants. 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 that are dropped or rewound upon physical standby 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 that are dropped or rewound upon physical standby 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 set `failover = true` when invoking `pg_create_logical_replication_slot()` in PostgreSQL 17+ environments.

Engineers MUST ALWAYS set `failover = true` when invoking `pg_create_logical_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 NEVER permit CDC consumers to advance logical slots past the LSN confirmed by all entries in `synchronized_standby_slots` on the primary instance.

Engineers MUST NEVER permit CDC consumers to advance logical slots past the LSN confirmed by all entries in `synchronized_standby_slots` on the primary instance.

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 explicitly handle reconnects by querying `pg_replication_slots.sync_state` to ensure the slot is promoted and ready following a failover event.

Code MUST explicitly handle reconnects by querying `pg_replication_slots.sync_state` to ensure the slot is promoted and ready following a failover event.

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 persist committed downstream consumer offsets idempotently alongside transaction boundaries to prevent duplicate processing on slot rewind.

Services MUST persist committed downstream consumer offsets idempotently alongside transaction boundaries to prevent duplicate processing on slot rewind.

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 physical replication slot names correspond to logical slots without verifying `sync_state = 'synced'` on the standby replica.

Components NEVER assume physical replication slot names correspond to logical slots without verifying `sync_state = 'synced'` on the standby replica.

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 Sync & Logical Replication Invariants critical for AI coding assistants?

Enforces failover-safe logical replication slots introduced in PostgreSQL 17 to prevent message loss or unbounded re-streaming during high-availability switchovers. Mandates `failover = true` on logical slots, strict synchronization across physical standbys via `synchronized_standby_slots`, and downstream LSN tracking to uphold exactly-once or at-least-once CDC processing invariants. 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 that are dropped or rewound upon physical standby 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