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

PostgreSQL 17 Failover Slot Sync & CDC Continuity Guardrail

Enforces PostgreSQL 17 native logical replication failover slot synchronization and LSN progression controls across high-availability clusters. Guarantees logical replication slots survive automated primary failovers without CDC event stream duplication, un-replicated transaction loss, or pipeline restart panics.

Prohibited Anti-Pattern: Creating un-synchronized logical slots without failover flags and standby_slot_names coordination

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: PostgreSQL 17 Failover Slot Sync & CDC Continuity Guardrail - Enforces PostgreSQL 17 native logical replication failover slot synchronization and LSN progression controls across high-availability clusters. Guarantees logical replication slots survive automated primary failovers without CDC event stream duplication, un-replicated transaction loss, or pipeline restart panics.
globs: src/database/**/*.ts, src/services/cdc/**/*.ts, src/infra/**/*.sql, migrations/**/*.sql, deploy/**/*.yaml
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/postgres-17-standby-failover-slot-sync-standard"
---

# PostgreSQL 17 Failover Slot Sync & CDC Continuity Guardrail

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Creating un-synchronized logical slots without failover flags and standby_slot_names coordination

## System Constraints
You are a Principal Database Architect enforcing PostgreSQL 17 Logical Replication Slot Synchronization Standards. Mandate native failover slot coordination, correct WAL retention guarantees across physical standbys via standby_slot_names, and deterministic LSN resume strategies for CDC consumers.

## Strict Guidelines
- Engineers MUST ALWAYS provision logical replication slots with failover enabled using PostgreSQL 17's extended signature: pg_create_logical_replication_slot(slot_name, plugin, temporary, two_phase, failover => true).
- Engineers MUST configure standby_slot_names on the primary instance containing all critical physical standbys, ensuring WAL is not recycled before standbys consume it and preventing logical slots from advancing ahead of physical standbys.
- Standby replicas MUST configure sync_replication_slots = true and specify dbname in primary_conninfo to run the slotsync background worker.
- CDC consumer services MUST track confirmed_flush_lsn and implement idempotent transactional sinks to gracefully handle the bounded replay gap inherent after standby promotion.
- Engineers MUST NOT attempt to consume or advance synchronized slots directly on a standby replica while it remains in recovery; consumption must only transition once the standby promotes to primary.
- Database migration scripts and infrastructure code MUST verify server_version_num >= 170000 before invoking native failover slot parameters.

## Bad vs Good Implementations
### Logical Replication Slot Provisioning & Verification

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Creating a logical replication slot without failover => true means the standby slot sync worker will ignore this slot. When an automated failover occurs, the new primary will not possess this slot, causing CDC pipelines to panic and require full, costly resynchronization.
```typescript
import { Client } from 'pg';

export async function setupCdcSlot(client: Client, slotName: string): Promise<void> {
  // Flaw: Omits PostgreSQL 17 failover parameter;
  // slot will be lost permanently upon HA standby failover.
  await client.query(
    `SELECT pg_create_logical_replication_slot($1, 'pgoutput');`,
    [slotName]
  );
}
```

#### Production Standard (Correct)
> **Standard**: Validates engine version, guarantees the primary uses standby_slot_names to avoid replication divergence, and provisions the slot with failover => true so the PG17 slotsync worker maintains identical LSN states on standby replicas.
```typescript
import { Client } from 'pg';

interface SlotConfig {
  slotName: string;
  plugin?: string;
  twoPhase?: boolean;
}

export async function setupFailoverSafeCdcSlot(
  client: Client,
  config: SlotConfig
): Promise<void> {
  const { slotName, plugin = 'pgoutput', twoPhase = false } = config;

  // 1. Verify PostgreSQL 17+ for native failover support
  const versionRes = await client.query<{ server_version_num: string }>(
    'SHOW server_version_num;'
  );
  const version = parseInt(versionRes.rows[0].server_version_num, 10);
  if (version < 170000) {
    throw new Error('PostgreSQL 17+ is required for native failover slot synchronization.');
  }

  // 2. Verify primary enforces physical standby replication synchronization
  const standbyCheck = await client.query<{ setting: string }>(
    "SELECT setting FROM pg_settings WHERE name = 'standby_slot_names';"
  );
  if (!standbyCheck.rows[0]?.setting) {
    throw new Error(
      'CRITICAL: standby_slot_names must be configured on primary to prevent physical-logical WAL race.'
    );
  }

  // 3. Provision slot with native failover enabled
  await client.query(
    `SELECT pg_create_logical_replication_slot(
       slot_name => $1,
       plugin => $2,
       temporary => false,
       two_phase => $3,
       failover => true
     );`,
    [slotName, plugin, twoPhase]
  );
}
```

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 Sync & CDC Continuity Guardrail

PostgreSQL 17 Failover Slot Sync & CDC Continuity Guardrail defines an industrial-grade behavioral standard for backend engineering. Enforces PostgreSQL 17 native logical replication failover slot synchronization and LSN progression controls across high-availability clusters. Guarantees logical replication slots survive automated primary failovers without CDC event stream duplication, un-replicated transaction loss, or pipeline restart panics. 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 un-synchronized logical slots without failover flags and standby_slot_names coordination 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 un-synchronized logical slots without failover flags and standby_slot_names coordinationCritical
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 enabled using PostgreSQL 17's extended signature

Engineers MUST ALWAYS provision logical replication slots with failover enabled using PostgreSQL 17's extended signature: pg_create_logical_replication_slot(slot_name, plugin, temporary, two_phase, failover => 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

Engineers MUST configure standby_slot_names on the primary instance containing all critical physical standbys, ensuring WAL is not recycled before standbys consume it and preventing logical slots from advancing ahead of physical standbys.

Engineers MUST configure standby_slot_names on the primary instance containing all critical physical standbys, ensuring WAL is not recycled before standbys consume it and preventing logical slots from advancing ahead of 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.
3

Standby replicas MUST configure sync_replication_slots = true and specify dbname in primary_conninfo to run the slotsync background worker.

Standby replicas MUST configure sync_replication_slots = true and specify dbname in primary_conninfo to run the slotsync background 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 track confirmed_flush_lsn and implement idempotent transactional sinks to gracefully handle the bounded replay gap inherent after standby promotion.

CDC consumer services MUST track confirmed_flush_lsn and implement idempotent transactional sinks to gracefully handle the bounded replay gap inherent after standby 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

Engineers MUST NOT attempt to consume or advance synchronized slots directly on a standby replica while it remains in recovery

Engineers MUST NOT attempt to consume or advance synchronized slots directly on a standby replica while it remains in recovery; consumption must only transition once the standby promotes to primary.

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

Database migration scripts and infrastructure code MUST verify server_version_num >= 170000 before invoking native failover slot parameters.

Database migration scripts and infrastructure code MUST verify server_version_num >= 170000 before invoking native failover slot parameters.

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 & CDC Continuity Guardrail critical for AI coding assistants?

Enforces PostgreSQL 17 native logical replication failover slot synchronization and LSN progression controls across high-availability clusters. Guarantees logical replication slots survive automated primary failovers without CDC event stream duplication, un-replicated transaction loss, or pipeline restart panics. 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 un-synchronized logical slots without failover flags and standby_slot_names coordination) 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