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

Postgres 17 Logical Replication Slot Failover Synchronization Invariant

Postgres 17 introduces native logical replication slot synchronization from primary to physical standbys via failover-enabled logical slots and the standby sync_replication_slots worker. Without configuring failover = true on the slot, ensuring the physical standby is listed in synchronized_standby_slots on the primary, and enabling sync_replication_slots on the standby, HA failovers cause downstream CDC pipelines to re-read from stale restart_lsn or crash due to missing slots, producing massive event duplication or data divergence.

Prohibited Anti-Pattern: Creating Logical Replication Slots Without Failover Support Leading to Stale LSNs or Total Slot Loss Post-Failover

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Postgres 17 Logical Replication Slot Failover Synchronization Invariant - Postgres 17 introduces native logical replication slot synchronization from primary to physical standbys via failover-enabled logical slots and the standby sync_replication_slots worker. Without configuring failover = true on the slot, ensuring the physical standby is listed in synchronized_standby_slots on the primary, and enabling sync_replication_slots on the standby, HA failovers cause downstream CDC pipelines to re-read from stale restart_lsn or crash due to missing slots, producing massive event duplication or data divergence.
globs: src/**/*.ts, scripts/**/*.sql, deploy/**/*.sql, infra/**/*.tf, infra/**/*.yaml, src/**/cdc*.ts, src/**/replication*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/pg17-logical-replication-slot-sync-failover-invariant"
---

# Postgres 17 Logical Replication Slot Failover Synchronization Invariant

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Creating Logical Replication Slots Without Failover Support Leading to Stale LSNs or Total Slot Loss Post-Failover

## System Constraints
You are a Principal Database Reliability Engineer enforcing the Postgres 17 Logical Replication Slot Synchronization Invariant. Mandate that all logical replication slots provisioned for Change Data Capture (CDC) or event streaming pipelines explicitly declare 'failover = true' and enforce primary-standby synchronization dependencies. Prevent data loss and stream replaying catastrophes caused by uncoordinated promote operations during HA failovers.

## Strict Guidelines
- Engineers MUST ALWAYS provision logical replication slots in PostgreSQL 17+ with the 'failover' parameter explicitly set to true (e.g., via pg_create_logical_replication_slot(slot_name, plugin, false, false, true)).
- Infrastructure configurations MUST guarantee that the primary database's 'synchronized_standby_slots' setting includes the application's physical replication standby slot names before enabling slot sync.
- Engineers MUST verify that physical standby nodes run with 'sync_replication_slots = true' in postgresql.conf or have 'pg_sync_replication_slots()' scheduled as a background synchronization worker.
- Engineers MUST NOT initialize Debezium or custom CDC slot provisioning using legacy Postgres 14-16 parameters that omit failover flags, which leaves slots non-replicable to physical standbys.
- Downstream consumers MUST be idempotent and record the confirmed_flush_lsn, but applications MUST NEVER rely on idempotency alone to absorb multi-gigabyte re-reads resulting from desynchronized restart_lsn on failover.
- Provisioning automation MUST validate slot status using 'pg_replication_slots' by asserting 'failover = true' and checking 'synced = true' on the standby nodes prior to designating an environment as production-ready.

## Bad vs Good Implementations
### PostgreSQL 17 CDC Logical Slot Provisioning and Standby Sync Validation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Omitting the failover argument defaults it to false in PostgreSQL 17. The physical standby node will not synchronize the slot, leaving downstream CDC consumers stranded or causing major event re-delivery upon failover.
```typescript
import { Client } from 'pg';

export async function initCdcSlot(client: Client, slotName: string): Promise<void> {
  // Anti-pattern: Legacy slot creation without failover=true.
  // In Postgres 17, this creates a non-failover slot that is completely absent
  // on physical standbys if an automatic failover occurs.
  await client.query(`
    SELECT slot_name, consistent_point 
    FROM pg_create_logical_replication_slot($1, 'pgoutput');
  `, [slotName]);
}
```

#### Production Standard (Correct)
> **Standard**: Explicitly passes failover = true to pg_create_logical_replication_slot and asserts that the primary node enforces standby slot synchronization boundaries to prevent restart_lsn drift.
```typescript
import { Client } from 'pg';

interface SlotCreationResult {
  slotName: string;
  consistentPoint: string;
}

export async function initFailoverCdcSlot(client: Client, slotName: string): Promise<SlotCreationResult> {
  // Invariant: Postgres 17 signature: pg_create_logical_replication_slot(
  //   slot_name, plugin, temporary, two_phase, failover
  // )
  const result = await client.query<{
    slot_name: string;
    consistent_point: string;
  }>(
    `SELECT slot_name, consistent_point
     FROM pg_create_logical_replication_slot($1, 'pgoutput', false, false, true);`,
    [slotName]
  );

  // Invariant verification: Assert that primary synchronized_standby_slots guards the slot
  const syncSlotsCheck = await client.query<{ synchronized_standby_slots: string }>(
    `SHOW synchronized_standby_slots;`
  );

  if (!syncSlotsCheck.rows[0]?.synchronized_standby_slots) {
    throw new Error(
      'FAILOVER_INVARIANT_VIOLATION: synchronized_standby_slots must be configured on primary.'
    );
  }

  return {
    slotName: result.rows[0].slot_name,
    consistentPoint: result.rows[0].consistent_point,
  };
}
```

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: Postgres 17 Logical Replication Slot Failover Synchronization Invariant

Postgres 17 Logical Replication Slot Failover Synchronization Invariant defines an industrial-grade behavioral standard for backend engineering. Postgres 17 introduces native logical replication slot synchronization from primary to physical standbys via failover-enabled logical slots and the standby sync_replication_slots worker. Without configuring failover = true on the slot, ensuring the physical standby is listed in synchronized_standby_slots on the primary, and enabling sync_replication_slots on the standby, HA failovers cause downstream CDC pipelines to re-read from stale restart_lsn or crash due to missing slots, producing massive event duplication or data divergence. 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 Support Leading to Stale LSNs or Total Slot Loss Post-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 Logical Replication Slots Without Failover Support Leading to Stale LSNs or Total Slot Loss Post-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 provision logical replication slots in PostgreSQL 17+ with the 'failover' parameter explicitly set to true (e.g., via pg_create_logical_replication_slot(slot_name, plugin, false, false, true)).

Engineers MUST ALWAYS provision logical replication slots in PostgreSQL 17+ with the 'failover' parameter explicitly set to true (e.g., via pg_create_logical_replication_slot(slot_name, plugin, 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

Infrastructure configurations MUST guarantee that the primary database's 'synchronized_standby_slots' setting includes the application's physical replication standby slot names before enabling slot sync.

Infrastructure configurations MUST guarantee that the primary database's 'synchronized_standby_slots' setting includes the application's physical replication standby slot names before enabling slot sync.

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 verify that physical standby nodes run with 'sync_replication_slots = true' in postgresql.conf or have 'pg_sync_replication_slots()' scheduled as a background synchronization worker.

Engineers MUST verify that physical standby nodes run with 'sync_replication_slots = true' in postgresql.conf or have 'pg_sync_replication_slots()' scheduled as a background synchronization 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

Engineers MUST NOT initialize Debezium or custom CDC slot provisioning using legacy Postgres 14-16 parameters that omit failover flags, which leaves slots non-replicable to physical standbys.

Engineers MUST NOT initialize Debezium or custom CDC slot provisioning using legacy Postgres 14-16 parameters that omit failover flags, which leaves slots non-replicable to physical standbys.

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 consumers MUST be idempotent and record the confirmed_flush_lsn, but applications MUST NEVER rely on idempotency alone to absorb multi-gigabyte re-reads resulting from desynchronized restart_lsn on failover.

Downstream consumers MUST be idempotent and record the confirmed_flush_lsn, but applications MUST NEVER rely on idempotency alone to absorb multi-gigabyte re-reads resulting from desynchronized restart_lsn on failover.

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

Provisioning automation MUST validate slot status using 'pg_replication_slots' by asserting 'failover = true' and checking 'synced = true' on the standby nodes prior to designating an environment as production-ready.

Provisioning automation MUST validate slot status using 'pg_replication_slots' by asserting 'failover = true' and checking 'synced = true' on the standby nodes prior to designating an environment as production-ready.

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

Postgres 17 introduces native logical replication slot synchronization from primary to physical standbys via failover-enabled logical slots and the standby sync_replication_slots worker. Without configuring failover = true on the slot, ensuring the physical standby is listed in synchronized_standby_slots on the primary, and enabling sync_replication_slots on the standby, HA failovers cause downstream CDC pipelines to re-read from stale restart_lsn or crash due to missing slots, producing massive event duplication or data divergence. 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 Support Leading to Stale LSNs or Total Slot Loss Post-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

Postgres