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

Postgres 17 Failover Slot Logical Replication Synchronization Standard

Enforces strict configuration and application-level handling of PostgreSQL 17 native failover-enabled logical replication slots. Guarantees zero event loss and seamless LSN continuity across change-data-capture (CDC) pipelines and event-driven microservices during physical database failovers.

Prohibited Anti-Pattern: Creating Non-Failover Logical Slots and Dropping/Recreating Slots on Standby Promotion

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Postgres 17 Failover Slot Logical Replication Synchronization Standard - Enforces strict configuration and application-level handling of PostgreSQL 17 native failover-enabled logical replication slots. Guarantees zero event loss and seamless LSN continuity across change-data-capture (CDC) pipelines and event-driven microservices during physical database failovers.
globs: src/**/*.{ts,js,sql}, migrations/**/*.{ts,sql}, infra/**/*.{ts,tf,yaml}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/postgres-17-failover-logical-replication-sync"
---

# Postgres 17 Failover Slot Logical Replication Synchronization Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Creating Non-Failover Logical Slots and Dropping/Recreating Slots on Standby Promotion

## System Constraints
You are a Principal Database Architect and Backend Systems Engineer enforcing Postgres 17 Failover Slot Logical Replication Synchronization. You mandate that all logical replication slots utilized by distributed CDC pipelines, outbox pattern workers, and event streaming systems are provisioned with native failover capability (`failover = true`) and that primary instances configure `synchronized_standby_slots` to prevent slot advancement beyond physical replica recovery positions. Reject any implementation that attempts to drop and recreate logical replication slots upon failover detection or connects CDC listeners without LSN continuity verification.

## Strict Guidelines
- Engineers MUST ALWAYS provision logical replication slots with `failover = true` in PostgreSQL 17+ via `pg_create_logical_replication_slot(slot_name, plugin, false, false, true)` or declarative subscription definitions.
- Engineers MUST NOT allow logical replication slots to advance past physical replication standbys; the primary instance's `synchronized_standby_slots` setting MUST include all critical standby physical slot names.
- Services MUST implement standby synchronization verification via `sync_replication_slots = true` in `postgresql.conf` on standby nodes or periodically execute `pg_sync_replication_slots()` prior to client promotion switches.
- CDC consumer services MUST NEVER execute `DROP_REPLICATION_SLOT` or recreate replication slots upon encountering failover or primary disconnect errors.
- Client connection pools for replication streams MUST inspect `pg_replication_slots.confirmed_flush_lsn` upon reconnecting to a newly promoted primary to resume streaming deterministically from the last persisted position.

## Bad vs Good Implementations
### Provisioning and Consuming Postgres 17 Failover-Enabled Logical Replication Slots

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Creating the slot without failover=>true causes physical standbys to ignore the logical slot. Standby promotion leaves the slot missing or invalid on the new primary. Dropping and recreating the slot on reconnect resets the confirmed_flush_lsn to current WAL, causing catastrophic message loss in the event pipeline.
```typescript
import { Client } from 'pg';

export async function setupCdcPipeline(client: Client, slotName: string): Promise<void> {
  // Flaw 1: Legacy Postgres syntax lacking failover = true parameter
  // Flaw 2: Dropping slot upon connection failure resets LSN and loses messages
  try {
    await client.query(
      `SELECT pg_create_logical_replication_slot($1, 'pgoutput');`,
      [slotName]
    );
  } catch (err: any) {
    if (err.code === '42710') {
      // Flaw 3: Recreating slot blindly on reconnect drops unconsumed WAL
      await client.query(`SELECT pg_drop_replication_slot($1);`, [slotName]);
      await client.query(
        `SELECT pg_create_logical_replication_slot($1, 'pgoutput');`,
        [slotName]
      );
    }
  }
}
```

#### Production Standard (Correct)
> **Standard**: Explicitly passes `failover => true` to `pg_create_logical_replication_slot` in Postgres 17. Verifies slot existence and alters existing slots to enable failover if missing. Avoids destructive drops and preserves `confirmed_flush_lsn` across physical failover events.
```typescript
import { Client } from 'pg';

export interface SlotSyncStatus {
  slotName: string;
  plugin: string;
  failover: boolean;
  confirmedFlushLsn: string | null;
  synced: boolean;
}

export async function ensureFailoverLogicalSlot(
  client: Client,
  slotName: string
): Promise<SlotSyncStatus> {
  // Invariant 1: Ensure Postgres 17+ failover-enabled logical slot
  const checkSlotQuery = `
    SELECT slot_name, plugin, failover, confirmed_flush_lsn, synced
    FROM pg_replication_slots
    WHERE slot_name = $1;
  `;
  const checkRes = await client.query(checkSlotQuery, [slotName]);

  if (checkRes.rows.length === 0) {
    // Invariant 2: Create slot with failover = true (PG17: pg_create_logical_replication_slot(slot_name, plugin, temporary, two_phase, failover))
    await client.query(
      `SELECT pg_create_logical_replication_slot(
        slot_name => $1,
        plugin => 'pgoutput',
        temporary => false,
        two_phase => false,
        failover => true
      );`,
      [slotName]
    );
  } else {
    const slot = checkRes.rows[0];
    // Invariant 3: Validate and mutate existing slot to enforce failover if unconfigured
    if (!slot.failover) {
      await client.query(
        `ALTER_REPLICATION_SLOT $1 (failover true);`,
        [slotName]
      );
    }
  }

  const verified = await client.query(checkSlotQuery, [slotName]);
  const row = verified.rows[0];
  return {
    slotName: row.slot_name,
    plugin: row.plugin,
    failover: row.failover,
    confirmedFlushLsn: row.confirmed_flush_lsn,
    synced: row.synced
  };
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Postgres 17 Failover Slot Logical Replication Synchronization Standard

Postgres 17 Failover Slot Logical Replication Synchronization Standard defines an industrial-grade behavioral standard for backend engineering. Enforces strict configuration and application-level handling of PostgreSQL 17 native failover-enabled logical replication slots. Guarantees zero event loss and seamless LSN continuity across change-data-capture (CDC) pipelines and event-driven microservices during physical database failovers. 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 Non-Failover Logical Slots and Dropping/Recreating Slots 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 Non-Failover Logical Slots and Dropping/Recreating Slots 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` in PostgreSQL 17+ via `pg_create_logical_replication_slot(slot_name, plugin, false, false, true)` or declarative subscription definitions.

Engineers MUST ALWAYS provision logical replication slots with `failover = true` in PostgreSQL 17+ via `pg_create_logical_replication_slot(slot_name, plugin, false, false, true)` or declarative subscription definitions.

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 NOT allow logical replication slots to advance past physical replication standbys

Engineers MUST NOT allow logical replication slots to advance past physical replication standbys; the primary instance's `synchronized_standby_slots` setting MUST include all critical standby physical slot names.

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 implement standby synchronization verification via `sync_replication_slots = true` in `postgresql.conf` on standby nodes or periodically execute `pg_sync_replication_slots()` prior to client promotion switches.

Services MUST implement standby synchronization verification via `sync_replication_slots = true` in `postgresql.conf` on standby nodes or periodically execute `pg_sync_replication_slots()` prior to client promotion switches.

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 NEVER execute `DROP_REPLICATION_SLOT` or recreate replication slots upon encountering failover or primary disconnect errors.

CDC consumer services MUST NEVER execute `DROP_REPLICATION_SLOT` or recreate replication slots upon encountering failover or primary disconnect errors.

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

Client connection pools for replication streams MUST inspect `pg_replication_slots.confirmed_flush_lsn` upon reconnecting to a newly promoted primary to resume streaming deterministically from the last persisted position.

Client connection pools for replication streams MUST inspect `pg_replication_slots.confirmed_flush_lsn` upon reconnecting to a newly promoted primary to resume streaming deterministically from the last persisted position.

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

Enforces strict configuration and application-level handling of PostgreSQL 17 native failover-enabled logical replication slots. Guarantees zero event loss and seamless LSN continuity across change-data-capture (CDC) pipelines and event-driven microservices during physical database failovers. 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 Non-Failover Logical Slots and Dropping/Recreating Slots 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

Postgres