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

PostgreSQL 17 Logical Replication Slot Failover and Standby Synchronization Protocol

Mandates strict declaration and management of PostgreSQL 17 failover-enabled logical replication slots (`failover = true`), coupled with primary `synchronized_standby_slots` retention and standby slot synchronization daemon orchestration. Prevents silent CDC stream loss, invalid LSN rewinds, and WAL truncation across physical standby promotion boundaries.

Prohibited Anti-Pattern: Creating Logical Slots Without Failover Persistence or Standby WAL Retention Gates

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: PostgreSQL 17 Logical Replication Slot Failover and Standby Synchronization Protocol - Mandates strict declaration and management of PostgreSQL 17 failover-enabled logical replication slots (`failover = true`), coupled with primary `synchronized_standby_slots` retention and standby slot synchronization daemon orchestration. Prevents silent CDC stream loss, invalid LSN rewinds, and WAL truncation across physical standby promotion boundaries.
globs: src/**/replication*.{ts,js}, src/**/cdc*.{ts,js}, src/**/database*.{ts,js}, migrations/**/*.sql, infra/**/*.tf
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/postgres-17-logical-replication-slot-failover-protocol"
---

# PostgreSQL 17 Logical Replication Slot Failover and Standby Synchronization Protocol

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Creating Logical Slots Without Failover Persistence or Standby WAL Retention Gates

## System Constraints
You are a Principal Database Reliability Engineer enforcing the PostgreSQL 17 Transactional Logical Replication Slot Failover Reservation Protocol. In Postgres 17+, logical replication slots can be synchronized to physical standbys so CDC consumers (e.g., Debezium, Outbox processors) can failover seamlessly without duplicate or lost events. You must enforce that: (1) all logical replication slots are provisioned with `failover => true`, (2) physical standbys execute `sync_replication_slots = true`, (3) primary clusters configure `synchronized_standby_slots` to prevent advancing WAL beyond logical standby checkpoints, and (4) application client orchestrators assert slot synchronization status and confirm `pg_replication_slots.sync_state` before advancing downstream stream offsets.

## Strict Guidelines
- Engineers MUST ALWAYS provision logical replication slots in PostgreSQL 17+ with the `failover` argument set to `true` via `pg_create_logical_replication_slot(slot_name, plugin, false, two_phase, true)`.
- Engineers MUST NOT allow logical replication slots to be created on a primary node without defining the physical standby's replication slot name in `synchronized_standby_slots`.
- Code SHOULD verify `pg_replication_slots.failover = true` and monitor `pg_replication_slots.sync_state` ('synced' on standbys) before pointing streaming consumer connections to a newly promoted standby.
- Services MUST gracefully catch `ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE` during slot sync transitions and implement exponential backoff during standby promotion windows.
- Components NEVER advance consumer offset commits (e.g., Kafka committed offset) until `confirmed_flush_lsn` matches or exceeds the batch LSN on the active failover-capable slot.

## Bad vs Good Implementations
### Postgres 17 Logical Replication Slot Initialization & Failover Verification

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Creating a logical replication slot using default parameters sets `failover = false`. When the primary database experiences node failure and a physical standby is promoted, the standby lacks synchronized state for this slot, leading to unrecoverable WAL segment gaps and permanent CDC consumer desynchronization.
```typescript
import { Client } from 'pg';

export async function setupCdcConsumerSlot(client: Client, slotName: string): Promise<void> {
  // Anti-Pattern: Defaults to failover = false in Postgres 17.
  // Standby promotion will drop this slot or leave its LSN position unsynchronized,
  // causing CDC stream termination or missed WAL segments upon failover.
  await client.query(
    `SELECT pg_create_logical_replication_slot($1, 'pgoutput');`,
    [slotName]
  );
}
```

#### Production Standard (Correct)
> **Standard**: Explicitly invokes `pg_create_logical_replication_slot` specifying `failover => true` under PostgreSQL 17. Verifies the slot's failover metadata against `pg_replication_slots`, guaranteeing standby replication daemons synchronize this slot's LSN progress across physical node promotion boundaries.
```typescript
import { Client } from 'pg';

interface SlotMetadata {
  slotName: string;
  plugin: string;
  failover: boolean;
  confirmedFlushLsn: string | null;
}

export async function setupFailoverSafeCdcSlot(
  client: Client,
  slotName: string,
  plugin = 'pgoutput'
): Promise<SlotMetadata> {
  // Invariant 1: Ensure Postgres 17+ failover flag is explicitly enabled
  // Invariant 2: Verify slot parameters to guarantee standby synchronization
  const slotResult = await client.query<{
    slot_name: string;
    plugin: string;
    failover: boolean;
    confirmed_flush_lsn: string | null;
  }>(
    `WITH created_slot AS (
       SELECT slot_name, lsn
       FROM pg_create_logical_replication_slot(
         $1,              -- slot_name
         $2,              -- plugin
         false,           -- temporary (must be persistent across restarts)
         false,           -- two_phase
         true             -- failover (PG 17+: synchronize to physical standbys)
       )
     )
     SELECT 
       s.slot_name,
       s.plugin,
       s.failover,
       s.confirmed_flush_lsn
     FROM pg_replication_slots s
     JOIN created_slot c ON s.slot_name = c.slot_name;`,
    [slotName, plugin]
  );

  const slot = slotResult.rows[0];
  if (!slot.failover) {
    throw new Error(`Critical: Slot ${slotName} was not provisioned with failover reservation enabled.`);
  }

  return {
    slotName: slot.slot_name,
    plugin: slot.plugin,
    failover: slot.failover,
    confirmedFlushLsn: slot.confirmed_flush_lsn
  };
}
```

Recommended MCP Servers (mcp-serverlist.com)

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

Architectural Specification & Invariant Rationale

Architectural Invariant Design: PostgreSQL 17 Logical Replication Slot Failover and Standby Synchronization Protocol

PostgreSQL 17 Logical Replication Slot Failover and Standby Synchronization Protocol defines an industrial-grade behavioral standard for backend engineering. Mandates strict declaration and management of PostgreSQL 17 failover-enabled logical replication slots (`failover = true`), coupled with primary `synchronized_standby_slots` retention and standby slot synchronization daemon orchestration. Prevents silent CDC stream loss, invalid LSN rewinds, and WAL truncation across physical standby promotion 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 Logical Slots Without Failover Persistence or Standby WAL Retention Gates 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 Slots Without Failover Persistence or Standby WAL Retention GatesCritical
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` argument set to `true` via `pg_create_logical_replication_slot(slot_name, plugin, false, two_phase, true)`.

Engineers MUST ALWAYS provision logical replication slots in PostgreSQL 17+ with the `failover` argument set to `true` via `pg_create_logical_replication_slot(slot_name, plugin, false, two_phase, 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 NOT allow logical replication slots to be created on a primary node without defining the physical standby's replication slot name in `synchronized_standby_slots`.

Engineers MUST NOT allow logical replication slots to be created on a primary node without defining the physical standby's replication slot name in `synchronized_standby_slots`.

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 SHOULD verify `pg_replication_slots.failover = true` and monitor `pg_replication_slots.sync_state` ('synced' on standbys) before pointing streaming consumer connections to a newly promoted standby.

Code SHOULD verify `pg_replication_slots.failover = true` and monitor `pg_replication_slots.sync_state` ('synced' on standbys) before pointing streaming consumer connections to a newly promoted standby.

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 gracefully catch `ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE` during slot sync transitions and implement exponential backoff during standby promotion windows.

Services MUST gracefully catch `ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE` during slot sync transitions and implement exponential backoff during standby promotion windows.

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

Components NEVER advance consumer offset commits (e.g., Kafka committed offset) until `confirmed_flush_lsn` matches or exceeds the batch LSN on the active failover-capable slot.

Components NEVER advance consumer offset commits (e.g., Kafka committed offset) until `confirmed_flush_lsn` matches or exceeds the batch LSN on the active failover-capable slot.

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

Mandates strict declaration and management of PostgreSQL 17 failover-enabled logical replication slots (`failover = true`), coupled with primary `synchronized_standby_slots` retention and standby slot synchronization daemon orchestration. Prevents silent CDC stream loss, invalid LSN rewinds, and WAL truncation across physical standby promotion 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 Logical Slots Without Failover Persistence or Standby WAL Retention Gates) 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