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

PostgreSQL 17 Replication Slot Failover Synchronization Invariant

Mandates explicit logical replication slot state synchronization across physical read replicas using PostgreSQL 17 slot failover primitives. Prevents downstream CDC data loss, replay holes, and broken subscriber streams during HA standby promotion.

Prohibited Anti-Pattern: Creating Logical Slots Without Failover Capabilities or synchronized_standby_slots Interlocks

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: PostgreSQL 17 Replication Slot Failover Synchronization Invariant - Mandates explicit logical replication slot state synchronization across physical read replicas using PostgreSQL 17 slot failover primitives. Prevents downstream CDC data loss, replay holes, and broken subscriber streams during HA standby promotion.
globs: src/database/**/*.ts, src/infra/**/*.ts, migrations/**/*.sql, infra/**/*.tf
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/pg17-replication-slot-failover-sync-invariant"
---

# PostgreSQL 17 Replication Slot Failover Synchronization Invariant

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Creating Logical Slots Without Failover Capabilities or synchronized_standby_slots Interlocks

## System Constraints
You are a Principal Database Architect and Infrastructure Reliability Engineer enforcing PostgreSQL 17 Streaming Replication Slot Failover Sync Invariants. You must ensure all logical replication slots are provisioned with failover enablement ('failover = true') and synchronized across physical standbys via 'synchronized_standby_slots'. Standby promotion routines and slot creation calls must strictly validate replication slot synchronization health before proceeding.

## Strict Guidelines
- Engineers MUST ALWAYS enable the 'failover' parameter when invoking 'pg_create_logical_replication_slot' (or setting 'failover = true') in PostgreSQL 17+ environments.
- Engineers MUST configure 'synchronized_standby_slots' on the primary instance with physical standby replication slot names to prevent logical slots from outpacing physical replication.
- Engineers MUST configure 'sync_replication_slots = on' in 'postgresql.conf' on standby instances to enable background slot replication daemon sync.
- Database migration scripts and slot provisioning abstractions MUST verify that 'pg_replication_slots.failover' is 'true' and 'pg_replication_slots.synced' reflects valid standby state.
- Failover orchestration scripts MUST NEVER promote a standby until validating that 'pg_sync_replication_slots()' has fully converged or that the standby's logical slots match the primary's confirmed flush LSN.
- Services MUST query 'pg_replication_slots' to assert 'sync_state' before allowing downstream consumers (e.g., Debezium, Kafka Connect, read-model projectors) to subscribe.

## Bad vs Good Implementations
### Logical Replication Slot Provisioning & Verification Invariant

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Creating a logical replication slot without failover=true leaves the slot unsynchronized on physical standbys. If the primary crashes, the promoted standby has no record of the slot or its confirmed_flush_lsn, leading to complete stream desynchronization or permanent data loss.
```typescript
import { Client } from 'pg';

export async function provisionCdcSlot(client: Client, slotName: string): Promise<void> {
  // ANTI-PATTERN: Pre-PG17 style slot creation or omitting failover parameter.
  // This slot will not exist or sync to physical standbys during failover,
  // causing CDC subscribers to crash or suffer silent data loss upon primary promotion.
  await client.query(`
    SELECT pg_create_logical_replication_slot($1, 'pgoutput');
  `, [slotName]);
}
```

#### Production Standard (Correct)
> **Standard**: Enforces the PostgreSQL 17 invariant: explicitly sets failover=true upon logical slot creation and enforces that the physical standby slot is registered in 'synchronized_standby_slots' before creation, guaranteeing consistent slot propagation across replicas.
```typescript
import { Client } from 'pg';

export interface SlotProvisionOptions {
  slotName: string;
  plugin?: string;
  expectedStandbySlot: string;
}

export async function provisionCdcSlot(
  client: Client,
  options: SlotProvisionOptions
): Promise<void> {
  const { slotName, plugin = 'pgoutput', expectedStandbySlot } = options;

  // 1. Verify primary has synchronized_standby_slots configured
  const syncSettingRes = await client.query<{ setting: string }>(
    "SELECT setting FROM pg_settings WHERE name = 'synchronized_standby_slots'"
  );
  const configuredSyncSlots = syncSettingRes.rows[0]?.setting?.split(',').map(s => s.trim()) ?? [];

  if (!configuredSyncSlots.includes(expectedStandbySlot)) {
    throw new Error(
      `Invariant Violation: Physical standby slot '${expectedStandbySlot}' ` +
      `is not in 'synchronized_standby_slots' (${configuredSyncSlots.join(', ')}).`
    );
  }

  // 2. Provision logical slot with PG17 failover support enabled (5th parameter = true)
  await client.query(`
    SELECT pg_create_logical_replication_slot(
      $1,
      $2,
      false,
      false,
      true
    );
  `, [slotName, plugin]);

  // 3. Assert failover property is true in catalog
  const slotCheck = await client.query<{
    slot_name: string;
    failover: boolean;
  }>(
    'SELECT slot_name, failover FROM pg_replication_slots WHERE slot_name = $1',
    [slotName]
  );

  if (!slotCheck.rows[0]?.failover) {
    throw new Error(`Logical slot '${slotName}' failed to initialize with failover=true.`);
  }
}
```

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: PostgreSQL 17 Replication Slot Failover Synchronization Invariant

PostgreSQL 17 Replication Slot Failover Synchronization Invariant defines an industrial-grade behavioral standard for backend engineering. Mandates explicit logical replication slot state synchronization across physical read replicas using PostgreSQL 17 slot failover primitives. Prevents downstream CDC data loss, replay holes, and broken subscriber streams during HA standby 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 Capabilities or synchronized_standby_slots Interlocks 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 Capabilities or synchronized_standby_slots InterlocksCritical
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 enable the 'failover' parameter when invoking 'pg_create_logical_replication_slot' (or setting 'failover = true') in PostgreSQL 17+ environments.

Engineers MUST ALWAYS enable the 'failover' parameter when invoking 'pg_create_logical_replication_slot' (or setting 'failover = true') 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.
2

Engineers MUST configure 'synchronized_standby_slots' on the primary instance with physical standby replication slot names to prevent logical slots from outpacing physical replication.

Engineers MUST configure 'synchronized_standby_slots' on the primary instance with physical standby replication slot names to prevent logical slots from outpacing physical replication.

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 'sync_replication_slots = on' in 'postgresql.conf' on standby instances to enable background slot replication daemon sync.

Engineers MUST configure 'sync_replication_slots = on' in 'postgresql.conf' on standby instances to enable background slot replication daemon sync.

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

Database migration scripts and slot provisioning abstractions MUST verify that 'pg_replication_slots.failover' is 'true' and 'pg_replication_slots.synced' reflects valid standby state.

Database migration scripts and slot provisioning abstractions MUST verify that 'pg_replication_slots.failover' is 'true' and 'pg_replication_slots.synced' reflects valid standby state.

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

Failover orchestration scripts MUST NEVER promote a standby until validating that 'pg_sync_replication_slots()' has fully converged or that the standby's logical slots match the primary's confirmed flush LSN.

Failover orchestration scripts MUST NEVER promote a standby until validating that 'pg_sync_replication_slots()' has fully converged or that the standby's logical slots match the primary'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.
6

Services MUST query 'pg_replication_slots' to assert 'sync_state' before allowing downstream consumers (e.g., Debezium, Kafka Connect, read-model projectors) to subscribe.

Services MUST query 'pg_replication_slots' to assert 'sync_state' before allowing downstream consumers (e.g., Debezium, Kafka Connect, read-model projectors) to subscribe.

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

Mandates explicit logical replication slot state synchronization across physical read replicas using PostgreSQL 17 slot failover primitives. Prevents downstream CDC data loss, replay holes, and broken subscriber streams during HA standby 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 Capabilities or synchronized_standby_slots Interlocks) 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