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-postgresql-17-lo-496

PostgreSQL 17 Logical Replication Failover Slot Synchronization Standard

Enforces strict failover slot synchronization and standby confirmation protocol introduced in PostgreSQL 17 for zero-data-loss CDC architectures. Mandates synchronized slots on physical standbys and synchronized subscription failovers to prevent duplicate downstream ingestion and uncoordinated LSN rewind during primary node failover events.

Prohibited Anti-Pattern: Unsynchronized Logical Slots and Uncoordinated Standby Promotion Causing CDC Replay and Downstream Poisoning

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: PostgreSQL 17 Logical Replication Failover Slot Synchronization Standard - Enforces strict failover slot synchronization and standby confirmation protocol introduced in PostgreSQL 17 for zero-data-loss CDC architectures. Mandates synchronized slots on physical standbys and synchronized subscription failovers to prevent duplicate downstream ingestion and uncoordinated LSN rewind during primary node failover events.
globs: src/infra/**/*.ts, src/database/**/*.ts, src/cdc/**/*.ts, src/config/postgres/**/*.ts, migrations/**/*.sql
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/pg17-logical-replication-failover-slot-sync-postgresql-17-lo-496"
---

# PostgreSQL 17 Logical Replication Failover Slot Synchronization Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unsynchronized Logical Slots and Uncoordinated Standby Promotion Causing CDC Replay and Downstream Poisoning

## System Constraints
You are a Principal Database Infrastructure Architect enforcing PostgreSQL 17 logical replication failover slot synchronization. You must enforce the usage of `FAILOVER (true)` on logical replication slots, configure `synchronized_standby_slots` on the primary instance, and ensure downstream subscribers coordinate failover with `ALTER SUBSCRIPTION ... SET (failover = true)` to avoid duplicate CDC stream replays or data loss upon standby promotion.

## Strict Guidelines
- Engineers MUST ALWAYS configure `FAILOVER (true)` when creating logical replication slots intended to survive physical replica failover in PostgreSQL 17+.
- Engineers MUST configure `synchronized_standby_slots` on the primary instance referencing the physical replica application name to ensure WAL retention prevents slot invalidation.
- Engineers MUST set `sync_replication_slots = true` on physical standby instances to enable background slot synchronization via the slot synchronization worker.
- Engineers MUST configure subscriber connections to target promoted standbys using `failover = true` in PostgreSQL 17 subscription definitions.
- Engineers MUST NOT rely on external bespoke cron scripts or manual pg_replication_slot copies to sync LSN positions across physical replicas in PostgreSQL 17 environments.
- Code SHOULD verify `pg_replication_slots.failover` and `pg_replication_slots.synced` flags through health probes before initiating managed primary database switchovers.

## Bad vs Good Implementations
### Configuring Postgres 17 Logical Replication Slot and Subscriber with Failover Coordination

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Creating a logical replication slot without `failover = true` causes the slot to vanish or desynchronize when a physical standby is promoted. Downstream subscribers cannot safely repoint without re-streaming from unknown LSN boundaries, triggering mass duplicate delivery.
```typescript
import { Client } from 'pg';

export async function setupLegacyCdcSlot(client: Client, slotName: string, subName: string, connString: string) {
  // Anti-pattern: standard PG16-style slot without failover synchronization parameters
  await client.query(`SELECT pg_create_logical_replication_slot($1, 'pgoutput');`, [slotName]);
  
  // Subscriber created without failover enablement; will fail to resume cleanly upon standby promotion
  await client.query(`
    CREATE SUBSCRIPTION ${subName}
    CONNECTION '${connString}'
    PUBLICATION cdc_events_pub
    WITH (copy_data = false, create_slot = false, slot_name = '${slotName}');
  `);
}
```

#### Production Standard (Correct)
> **Standard**: Configures both the replication slot and the subscription with `failover = true`. In PG17, this ensures physical standbys sync the slot's restart_lsn and confirmed_flush_lsn via the built-in slot sync worker, guaranteeing idempotent continuation post-failover.
```typescript
import { Client } from 'pg';

export async function setupPg17FailoverCdcSlot(
  primaryClient: Client,
  slotName: string,
  subName: string,
  primaryConnString: string
): Promise<void> {
  // Invariant: PG17 logical slot created with failover: true
  await primaryClient.query(
    `SELECT pg_create_logical_replication_slot(
      slot_name => $1,
      plugin => 'pgoutput',
      temporary => false,
      twophase => false,
      failover => true
    );`,
    [slotName]
  );

  // Invariant: Subscription explicitly configured with failover = true
  await primaryClient.query(`
    CREATE SUBSCRIPTION ${subName}
    CONNECTION '${primaryConnString}'
    PUBLICATION cdc_events_pub
    WITH (
      copy_data = false,
      create_slot = false,
      slot_name = '${slotName}',
      failover = true
    );
  `);
}
```

### Verifying Synchronized Slot Health Prior to Physical Replica Switchover

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Promoting a standby based solely on physical replay status can lead to silent CDC data divergence or slot drops if the standby has not yet synchronized logical slot positions from the primary.
```typescript
import { Client } from 'pg';

export async function assertStandbyHealthy(standbyClient: Client): Promise<boolean> {
  // Anti-pattern: only checking physical replication delay without validating logical slot synchronization state
  const res = await standbyClient.query('SELECT pg_is_in_recovery() as in_recovery;');
  return res.rows[0].in_recovery === true;
}
```

#### Production Standard (Correct)
> **Standard**: Validates that all designated failover slots are mirrored and flagged with `synced = true` on the standby replica before any failover or planned promotion sequence is allowed to proceed.
```typescript
import { Client } from 'pg';

interface SlotSyncStatus {
  slotName: string;
  synced: boolean;
  confirmedFlushLsn: string;
}

export async function assertStandbySlotsSynchronized(
  standbyClient: Client,
  expectedSlotNames: string[]
): Promise<void> {
  const res = await standbyClient.query<SlotSyncStatus>(`
    SELECT slot_name AS "slotName", synced, confirmed_flush_lsn AS "confirmedFlushLsn"
    FROM pg_replication_slots
    WHERE slot_name = ANY($1::text[])
      AND failover = true;
  `, [expectedSlotNames]);

  if (res.rows.length !== expectedSlotNames.length) {
    throw new Error('Not all failover slots are mirrored on the standby replica.');
  }

  const unsyncedSlots = res.rows.filter(row => !row.synced);
  if (unsyncedSlots.length > 0) {
    throw new Error(`Standby failover slots not fully synced: ${unsyncedSlots.map(s => s.slotName).join(', ')}`);
  }
}
```

Architectural Specification & Invariant Rationale

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

PostgreSQL 17 Logical Replication Failover Slot Synchronization Standard defines an industrial-grade behavioral standard for backend engineering. Enforces strict failover slot synchronization and standby confirmation protocol introduced in PostgreSQL 17 for zero-data-loss CDC architectures. Mandates synchronized slots on physical standbys and synchronized subscription failovers to prevent duplicate downstream ingestion and uncoordinated LSN rewind during primary node failover events. 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 Logical Slots and Uncoordinated Standby Promotion Causing CDC Replay and Downstream Poisoning 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 Logical Slots and Uncoordinated Standby Promotion Causing CDC Replay and Downstream PoisoningCritical
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 configure `FAILOVER (true)` when creating logical replication slots intended to survive physical replica failover in PostgreSQL 17+.

Engineers MUST ALWAYS configure `FAILOVER (true)` when creating logical replication slots intended to survive physical replica failover 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 instance referencing the physical replica application name to ensure WAL retention prevents slot invalidation.

Engineers MUST configure `synchronized_standby_slots` on the primary instance referencing the physical replica application name to ensure WAL retention prevents slot invalidation.

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

Engineers MUST set `sync_replication_slots = true` on physical standby instances to enable background slot synchronization via the slot synchronization worker.

Engineers MUST set `sync_replication_slots = true` on physical standby instances to enable background slot synchronization via the slot synchronization 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

Engineers MUST configure subscriber connections to target promoted standbys using `failover = true` in PostgreSQL 17 subscription definitions.

Engineers MUST configure subscriber connections to target promoted standbys using `failover = true` in PostgreSQL 17 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.
5

Engineers MUST NOT rely on external bespoke cron scripts or manual pg_replication_slot copies to sync LSN positions across physical replicas in PostgreSQL 17 environments.

Engineers MUST NOT rely on external bespoke cron scripts or manual pg_replication_slot copies to sync LSN positions across physical replicas 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.
6

Code SHOULD verify `pg_replication_slots.failover` and `pg_replication_slots.synced` flags through health probes before initiating managed primary database switchovers.

Code SHOULD verify `pg_replication_slots.failover` and `pg_replication_slots.synced` flags through health probes before initiating managed primary database switchovers.

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

Enforces strict failover slot synchronization and standby confirmation protocol introduced in PostgreSQL 17 for zero-data-loss CDC architectures. Mandates synchronized slots on physical standbys and synchronized subscription failovers to prevent duplicate downstream ingestion and uncoordinated LSN rewind during primary node failover events. 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 Logical Slots and Uncoordinated Standby Promotion Causing CDC Replay and Downstream Poisoning) 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