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

Postgres 17 Failover Slot Synchronization & LSN Lag Boundary Enforcement

Enforces failover-enabled logical slots (failover = true) and strict LSN lag boundaries across primary and physical standbys in PostgreSQL 17+. Prevents silent message drops, CDC consumer replay corruption, and phantom data loss during failovers by requiring synchronous replication slot validation (sync_replication_slots) and verified confirmed_flush_lsn assertions before traffic migration.

Prohibited Anti-Pattern: Unsynchronized Logical Replication Slots During Physical Failover Causing Silent Consumer Divergence

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Postgres 17 Failover Slot Synchronization & LSN Lag Boundary Enforcement - Enforces failover-enabled logical slots (failover = true) and strict LSN lag boundaries across primary and physical standbys in PostgreSQL 17+. Prevents silent message drops, CDC consumer replay corruption, and phantom data loss during failovers by requiring synchronous replication slot validation (sync_replication_slots) and verified confirmed_flush_lsn assertions before traffic migration.
globs: src/**/*.ts, src/**/*.sql, migrations/**/*.sql, infra/**/*.tf
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/postgres-17-failover-slot-synchronization-lsn-lag-boundary"
---

# Postgres 17 Failover Slot Synchronization & LSN Lag Boundary Enforcement

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unsynchronized Logical Replication Slots During Physical Failover Causing Silent Consumer Divergence

## System Constraints
You are a Principal Backend Database Architect enforcing PostgreSQL 17 logical replication durability and zero-loss failover standards. You mandate that all logical replication slots configured for CDC or downstream consumers specify `failover = true`, that standby clusters configure `sync_replication_slots = true`, and that client orchestrators validate `confirmed_flush_lsn` against physical standby replay LSN before routing consumer traffic during cluster failovers.

## Strict Guidelines
- Engineers MUST ALWAYS create logical replication slots with `failover => true` in PostgreSQL 17+ to enable metadata and LSN synchronization to physical standbys.
- Engineers MUST NOT promote a physical standby until `pg_replication_slots.synced` is verified `true` and the standby's replay LSN meets or exceeds the logical slot's `confirmed_flush_lsn`.
- Code SHOULD query `pg_replication_slots` and `pg_stat_replication_slots` to enforce lag thresholds (LSN delta < max_allowed_bytes) before acknowledging consumer health checks.
- Services MUST configure PostgreSQL 17 primary instances with `synchronized_standby_slots` referencing designated physical standby application names to prevent the primary from discarding WAL needed by synchronized slots.
- Components NEVER resume CDC ingestion on a newly promoted replica without asserting that the slot's `confirmed_flush_lsn` is greater than or equal to the consumer's persisted checkpoint offset.

## Bad vs Good Implementations
### PostgreSQL 17 CDC Slot Initialization and Failover Validation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Creating a logical replication slot without explicitly setting failover to true ignores Postgres 17 slot synchronization. In the event of a physical standby promotion, the logical slot will be absent on the standby, leading to pipeline halts, uncoordinated recreation, or silent event drop.
```typescript
import { Client } from 'pg';

export async function initCdcSlot(client: Client, slotName: string): Promise<void> {
  // FAILS: Creates legacy slot without failover parameter (Postgres 17 default is failover = false)
  // If the primary fails over, this slot does not exist on the promoted physical standby,
  // causing CDC stream termination or recreation with silent data loss.
  await client.query(
    `SELECT pg_create_logical_replication_slot($1, 'pgoutput');`,
    [slotName]
  );
}
```

#### Production Standard (Correct)
> **Standard**: Uses PostgreSQL 17's named parameter `failover => true` when invoking `pg_create_logical_replication_slot`, and performs an assertion on `pg_replication_slots` ensuring failover synchronization capabilities are active before consuming events.
```typescript
import { Client } from 'pg';

interface ReplicationSlotStatus {
  slot_name: string;
  plugin: string;
  failover: boolean;
  synced: boolean;
  confirmed_flush_lsn: string;
}

export async function initCdcSlot(client: Client, slotName: string): Promise<ReplicationSlotStatus> {
  // In Postgres 17+, specify failover => true to synchronize slot to physical standbys
  await client.query(`
    DO $$
    BEGIN
      IF NOT EXISTS (
        SELECT 1 FROM pg_replication_slots WHERE slot_name = $1
      ) THEN
        PERFORM pg_create_logical_replication_slot(
          slot_name => $1,
          plugin => 'pgoutput',
          temporary => false,
          twophase => false,
          failover => true
        );
      END IF;
    END
    $$;
  `, [slotName]);

  // Verify slot integrity and sync status
  const { rows } = await client.query<ReplicationSlotStatus>(`
    SELECT slot_name, plugin, failover, synced, confirmed_flush_lsn::text
    FROM pg_replication_slots
    WHERE slot_name = $1;
  `, [slotName]);

  const slot = rows[0];
  if (!slot || !slot.failover) {
    throw new Error(`Logical slot ${slotName} must be configured with failover = true`);
  }

  return slot;
}
```

Recommended MCP Servers (mcp-serverlist.com)

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

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Postgres 17 Failover Slot Synchronization & LSN Lag Boundary Enforcement

Postgres 17 Failover Slot Synchronization & LSN Lag Boundary Enforcement defines an industrial-grade behavioral standard for backend engineering. Enforces failover-enabled logical slots (failover = true) and strict LSN lag boundaries across primary and physical standbys in PostgreSQL 17+. Prevents silent message drops, CDC consumer replay corruption, and phantom data loss during failovers by requiring synchronous replication slot validation (sync_replication_slots) and verified confirmed_flush_lsn assertions before traffic migration. 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 During Physical Failover Causing Silent Consumer Divergence 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 During Physical Failover Causing Silent Consumer DivergenceCritical
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+ to enable metadata and LSN synchronization to physical standbys.

Engineers MUST ALWAYS create logical replication slots with `failover => true` in PostgreSQL 17+ to enable metadata and LSN synchronization to physical standbys.

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 promote a physical standby until `pg_replication_slots.synced` is verified `true` and the standby's replay LSN meets or exceeds the logical slot's `confirmed_flush_lsn`.

Engineers MUST NOT promote a physical standby until `pg_replication_slots.synced` is verified `true` and the standby's replay LSN meets or exceeds the logical slot's `confirmed_flush_lsn`.

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 query `pg_replication_slots` and `pg_stat_replication_slots` to enforce lag thresholds (LSN delta < max_allowed_bytes) before acknowledging consumer health checks.

Code SHOULD query `pg_replication_slots` and `pg_stat_replication_slots` to enforce lag thresholds (LSN delta < max_allowed_bytes) before acknowledging consumer health checks.

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 configure PostgreSQL 17 primary instances with `synchronized_standby_slots` referencing designated physical standby application names to prevent the primary from discarding WAL needed by synchronized slots.

Services MUST configure PostgreSQL 17 primary instances with `synchronized_standby_slots` referencing designated physical standby application names to prevent the primary from discarding WAL needed by synchronized 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.
5

Components NEVER resume CDC ingestion on a newly promoted replica without asserting that the slot's `confirmed_flush_lsn` is greater than or equal to the consumer's persisted checkpoint offset.

Components NEVER resume CDC ingestion on a newly promoted replica without asserting that the slot's `confirmed_flush_lsn` is greater than or equal to the consumer's persisted checkpoint offset.

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 Synchronization & LSN Lag Boundary Enforcement critical for AI coding assistants?

Enforces failover-enabled logical slots (failover = true) and strict LSN lag boundaries across primary and physical standbys in PostgreSQL 17+. Prevents silent message drops, CDC consumer replay corruption, and phantom data loss during failovers by requiring synchronous replication slot validation (sync_replication_slots) and verified confirmed_flush_lsn assertions before traffic migration. 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 During Physical Failover Causing Silent Consumer Divergence) 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