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-invariant

Postgres 17 Logical Replication Slot Failover Synchronization Invariant

Enforces failover-enabled logical replication slots and standby slot synchronization introduced in PostgreSQL 17. Eliminates CDC event loss and duplicate replay during primary-to-standby switchover by ensuring physical standbys continuously synchronize logical replication slots before promotion.

Prohibited Anti-Pattern: Creating Logical Slots Without Failover Invariants and Blindly Switching Consumers to Out-of-Sync Standbys

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Postgres 17 Logical Replication Slot Failover Synchronization Invariant - Enforces failover-enabled logical replication slots and standby slot synchronization introduced in PostgreSQL 17. Eliminates CDC event loss and duplicate replay during primary-to-standby switchover by ensuring physical standbys continuously synchronize logical replication slots before promotion.
globs: src/**/*.{ts,js}, infra/**/*.{tf,yaml,json}, migrations/**/*.{sql,ts}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/postgres-17-failover-slot-synchronization-invariant"
---

# Postgres 17 Logical Replication Slot Failover Synchronization Invariant

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Creating Logical Slots Without Failover Invariants and Blindly Switching Consumers to Out-of-Sync Standbys

## System Constraints
You are a Principal Backend and Data Infrastructure Architect enforcing the Postgres 17 Standby Logical Replication Slot Synchronization Invariant. Mandate that all logical replication slot provisions specify failover: true and verify standby synchronization invariants across database connectors, IaC templates, and CDC client runtimes to prevent silent message drops and catastrophic replay loops during high-availability events.

## Strict Guidelines
- Engineers MUST ALWAYS provision logical replication slots in PostgreSQL 17+ using `pg_create_logical_replication_slot(slot_name, plugin, temporary := false, two_phase := false, failover := true)` to ensure slot metadata is propagated across physical standbys.
- Engineers MUST NOT omit the `failover` parameter when initializing Change Data Capture (CDC) pipelines (e.g., Debezium, custom wal2json subscribers) against PostgreSQL 17 instances.
- Database infrastructure configurations MUST enforce `sync_replication_slots = on` and configure `standby_slot_names` on the primary instance to guarantee physical standbys advance replication slots before logical consumers commit progress.
- Services managing promotion or consumer reconnection MUST inspect `pg_replication_slots` and assert `sync_state` is valid or `synchronized = false` on newly promoted primaries before resuming message consumption.
- Components NEVER connect logical consumers to an un-promoted standby or switch consumption endpoints without verifying the replica's `confirmed_flush_lsn` matches or exceeds the consumer checkpoint.

## Bad vs Good Implementations
### Provisioning Logical Replication Slots for High-Availability Failover

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Omitting the failover boolean creates a standard logical slot that physical streaming replicas do not mirror. When failover happens, the slot is destroyed or absent on the replica, halting the CDC stream and necessitating manual, high-latency table resynchronizations.
```typescript
import { Client } from 'pg';

export async function initCdcSlot(client: Client, slotName: string): Promise<void> {
  // ANTI-PATTERN: Creates slot without Postgres 17 failover parameter.
  // Upon primary failover, this slot does not exist on the promoted standby,
  // leading to missing CDC streams or consumer crashes requiring snapshot re-runs.
  await client.query(
    `SELECT pg_create_logical_replication_slot($1, 'pgoutput')`,
    [slotName]
  );
}
```

#### Production Standard (Correct)
> **Standard**: Explicitly invoking pg_create_logical_replication_slot with failover := true registers the logical slot with PostgreSQL 17's slot synchronization engine. Standby instances sync LSN positions continuously via sync_replication_slots, allowing consumers to switch to a promoted replica seamlessly without message loss or duplications.
```typescript
import { Client } from 'pg';

export interface ReplicationSlotResult {
  slotName: string;
  consistentPoint: string;
}

export async function initCdcSlot(client: Client, slotName: string): Promise<ReplicationSlotResult> {
  // INVARIANT: In PostgreSQL 17+, specify failover := true.
  // Physical standbys with sync_replication_slots = on will maintain this slot's progress.
  const query = `
    SELECT slot_name, consistent_point
    FROM pg_create_logical_replication_slot(
      $1,
      'pgoutput',
      temporary := false,
      two_phase := false,
      failover := true
    );
  `;
  const result = await client.query<{ slot_name: string; consistent_point: string }>(query, [slotName]);
  
  if (result.rowCount === 0) {
    throw new Error(`Failed to create synchronized failover slot: ${slotName}`);
  }

  return {
    slotName: result.rows[0].slot_name,
    consistentPoint: result.rows[0].consistent_point,
  };
}
```

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 Slot Failover Synchronization Invariant

Postgres 17 Logical Replication Slot Failover Synchronization Invariant defines an industrial-grade behavioral standard for backend engineering. Enforces failover-enabled logical replication slots and standby slot synchronization introduced in PostgreSQL 17. Eliminates CDC event loss and duplicate replay during primary-to-standby switchover by ensuring physical standbys continuously synchronize logical replication slots before promotion. 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: Creating Logical Slots Without Failover Invariants and Blindly Switching Consumers to Out-of-Sync Standbys 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 DriftCreating Logical Slots Without Failover Invariants and Blindly Switching Consumers to Out-of-Sync StandbysCritical
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 replication slots in PostgreSQL 17+ using `pg_create_logical_replication_slot(slot_name, plugin, temporary

Engineers MUST ALWAYS provision logical replication slots in PostgreSQL 17+ using `pg_create_logical_replication_slot(slot_name, plugin, temporary := false, two_phase := false, failover := true)` to ensure slot metadata is propagated across 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 omit the `failover` parameter when initializing Change Data Capture (CDC) pipelines (e.g., Debezium, custom wal2json subscribers) against PostgreSQL 17 instances.

Engineers MUST NOT omit the `failover` parameter when initializing Change Data Capture (CDC) pipelines (e.g., Debezium, custom wal2json subscribers) against PostgreSQL 17 instances.

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

Database infrastructure configurations MUST enforce `sync_replication_slots = on` and configure `standby_slot_names` on the primary instance to guarantee physical standbys advance replication slots before logical consumers commit progress.

Database infrastructure configurations MUST enforce `sync_replication_slots = on` and configure `standby_slot_names` on the primary instance to guarantee physical standbys advance replication slots before logical consumers commit progress.

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 managing promotion or consumer reconnection MUST inspect `pg_replication_slots` and assert `sync_state` is valid or `synchronized = false` on newly promoted primaries before resuming message consumption.

Services managing promotion or consumer reconnection MUST inspect `pg_replication_slots` and assert `sync_state` is valid or `synchronized = false` on newly promoted primaries before resuming message consumption.

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 connect logical consumers to an un-promoted standby or switch consumption endpoints without verifying the replica's `confirmed_flush_lsn` matches or exceeds the consumer checkpoint.

Components NEVER connect logical consumers to an un-promoted standby or switch consumption endpoints without verifying the replica's `confirmed_flush_lsn` matches or exceeds the consumer checkpoint.

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

Enforces failover-enabled logical replication slots and standby slot synchronization introduced in PostgreSQL 17. Eliminates CDC event loss and duplicate replay during primary-to-standby switchover by ensuring physical standbys continuously synchronize logical replication slots before promotion. 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 (Creating Logical Slots Without Failover Invariants and Blindly Switching Consumers to Out-of-Sync Standbys) 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