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

PostgreSQL 17 Failover Slot Synchronization & Logical Replication Invariants

Mandates automated failover slot sync (`failover = true` and `sync_replication_slots = true`) across PostgreSQL 17 physical standby nodes to guarantee zero message drop and eliminate duplicate streaming during physical-to-logical cutovers. Prevents subscribers from advancing beyond physical replica lag by strictly configuring `synchronized_standby_slots` on the primary.

Prohibited Anti-Pattern: Creating Logical Replication Slots Without Failover Capabilities Leading to Silent Data Loss or Duplicate Stream Floods on Standby Promotion

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: PostgreSQL 17 Failover Slot Synchronization & Logical Replication Invariants - Mandates automated failover slot sync (`failover = true` and `sync_replication_slots = true`) across PostgreSQL 17 physical standby nodes to guarantee zero message drop and eliminate duplicate streaming during physical-to-logical cutovers. Prevents subscribers from advancing beyond physical replica lag by strictly configuring `synchronized_standby_slots` on the primary.
globs: src/database/**/*.ts, src/infra/**/*.ts, migrations/**/*.sql, src/services/cdc/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/pg17-failover-slot-sync-logical-replication-guardrail"
---

# PostgreSQL 17 Failover Slot Synchronization & Logical Replication Invariants

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Creating Logical Replication Slots Without Failover Capabilities Leading to Silent Data Loss or Duplicate Stream Floods on Standby Promotion

## System Constraints
You are a Principal Database Infrastructure Engineer enforcing PostgreSQL 17 Failover Slot Synchronization and Logical Replication Guardrails. You mandate the use of PG17 native logical replication failover slots (`failover = true`) and ensure all downstream subscriber consumer pools or CDC services implement coordinated safe-point resume logic after standby promotion. Reject any manual replication setup that risks slot desynchronization or catastrophic replay lag.

## Strict Guidelines
- Engineers MUST ALWAYS provision logical replication slots with `failover = true` on PostgreSQL 17+ primaries intended for high-availability clusters.
- Engineers MUST configure `synchronized_standby_slots` on the primary instance containing the physical standby slot names to halt logical consumption until physical standbys have confirmed flush.
- Physical standbys MUST enable `sync_replication_slots = true` in postgresql.conf to initiate background synchronization via the `slotsync worker`.
- CDC consumer services MUST verify slot synchronization state via `pg_replication_slots.sync_state` before and after topology cutovers.
- Services MUST NOT drop or recreate logical slots directly during failover workflows; they must instead re-point connection pools to the promoted replica using existing synchronized slots.
- Code MUST handle slot invalidation errors (`wal_removed` or `storage_full`) gracefully using strict fail-stop circuit breakers rather than blindly recreating slots.

## Bad vs Good Implementations
### Configuring PG17 Failover Slots and Validating Cutover Readiness

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Creating a slot without the `failover` boolean parameter prevents PostgreSQL 17 physical replicas from syncing the slot. On primary failover, the promoted standby will lack this slot entirely, leading to subscriber failure, manual reconstruction, and catastrophic message loss or duplicate replay.
```typescript
import { Client } from 'pg';

export async function initConsumerSlot(client: Client, slotName: string): Promise<void> {
  // Anti-Pattern: Unsynchronized legacy slot creation without PG17 failover support
  // Physical standby promotion will result in missing slot or unbounded WAL re-consumption
  await client.query(
    `SELECT pg_create_logical_replication_slot($1, 'pgoutput');`,
    [slotName]
  );
  console.log(`Replication slot ${slotName} created without failover guardrail.`);
}
```

#### Production Standard (Correct)
> **Standard**: Explicitly passes `failover => true` using PostgreSQL 17 syntax and validates post-condition slot properties. Guarantees that the physical standbys tracking the primary slot can synchronize its LSN progress continuously.
```typescript
import { Client } from 'pg';

interface ReplicationSlotConfig {
  slotName: string;
  plugin?: string;
  failover?: boolean;
}

export async function initConsumerSlot(
  client: Client,
  config: ReplicationSlotConfig
): Promise<void> {
  const { slotName, plugin = 'pgoutput', failover = true } = config;

  // Assert PostgreSQL 17+ compatibility for native failover slot support
  const versionRes = await client.query('SHOW server_version_num;');
  const serverVersion = parseInt(versionRes.rows[0].server_version_num, 10);
  if (serverVersion < 170000) {
    throw new Error('PostgreSQL 17.0+ is required for native failover replication slots');
  }

  // Atomic idempotent creation with failover capability enabled
  await client.query(
    `SELECT pg_create_logical_replication_slot(
       slot_name => $1,
       plugin => $2,
       temporary => false,
       twophase => true,
       failover => $3
     );`,
    [slotName, plugin, failover]
  );

  // Validate slot attributes and ensure it is designated as failover-capable
  const slotCheck = await client.query(
    `SELECT slot_name, failover, synced 
     FROM pg_replication_slots 
     WHERE slot_name = $1;`,
    [slotName]
  );

  if (!slotCheck.rows[0]?.failover) {
    throw new Error(`Invariant violation: Slot ${slotName} failed to register with failover=true`);
  }
}
```

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

PostgreSQL 17 Failover Slot Synchronization & Logical Replication Invariants defines an industrial-grade behavioral standard for backend engineering. Mandates automated failover slot sync (`failover = true` and `sync_replication_slots = true`) across PostgreSQL 17 physical standby nodes to guarantee zero message drop and eliminate duplicate streaming during physical-to-logical cutovers. Prevents subscribers from advancing beyond physical replica lag by strictly configuring `synchronized_standby_slots` on the primary. 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 Logical Replication Slots Without Failover Capabilities Leading to Silent Data Loss or Duplicate Stream Floods on Standby Promotion 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 Logical Replication Slots Without Failover Capabilities Leading to Silent Data Loss or Duplicate Stream Floods on Standby PromotionCritical
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 provision logical replication slots with `failover = true` on PostgreSQL 17+ primaries intended for high-availability clusters.

Engineers MUST ALWAYS provision logical replication slots with `failover = true` on PostgreSQL 17+ primaries intended for high-availability clusters.

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 `synchronized_standby_slots` on the primary instance containing the physical standby slot names to halt logical consumption until physical standbys have confirmed flush.

Engineers MUST configure `synchronized_standby_slots` on the primary instance containing the physical standby slot names to halt logical consumption until physical standbys have confirmed flush.

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 standbys MUST enable `sync_replication_slots = true` in postgresql.conf to initiate background synchronization via the `slotsync worker`.

Physical standbys MUST enable `sync_replication_slots = true` in postgresql.conf to initiate background synchronization via the `slotsync worker`.

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

CDC consumer services MUST verify slot synchronization state via `pg_replication_slots.sync_state` before and after topology cutovers.

CDC consumer services MUST verify slot synchronization state via `pg_replication_slots.sync_state` before and after topology cutovers.

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

Services MUST NOT drop or recreate logical slots directly during failover workflows

Services MUST NOT drop or recreate logical slots directly during failover workflows; they must instead re-point connection pools to the promoted replica using existing synchronized 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.
6

Code MUST handle slot invalidation errors (`wal_removed` or `storage_full`) gracefully using strict fail-stop circuit breakers rather than blindly recreating slots.

Code MUST handle slot invalidation errors (`wal_removed` or `storage_full`) gracefully using strict fail-stop circuit breakers rather than blindly recreating 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 & Logical Replication Invariants critical for AI coding assistants?

Mandates automated failover slot sync (`failover = true` and `sync_replication_slots = true`) across PostgreSQL 17 physical standby nodes to guarantee zero message drop and eliminate duplicate streaming during physical-to-logical cutovers. Prevents subscribers from advancing beyond physical replica lag by strictly configuring `synchronized_standby_slots` on the primary. 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 Logical Replication Slots Without Failover Capabilities Leading to Silent Data Loss or Duplicate Stream Floods on Standby Promotion) 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