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

Postgres 17 Logical Replication Failover Slot Synchronization Guardrail

Enforces Postgres 17 native logical replication failover slot synchronization across physical standbys. Prevents downstream CDC data duplication and message loss during standby promotion by requiring the FAILOVER clause and strict validation of synchronized_standby_slots alignment before WAL consumption.

Prohibited Anti-Pattern: Unsynchronized Logical Slots Advancing Beyond Physical Standby Confirmed LSN

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Postgres 17 Logical Replication Failover Slot Synchronization Guardrail - Enforces Postgres 17 native logical replication failover slot synchronization across physical standbys. Prevents downstream CDC data duplication and message loss during standby promotion by requiring the FAILOVER clause and strict validation of synchronized_standby_slots alignment before WAL consumption.
globs: src/database/**/*.ts, src/services/cdc/**/*.ts, infra/postgres/**/*.sql, migrations/**/*.sql
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/postgres-17-logical-failover-slot-sync"
---

# Postgres 17 Logical Replication Failover Slot Synchronization Guardrail

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unsynchronized Logical Slots Advancing Beyond Physical Standby Confirmed LSN

## System Constraints
You are a Principal Database Infrastructure Engineer enforcing strict Postgres 17 logical replication failover slot configurations. Postgres 17 introduces native failover-ready logical slots (`FAILOVER (true)`) and `synchronized_standby_slots`. You must ensure that any logical replication slot creation, CDC provisioning script, or connection orchestration enforces failover safety, verifies standby LSN sync prior to offset commits, and disallows unconfirmed WAL processing.

## Strict Guidelines
- Engineers MUST ALWAYS provision logical slots with `FAILOVER true` in Postgres 17+ (`pg_create_logical_replication_slot(slot_name, plugin, false, false, true)` or SQL equivalent).
- Engineers MUST verify that `synchronized_standby_slots` is non-empty on the primary instance before starting logical decoding workers.
- Engineers MUST configure physical standbys with `sync_replication_slots = true` to allow standby slots to sync state from primary.
- Engineers MUST NOT acknowledge or commit CDC event offsets downstream (e.g., Kafka) until the logical slot's `confirmed_flush_lsn` is strictly behind or equal to the physical standbys' minimum `flushed_lsn`.
- Database migration scripts MUST fail closed if a Postgres 17 cluster is detected without matching `synchronized_standby_slots` for high-availability setups.

## Bad vs Good Implementations
### Postgres 17 Logical Replication Slot Provisioning and Health Check

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Creating a logical replication slot without Postgres 17 failover support leaves the slot unmaintained on physical standbys. Upon high-availability failover, the promoted standby lacks the slot state or restarts from an earlier LSN, leading to massive message duplication or silent WAL data loss.
```typescript
import { Client } from 'pg';

export async function setupLogicalSlot(client: Client, slotName: string): Promise<void> {
  // Anti-pattern: Pre-Postgres 17 syntax without failover flag
  // Logical slot advances independently of physical standby flush state
  await client.query(
    `SELECT pg_create_logical_replication_slot($1, 'pgoutput');`,
    [slotName]
  );
}
```

#### Production Standard (Correct)
> **Standard**: Validates that the Postgres 17 primary server has physical standby slots designated in `synchronized_standby_slots` and creates the slot with `failover: true`. This ensures logical slots synchronize to standby instances and prevent CDC stream corruption across primary failovers.
```typescript
import { Client } from 'pg';

interface SlotConfig {
  slotName: string;
  plugin?: string;
}

export async function setupLogicalSlot(client: Client, config: SlotConfig): Promise<void> {
  const plugin = config.plugin ?? 'pgoutput';

  // Invariant 1: Ensure primary has configured synchronized_standby_slots
  const syncSlotsResult = await client.query<{ setting: string }>(
    `SELECT setting FROM pg_settings WHERE name = 'synchronized_standby_slots';`
  );
  const synchronizedSlots = syncSlotsResult.rows[0]?.setting?.trim();

  if (!synchronizedSlots || synchronizedSlots === '') {
    throw new Error(
      'FATAL: synchronized_standby_slots is unconfigured. Standby failover slot sync cannot be guaranteed.'
    );
  }

  // Invariant 2: Create logical slot with failover = true (Postgres 17+)
  // Signature: pg_create_logical_replication_slot(slot_name, plugin, temporary, two_phase, failover)
  await client.query(
    `SELECT pg_create_logical_replication_slot(
      $1,
      $2,
      false,
      false,
      true
    );`,
    [config.slotName, plugin]
  );
}
```

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 Logical Replication Failover Slot Synchronization Guardrail

Postgres 17 Logical Replication Failover Slot Synchronization Guardrail defines an industrial-grade behavioral standard for backend engineering. Enforces Postgres 17 native logical replication failover slot synchronization across physical standbys. Prevents downstream CDC data duplication and message loss during standby promotion by requiring the FAILOVER clause and strict validation of synchronized_standby_slots alignment before WAL consumption. 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 Advancing Beyond Physical Standby Confirmed LSN 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 Advancing Beyond Physical Standby Confirmed LSNCritical
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 slots with `FAILOVER true` in Postgres 17+ (`pg_create_logical_replication_slot(slot_name, plugin, false, false, true)` or SQL equivalent).

Engineers MUST ALWAYS provision logical slots with `FAILOVER true` in Postgres 17+ (`pg_create_logical_replication_slot(slot_name, plugin, false, false, true)` or SQL equivalent).

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 verify that `synchronized_standby_slots` is non-empty on the primary instance before starting logical decoding workers.

Engineers MUST verify that `synchronized_standby_slots` is non-empty on the primary instance before starting logical decoding workers.

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 configure physical standbys with `sync_replication_slots = true` to allow standby slots to sync state from primary.

Engineers MUST configure physical standbys with `sync_replication_slots = true` to allow standby slots to sync state from primary.

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 acknowledge or commit CDC event offsets downstream (e.g., Kafka) until the logical slot's `confirmed_flush_lsn` is strictly behind or equal to the physical standbys' minimum `flushed_lsn`.

Engineers MUST NOT acknowledge or commit CDC event offsets downstream (e.g., Kafka) until the logical slot's `confirmed_flush_lsn` is strictly behind or equal to the physical standbys' minimum `flushed_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.
5

Database migration scripts MUST fail closed if a Postgres 17 cluster is detected without matching `synchronized_standby_slots` for high-availability setups.

Database migration scripts MUST fail closed if a Postgres 17 cluster is detected without matching `synchronized_standby_slots` for high-availability setups.

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 Guardrail critical for AI coding assistants?

Enforces Postgres 17 native logical replication failover slot synchronization across physical standbys. Prevents downstream CDC data duplication and message loss during standby promotion by requiring the FAILOVER clause and strict validation of synchronized_standby_slots alignment before WAL consumption. 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 Advancing Beyond Physical Standby Confirmed LSN) 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