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

Postgres 17 Logical Replication Failover Slot Synchronization Invariant

Enforces deterministic physical-to-logical replication slot synchronization using Postgres 17 failover-enabled slots and synchronized standbys. Guarantees zero duplicate event replays or silent data loss cascades in distributed event pipelines during planned switchovers and unplanned high-availability failovers.

Prohibited Anti-Pattern: Unsynchronized Logical Replication Slots Causing Data Loss Cascades or Multi-Day WAL Replays on Standby Failover

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Postgres 17 Logical Replication Failover Slot Synchronization Invariant - Enforces deterministic physical-to-logical replication slot synchronization using Postgres 17 failover-enabled slots and synchronized standbys. Guarantees zero duplicate event replays or silent data loss cascades in distributed event pipelines during planned switchovers and unplanned high-availability failovers.
globs: src/**/*.{ts,js,py,go,rs,sql}, migrations/**/*.{sql,ts}, infra/**/*.{tf,yaml,yml,json}, docker/**/*.{yaml,yml}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/postgres-17-logical-replication-failover-slot-sync-invariant"
---

# Postgres 17 Logical Replication Failover Slot Synchronization Invariant

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unsynchronized Logical Replication Slots Causing Data Loss Cascades or Multi-Day WAL Replays on Standby Failover

## System Constraints
You are a Principal Database Architect and Infrastructure Engineer enforcing Postgres 17 Logical Replication Failover Slot Sync invariants. You must prevent downstream CDC data corruption and message storms caused by unsynchronized logical slots during physical standby promotions. Mandate explicit `failover = true` slot configuration, `synchronized_standby_slots` standby gating on the primary, and automated standby slot synchronization worker validation prior to downstream consumer reconnects.

## Strict Guidelines
- Engineers MUST ALWAYS configure Postgres 17 logical replication slots with `failover = true` via `pg_create_logical_replication_slot(slot_name, plugin, false, false, true)` for all downstream CDC consumers in high-availability clusters.
- Engineers MUST ALWAYS set `synchronized_standby_slots` on the primary instance to include physical standby slots, ensuring WAL records are not pruned or consumed before physical standbys have confirmed flush.
- Engineers MUST ALWAYS configure physical standby instances with `sync_replication_slots = true` (or deploy continuous invocation of `pg_sync_replication_slots()`) so logical slots mirror their confirmed restart_lsn continuously.
- Engineers MUST NOT allow CDC downstream consumers (Debezium, Kafka Connect, custom outbox relay workers) to reconnect to a promoted standby without first validating that `pg_replication_slots.sync_state` is 's' (synchronized) or 'n' (not synchronized, but promoted) and that `restart_lsn` is strictly non-null.
- Code SHOULD verify downstream consumer idempotency keys and LSN checkpoints against `pg_replication_slots` metadata before resuming event consumption after any connection pool or topology failover event.
- Components NEVER drop or recreate failover-enabled logical slots on a promoted standby without invalidating and resetting downstream consumer offset registries to prevent double-delivery storms.

## Bad vs Good Implementations
### Postgres 17 Slot Provisioning and Failover Verification Client

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Legacy pg_create_logical_replication_slot invocations default to failover=false. When Patroni or cloud orchestrators promote a physical standby, this slot does not exist on the new primary, forcing consumer reconnection failures, manual slot recreation, and catastrophic replay or data loss.
```typescript
import { Client } from 'pg';

export async function initConsumerSlot(client: Client, slotName: string): Promise<void> {
  // Anti-Pattern: Creating legacy logical slot without Postgres 17 failover flag
  // Physical standbys will NOT replicate this slot, causing massive data loss or
  // consumer crash with missing slot errors after an HA failover event.
  await client.query(
    `SELECT pg_create_logical_replication_slot($1, 'pgoutput');`,
    [slotName]
  );
}

export async function verifySlotAfterFailover(client: Client, slotName: string): Promise<boolean> {
  // Anti-Pattern: Simply checking if slot exists regardless of sync state or LSN lag
  const res = await client.query(
    `SELECT slot_name FROM pg_replication_slots WHERE slot_name = $1;`,
    [slotName]
  );
  return res.rows.length > 0;
}
```

#### Production Standard (Correct)
> **Standard**: The production invariant provisions the slot using Postgres 17's 5-argument function signature with failover=true. The post-failover validator ensures the slot is synchronized on the newly promoted standby before downstream consumers can bind and advance the LSN.
```typescript
import { Client } from 'pg';

interface SlotMetadata {
  slotName: string;
  plugin: string;
  confirmedFlushLsn: string;
  restartLsn: string;
  failover: boolean;
  synced: boolean;
}

export async function initFailoverLogicalSlot(client: Client, slotName: string): Promise<void> {
  // Invariant: Postgres 17 signature mandates two-phase and failover booleans
  // 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]
  );
}

export async function assertSlotReadyPostFailover(client: Client, slotName: string): Promise<SlotMetadata> {
  const query = `
    SELECT 
      slot_name AS "slotName",
      plugin,
      confirmed_flush_lsn AS "confirmedFlushLsn",
      restart_lsn AS "restartLsn",
      failover,
      synced
    FROM pg_replication_slots 
    WHERE slot_name = $1 AND active = false;
  `;
  const res = await client.query<SlotMetadata>(query, [slotName]);
  
  if (res.rows.length === 0) {
    throw new Error(`CRITICAL: Logical slot '${slotName}' missing on promoted primary! Failover sync failed.`);
  }
  
  const slot = res.rows[0];
  if (!slot.failover) {
    throw new Error(`CRITICAL: Logical slot '${slotName}' was not configured with failover=true.`);
  }
  if (!slot.restartLsn || !slot.confirmedFlushLsn) {
    throw new Error(`CRITICAL: Logical slot '${slotName}' has invalid LSN coordinates on promoted standby.`);
  }
  
  return slot;
}
```

Architectural Specification & Invariant Rationale

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

Postgres 17 Logical Replication Failover Slot Synchronization Invariant defines an industrial-grade behavioral standard for backend engineering. Enforces deterministic physical-to-logical replication slot synchronization using Postgres 17 failover-enabled slots and synchronized standbys. Guarantees zero duplicate event replays or silent data loss cascades in distributed event pipelines during planned switchovers and unplanned high-availability 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 Logical Replication Slots Causing Data Loss Cascades or Multi-Day WAL Replays on Standby Failover 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 Replication Slots Causing Data Loss Cascades or Multi-Day WAL Replays on Standby FailoverCritical
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 Postgres 17 logical replication slots with `failover = true` via `pg_create_logical_replication_slot(slot_name, plugin, false, false, true)` for all downstream CDC consumers in high-availability clusters.

Engineers MUST ALWAYS configure Postgres 17 logical replication slots with `failover = true` via `pg_create_logical_replication_slot(slot_name, plugin, false, false, true)` for all downstream CDC consumers in high-availability clusters.

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 ALWAYS set `synchronized_standby_slots` on the primary instance to include physical standby slots, ensuring WAL records are not pruned or consumed before physical standbys have confirmed flush.

Engineers MUST ALWAYS set `synchronized_standby_slots` on the primary instance to include physical standby slots, ensuring WAL records are not pruned or consumed before physical standbys have confirmed flush.

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 ALWAYS configure physical standby instances with `sync_replication_slots = true` (or deploy continuous invocation of `pg_sync_replication_slots()`) so logical slots mirror their confirmed restart_lsn continuously.

Engineers MUST ALWAYS configure physical standby instances with `sync_replication_slots = true` (or deploy continuous invocation of `pg_sync_replication_slots()`) so logical slots mirror their confirmed restart_lsn continuously.

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 NOT allow CDC downstream consumers (Debezium, Kafka Connect, custom outbox relay workers) to reconnect to a promoted standby without first validating that `pg_replication_slots.sync_state` is 's' (synchronized) or 'n' (not synchronized, but promoted) and that `restart_lsn` is strictly non-null.

Engineers MUST NOT allow CDC downstream consumers (Debezium, Kafka Connect, custom outbox relay workers) to reconnect to a promoted standby without first validating that `pg_replication_slots.sync_state` is 's' (synchronized) or 'n' (not synchronized, but promoted) and that `restart_lsn` is strictly non-null.

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

Code SHOULD verify downstream consumer idempotency keys and LSN checkpoints against `pg_replication_slots` metadata before resuming event consumption after any connection pool or topology failover event.

Code SHOULD verify downstream consumer idempotency keys and LSN checkpoints against `pg_replication_slots` metadata before resuming event consumption after any connection pool or topology failover event.

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 drop or recreate failover-enabled logical slots on a promoted standby without invalidating and resetting downstream consumer offset registries to prevent double-delivery storms.

Components NEVER drop or recreate failover-enabled logical slots on a promoted standby without invalidating and resetting downstream consumer offset registries to prevent double-delivery storms.

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

Enforces deterministic physical-to-logical replication slot synchronization using Postgres 17 failover-enabled slots and synchronized standbys. Guarantees zero duplicate event replays or silent data loss cascades in distributed event pipelines during planned switchovers and unplanned high-availability 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 Logical Replication Slots Causing Data Loss Cascades or Multi-Day WAL Replays on Standby Failover) 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