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

Postgres 17 Failover-Safe Logical Replication Slot Synchronization

Mandates strict programmatic configuration and operational validation of PostgreSQL 17 failover-safe logical replication slots for downstream CDC and transactional outbox engines. Ensures logical slots specify failover enabled, primary instances enforce synchronized_standby_slots, and standby nodes sync slots to eliminate cursor corruption, dropped events, and duplicate stream bursts during replica failovers.

Prohibited Anti-Pattern: Unsynchronized Ephemeral Logical Slots Lost or Rewound Following Primary-Replica Failovers

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Postgres 17 Failover-Safe Logical Replication Slot Synchronization - Mandates strict programmatic configuration and operational validation of PostgreSQL 17 failover-safe logical replication slots for downstream CDC and transactional outbox engines. Ensures logical slots specify failover enabled, primary instances enforce synchronized_standby_slots, and standby nodes sync slots to eliminate cursor corruption, dropped events, and duplicate stream bursts during replica failovers.
globs: src/**/*.ts, src/**/*.pg.ts, migrations/**/*.sql, infra/**/*.tf
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/postgres-17-failover-safe-logical-replication-sync"
---

# Postgres 17 Failover-Safe Logical Replication Slot Synchronization

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unsynchronized Ephemeral Logical Slots Lost or Rewound Following Primary-Replica Failovers

## System Constraints
You are a Principal Software Architect enforcing PostgreSQL 17 failover-safe logical replication invariants. In Postgres 17, logical replication slots can be synchronized to physical streaming standbys to allow zero-downtime, lossless failover for CDC and outbox pipelines. You must mandate that every logical replication slot creation explicitly specifies failover => true, verify database version prerequisites (>= 170000), require primary configuration of synchronized_standby_slots, and reject any replication orchestration code that omits cursor re-anchoring on promoted standbys.

## Strict Guidelines
- Engineers MUST ALWAYS create logical replication slots with 'failover => true' in PostgreSQL 17+ environments.
- Engineers MUST NOT rely on default parameter values for pg_create_logical_replication_slot, as the failover flag defaults to false.
- Code MUST verify primary engine compatibility (server_version_num >= 170000) prior to requesting failover slot behavior.
- Services connecting to replication slots MUST query pg_replication_slots to verify 'failover = true' and 'synced = false' on the active primary before consuming logical streams.
- Infrastructure configs MUST define 'synchronized_standby_slots' on the primary containing the physical replication slot names of all eligible failover targets.
- Components NEVER advance LSN commitments downstream until confirming persistent delivery to storage to uphold at-least-once semantics across failovers.

## Bad vs Good Implementations
### Postgres 17 Logical Replication Slot Initialization for CDC Consumer

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Omits the PG17 'failover' boolean parameter in pg_create_logical_replication_slot. The slot will not be synced to physical standbys via sync_replication_slots or synchronized_standby_slots, causing immediate CDC pipeline failure and missing LSN positions upon replica promotion.
```typescript
import { Client } from 'pg';

export async function setupOutboxReplicationSlot(client: Client, slotName: string): Promise<void> {
  // Flaw: Invokes default legacy slot creation without PG17 failover flag.
  // During a primary failover to a physical standby, this slot does not exist
  // on the promoted node, causing the CDC pipeline to crash or duplicate messages.
  const res = await client.query(
    `SELECT slot_name, consistent_point 
     FROM pg_create_logical_replication_slot($1, 'pgoutput')`,
    [slotName]
  );
  console.log(`Replication slot created: ${res.rows[0].slot_name}`);
}
```

#### Production Standard (Correct)
> **Standard**: Validates engine compatibility (PostgreSQL 17+), verifies existing slot failover integrity, and explicitly sets 'failover => true' using named parameters in pg_create_logical_replication_slot, ensuring continuous streaming standby synchronization.
```typescript
import { Client } from 'pg';

interface ReplicationSlotMetadata {
  slot_name: string;
  consistent_point: string;
  failover: boolean;
}

export async function setupOutboxReplicationSlot(
  client: Client,
  slotName: string
): Promise<ReplicationSlotMetadata> {
  // 1. Validate Postgres 17+ support
  const verRes = await client.query<{ server_version_num: string }>(
    'SHOW server_version_num;'
  );
  const versionNum = parseInt(verRes.rows[0]?.server_version_num ?? '0', 10);
  if (versionNum < 170000) {
    throw new Error(`Postgres 170000+ required for failover slots. Detected: ${versionNum}`);
  }

  // 2. Idempotently check if slot exists with failover capability
  const existing = await client.query<ReplicationSlotMetadata>(
    `SELECT slot_name, confirmed_flush_lsn AS consistent_point, failover
     FROM pg_replication_slots 
     WHERE slot_name = $1`,
    [slotName]
  );

  if (existing.rows.length > 0) {
    const slot = existing.rows[0];
    if (!slot.failover) {
      throw new Error(`Replication slot '${slotName}' exists but failover is disabled.`);
    }
    return slot;
  }

  // 3. Create logical replication slot with explicit failover => true (5th argument in PG17)
  const createRes = await client.query<ReplicationSlotMetadata>(
    `SELECT slot_name, consistent_point, true AS failover
     FROM pg_create_logical_replication_slot(
       slot_name => $1,
       plugin => 'pgoutput',
       temporary => false,
       two_phase => false,
       failover => true
     );`,
    [slotName]
  );

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

Architectural Specification & Invariant Rationale

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

Postgres 17 Failover-Safe Logical Replication Slot Synchronization defines an industrial-grade behavioral standard for backend engineering. Mandates strict programmatic configuration and operational validation of PostgreSQL 17 failover-safe logical replication slots for downstream CDC and transactional outbox engines. Ensures logical slots specify failover enabled, primary instances enforce synchronized_standby_slots, and standby nodes sync slots to eliminate cursor corruption, dropped events, and duplicate stream bursts during replica 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: Unsynchronized Ephemeral Logical Slots Lost or Rewound Following Primary-Replica Failovers 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 DriftUnsynchronized Ephemeral Logical Slots Lost or Rewound Following Primary-Replica FailoversCritical
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' in PostgreSQL 17+ environments.

Engineers MUST ALWAYS create logical replication slots with 'failover => true' in PostgreSQL 17+ environments.

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 rely on default parameter values for pg_create_logical_replication_slot, as the failover flag defaults to false.

Engineers MUST NOT rely on default parameter values for pg_create_logical_replication_slot, as the failover flag defaults to false.

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 primary engine compatibility (server_version_num >= 170000) prior to requesting failover slot behavior.

Code MUST verify primary engine compatibility (server_version_num >= 170000) prior to requesting failover slot behavior.

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 connecting to replication slots MUST query pg_replication_slots to verify 'failover = true' and 'synced = false' on the active primary before consuming logical streams.

Services connecting to replication slots MUST query pg_replication_slots to verify 'failover = true' and 'synced = false' on the active primary before consuming logical streams.

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

Infrastructure configs MUST define 'synchronized_standby_slots' on the primary containing the physical replication slot names of all eligible failover targets.

Infrastructure configs MUST define 'synchronized_standby_slots' on the primary containing the physical replication slot names of all eligible failover targets.

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

Components NEVER advance LSN commitments downstream until confirming persistent delivery to storage to uphold at-least-once semantics across failovers.

Components NEVER advance LSN commitments downstream until confirming persistent delivery to storage to uphold at-least-once semantics across failovers.

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

Mandates strict programmatic configuration and operational validation of PostgreSQL 17 failover-safe logical replication slots for downstream CDC and transactional outbox engines. Ensures logical slots specify failover enabled, primary instances enforce synchronized_standby_slots, and standby nodes sync slots to eliminate cursor corruption, dropped events, and duplicate stream bursts during replica 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 (Unsynchronized Ephemeral Logical Slots Lost or Rewound Following Primary-Replica Failovers) 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