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

PostgreSQL 17 Failover Slot Synchronization for Zero-Data-Loss CDC

Enforces failover replication slot synchronization introduced in PostgreSQL 17 to prevent silent data loss and unbounded duplication during physical cluster failovers. Requires failover-enabled logical slots on the primary, synchronized standby worker coordination via synchronized_standby_slots, and consumer LSN confirmation validation across streaming worker boundaries.

Prohibited Anti-Pattern: Creating unsynchronized logical replication slots on the primary without physical standby slot synchronization barriers

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: PostgreSQL 17 Failover Slot Synchronization for Zero-Data-Loss CDC - Enforces failover replication slot synchronization introduced in PostgreSQL 17 to prevent silent data loss and unbounded duplication during physical cluster failovers. Requires failover-enabled logical slots on the primary, synchronized standby worker coordination via synchronized_standby_slots, and consumer LSN confirmation validation across streaming worker boundaries.
globs: src/**/*.ts, src/database/**/*.ts, src/cdc/**/*.ts, infra/**/*.ts, scripts/**/*.sql
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/pg17-failover-slot-sync-cdc-guardrail"
---

# PostgreSQL 17 Failover Slot Synchronization for Zero-Data-Loss CDC

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Creating unsynchronized logical replication slots on the primary without physical standby slot synchronization barriers

## System Constraints
You are a Principal Engineer and Infrastructure Architect enforcing PostgreSQL 17 failover slot synchronization for Change Data Capture (CDC) pipelines. You must ensure that any logical replication slot creation explicitly specifies failover: true, that the primary postgresql.conf coordinates with physical standbys via synchronized_standby_slots, and that downstream Node.js/TypeScript CDC ingestors implement deterministic idempotent checkpointing anchored by confirmed_flush_lsn across promotion events.

## Strict Guidelines
- Engineers MUST ALWAYS create logical replication slots with failover = true via pg_create_logical_replication_slot() when running PostgreSQL 17+ in high-availability topographies.
- Engineers MUST configure 'synchronized_standby_slots' on the primary containing all physical standbys to prevent primary WAL removal prior to standby consumption.
- Services MUST verify slot synchronization state ('sync_state' in pg_replication_slots) on standby instances before allowing read-replica CDC consumers to attach.
- Engineers MUST NOT rely on default pg_create_logical_replication_slot parameters, as failover defaults to false and drops slots upon promotion.
- Consumers MUST track and commit confirmed_flush_lsn idempotently in application metadata storage to gracefully handle rewinds across newly promoted primaries.

## Bad vs Good Implementations
### PostgreSQL 17 Slot Provisioning and Idempotent Ingestion Checkpoint

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Omitting the failover boolean creates a legacy logical replication slot. In PostgreSQL 17, failing over to a standby causes complete slot loss, forcing operators to recreate the slot from current WAL, resulting in permanent data loss for CDC consumers.
```typescript
import { Client } from 'pg';

export async function setupCdcPipeline(client: Client, slotName: string): Promise<void> {
  // Anti-pattern: omitting failover parameter (defaults to false)
  // If the primary fails over, the slot does not exist on the promoted standby,
  // leading to unrecoverable CDC interruption and dropped mutations.
  await client.query(`
    SELECT pg_create_logical_replication_slot($1, 'pgoutput');
  `, [slotName]);

  // Unchecked ingestion stream that does not verify slot synchronization
  console.log(`Slot ${slotName} created without failover guard.`);
}
```

#### Production Standard (Correct)
> **Standard**: Explicitly verifies the cluster has synchronized_standby_slots configured to halt primary WAL recycling until standbys are caught up, and passes failover = true to pg_create_logical_replication_slot so PG17 standby worker daemons replicate the logical slot metadata automatically.
```typescript
import { Client } from 'pg';

export interface SlotSyncConfig {
  slotName: string;
  plugin?: string;
  standbySlotNames: string[];
}

export async function provisionSynchronizedCdcSlot(
  client: Client,
  config: SlotSyncConfig
): Promise<{ slotName: string; lsn: string }> {
  const plugin = config.plugin ?? 'pgoutput';

  // Invariant 1: Ensure primary blocks WAL recycling until standbys sync
  const syncSettingRes = await client.query<{ setting: string }>(
    `SHOW synchronized_standby_slots;`
  );
  const configuredStandbys = syncSettingRes.rows[0]?.setting?.split(',').map(s => s.trim()) ?? [];
  const isConfigured = config.standbySlotNames.every(name => configuredStandbys.includes(name));

  if (!isConfigured) {
    throw new Error(
      `Primary synchronized_standby_slots does not contain all required physical standbys: ${config.standbySlotNames.join(', ')}`
    );
  }

  // Invariant 2: Create logical slot with PG17 failover = true
  const res = await client.query<{ slot_name: string; lsn: string }>(
    `SELECT slot_name, lsn FROM pg_create_logical_replication_slot(
       $1,
       $2,
       false, -- temporary
       false, -- two_phase
       true   -- failover (PG17+)
     );`,
    [config.slotName, plugin]
  );

  return res.rows[0];
}
```

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 for Zero-Data-Loss CDC

PostgreSQL 17 Failover Slot Synchronization for Zero-Data-Loss CDC defines an industrial-grade behavioral standard for backend engineering. Enforces failover replication slot synchronization introduced in PostgreSQL 17 to prevent silent data loss and unbounded duplication during physical cluster failovers. Requires failover-enabled logical slots on the primary, synchronized standby worker coordination via synchronized_standby_slots, and consumer LSN confirmation validation across streaming worker boundaries. 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 unsynchronized logical replication slots on the primary without physical standby slot synchronization barriers 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 unsynchronized logical replication slots on the primary without physical standby slot synchronization barriersCritical
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 via pg_create_logical_replication_slot() when running PostgreSQL 17+ in high-availability topographies.

Engineers MUST ALWAYS create logical replication slots with failover = true via pg_create_logical_replication_slot() when running PostgreSQL 17+ in high-availability topographies.

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 containing all physical standbys to prevent primary WAL removal prior to standby consumption.

Engineers MUST configure 'synchronized_standby_slots' on the primary containing all physical standbys to prevent primary WAL removal prior to standby consumption.

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

Services MUST verify slot synchronization state ('sync_state' in pg_replication_slots) on standby instances before allowing read-replica CDC consumers to attach.

Services MUST verify slot synchronization state ('sync_state' in pg_replication_slots) on standby instances before allowing read-replica CDC consumers to attach.

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 rely on default pg_create_logical_replication_slot parameters, as failover defaults to false and drops slots upon promotion.

Engineers MUST NOT rely on default pg_create_logical_replication_slot parameters, as failover defaults to false and drops slots upon promotion.

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

Consumers MUST track and commit confirmed_flush_lsn idempotently in application metadata storage to gracefully handle rewinds across newly promoted primaries.

Consumers MUST track and commit confirmed_flush_lsn idempotently in application metadata storage to gracefully handle rewinds across newly promoted 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.
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 for Zero-Data-Loss CDC critical for AI coding assistants?

Enforces failover replication slot synchronization introduced in PostgreSQL 17 to prevent silent data loss and unbounded duplication during physical cluster failovers. Requires failover-enabled logical slots on the primary, synchronized standby worker coordination via synchronized_standby_slots, and consumer LSN confirmation validation across streaming worker boundaries. 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 unsynchronized logical replication slots on the primary without physical standby slot synchronization barriers) 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