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

PostgreSQL 17 Failover-Safe Logical Replication Slot Synchronization

Enforces mandatory failover slot synchronization and physical standby synchronization boundaries for logical replication slots in PostgreSQL 17 topologies. Eliminates downstream CDC data loss, silent event skips, and replication lag panics during physical replica promotion by ensuring logical slots are synchronized to physical standbys with sync_replication_slots enabled. Prevents consumer consumption ahead of physical standby persistence.

Prohibited Anti-Pattern: Creating unmanaged logical replication slots without failover sync or synchronized_standby_slots tracking

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: PostgreSQL 17 Failover-Safe Logical Replication Slot Synchronization - Enforces mandatory failover slot synchronization and physical standby synchronization boundaries for logical replication slots in PostgreSQL 17 topologies. Eliminates downstream CDC data loss, silent event skips, and replication lag panics during physical replica promotion by ensuring logical slots are synchronized to physical standbys with sync_replication_slots enabled. Prevents consumer consumption ahead of physical standby persistence.
globs: src/database/**/*.{ts,js,sql}, src/infra/**/*.{ts,js,tf,yaml}, src/cdc/**/*.{ts,js}, migrations/**/*.{sql,ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/pg17-logical-replication-failover-slot-sync-standard"
---

# PostgreSQL 17 Failover-Safe Logical Replication Slot Synchronization

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Creating unmanaged logical replication slots without failover sync or synchronized_standby_slots tracking

## System Constraints
You are a Principal Database Reliability Engineer enforcing the PostgreSQL 17 Logical Replication Failover Slot Synchronization Standard. Mandate that every logical replication slot configuration explicitly uses failover: true, pairs with synchronized_standby_slots on the primary node, and verifies standby sync via pg_sync_replication_slots() or pg_replication_slots before permitting CDC subscriber cutover. Disallow unmanaged pg_create_logical_replication_slot invocations that omit failover flags.

## Strict Guidelines
- Engineers MUST ALWAYS provision logical replication slots with the 'failover' parameter explicitly set to true (pg_create_logical_replication_slot(slot_name, plugin, false, false, true)) in PostgreSQL 17+.
- Engineers MUST configure 'synchronized_standby_slots' on the primary cluster to include the application's physical replication standby slots, ensuring WAL changes are acknowledged by physical standbys before logical consumers can consume them.
- Code MUST verify slot synchronization state by querying 'pg_replication_slots' for 'sync_state' and 'failover' flags prior to connecting downstream CDC consumers.
- Services MUST NOT execute promotion of a physical standby without ensuring downstream logical consumers re-point to synchronized slots on the promoted primary without recreation.
- Engineers MUST configure 'sync_replication_slots = on' on physical standby nodes when configuring automated slot synchronization daemon processes.

## Bad vs Good Implementations
### Configuring Postgres 17 Logical Replication Slot with Failover Protection

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Legacy pg_create_logical_replication_slot calls omit the failover boolean flag. Under Postgres 17, omitting this prevents physical standbys from syncing slot LSN positions, resulting in data loss or CDC broker failure during physical node promotion.
```typescript
import { Client } from 'pg';

export async function initCdcSlot(client: Client, slotName: string): Promise<void> {
  // ANTI-PATTERN: Creates legacy logical slot without PG17 failover attribute.
  // During physical failover, this slot will NOT exist on the promoted standby,
  // leading to lost CDC state or complete subscriber re-sync from scratch.
  await client.query(
    `SELECT pg_create_logical_replication_slot($1, 'pgoutput');`,
    [slotName]
  );
}
```

#### Production Standard (Correct)
> **Standard**: Leverages the PostgreSQL 17 pg_create_logical_replication_slot fifth parameter (failover = true), validates existing slot failover properties, and confirms the cluster enforces synchronized_standby_slots to prevent data skip anomalies upon physical HA failover.
```typescript
import { Client } from 'pg';

export interface ReplicationSlotStatus {
  slotName: string;
  plugin: string;
  failover: boolean;
  synced: boolean;
}

export async function initFailoverSafeCdcSlot(client: Client, slotName: string): Promise<ReplicationSlotStatus> {
  // Check if slot exists with proper PG17 failover support
  const checkQuery = `
    SELECT slot_name, plugin, failover, synced 
    FROM pg_replication_slots 
    WHERE slot_name = $1;
  `;
  const { rows } = await client.query(checkQuery, [slotName]);
  
  if (rows.length === 0) {
    // PG17 signature: pg_create_logical_replication_slot(slot_name, plugin, temporary, two_phase, failover)
    await client.query(
      `SELECT pg_create_logical_replication_slot($1, 'pgoutput', false, false, true);`,
      [slotName]
    );
  } else if (!rows[0].failover) {
    throw new Error(`Slot ${slotName} exists but failover flag is false. Manual migration required.`);
  }

  // Primary invariant verification: ensure slot is listed in synchronized_standby_slots
  const syncCheck = await client.query(`SHOW synchronized_standby_slots;`);
  if (!syncCheck.rows[0].synchronized_standby_slots) {
    throw new Error('Postgres 17 primary must define synchronized_standby_slots to guard CDC ordering');
  }

  return {
    slotName,
    plugin: 'pgoutput',
    failover: true,
    synced: rows[0]?.synced ?? false
  };
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: PostgreSQL 17 Failover-Safe Logical Replication Slot Synchronization

PostgreSQL 17 Failover-Safe Logical Replication Slot Synchronization defines an industrial-grade behavioral standard for backend engineering. Enforces mandatory failover slot synchronization and physical standby synchronization boundaries for logical replication slots in PostgreSQL 17 topologies. Eliminates downstream CDC data loss, silent event skips, and replication lag panics during physical replica promotion by ensuring logical slots are synchronized to physical standbys with sync_replication_slots enabled. Prevents consumer consumption ahead of physical standby persistence. 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 without failover sync or synchronized_standby_slots tracking 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 without failover sync or synchronized_standby_slots trackingCritical
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 the 'failover' parameter explicitly set to true (pg_create_logical_replication_slot(slot_name, plugin, false, false, true)) in PostgreSQL 17+.

Engineers MUST ALWAYS provision logical replication slots with the 'failover' parameter explicitly set to true (pg_create_logical_replication_slot(slot_name, plugin, false, false, true)) in PostgreSQL 17+.

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 cluster to include the application's physical replication standby slots, ensuring WAL changes are acknowledged by physical standbys before logical consumers can consume them.

Engineers MUST configure 'synchronized_standby_slots' on the primary cluster to include the application's physical replication standby slots, ensuring WAL changes are acknowledged by physical standbys before logical consumers can consume them.

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 verify slot synchronization state by querying 'pg_replication_slots' for 'sync_state' and 'failover' flags prior to connecting downstream CDC consumers.

Code MUST verify slot synchronization state by querying 'pg_replication_slots' for 'sync_state' and 'failover' flags prior to connecting downstream CDC consumers.

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 NOT execute promotion of a physical standby without ensuring downstream logical consumers re-point to synchronized slots on the promoted primary without recreation.

Services MUST NOT execute promotion of a physical standby without ensuring downstream logical consumers re-point to synchronized slots on the promoted primary without recreation.

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 configure 'sync_replication_slots = on' on physical standby nodes when configuring automated slot synchronization daemon processes.

Engineers MUST configure 'sync_replication_slots = on' on physical standby nodes when configuring automated slot synchronization daemon processes.

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-Safe Logical Replication Slot Synchronization critical for AI coding assistants?

Enforces mandatory failover slot synchronization and physical standby synchronization boundaries for logical replication slots in PostgreSQL 17 topologies. Eliminates downstream CDC data loss, silent event skips, and replication lag panics during physical replica promotion by ensuring logical slots are synchronized to physical standbys with sync_replication_slots enabled. Prevents consumer consumption ahead of physical standby persistence. 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 without failover sync or synchronized_standby_slots tracking) 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