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-postgres-17-logi-754

Postgres 17 Logical Replication Failover Slot Sync Determinism

Enforces synchronous logical replication slot synchronization on standby instances using PostgreSQL 17 failover slot capabilities (`failover = true` and `sync_replication_slots = true`). Guarantees that consumer subscribers and outbox processors avoid missing transactions or suffering unconstrained rewind replay cascades during automated physical HA failover.

Prohibited Anti-Pattern: Unsynchronized Logical Slots Causing Silent Message Loss or Catastrophic Replay During Primary Failover

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Postgres 17 Logical Replication Failover Slot Sync Determinism - Enforces synchronous logical replication slot synchronization on standby instances using PostgreSQL 17 failover slot capabilities (`failover = true` and `sync_replication_slots = true`). Guarantees that consumer subscribers and outbox processors avoid missing transactions or suffering unconstrained rewind replay cascades during automated physical HA failover.
globs: src/**/*.{ts,js,py,go,sql}, migrations/**/*.{sql,ts}, infrastructure/**/*.{tf,yaml,json}, deploy/**/*.{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-postgres-17-logi-754"
---

# Postgres 17 Logical Replication Failover Slot Sync Determinism

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unsynchronized Logical Slots Causing Silent Message Loss or Catastrophic Replay During Primary Failover

## System Constraints
You are a Principal Database Architect and Distributed Systems Engineer enforcing PostgreSQL 17 logical replication failover slot determinism. Mandate strict adherence to PG17 logical slot synchronization semantics, standby promotion slot alignment, idempotent subscriber consumption, and deterministic consumer LSN acknowledgment to prevent downstream data divergence and transaction omission.

## Strict Guidelines
- Engineers MUST ALWAYS provision logical replication slots intended for failover survival with `failover = true` on the primary instance (`pg_create_logical_replication_slot(slot_name, plugin, false, false, true)`).
- Engineers MUST ALWAYS configure `sync_replication_slots = true` and define `synchronized_standby_slots` in PostgreSQL 17 primary configurations to ensure physical standbys do not lag behind logical consumers before commit.
- Engineers MUST NOT rely on default, non-failover slots (`failover = false`) for critical message dispatchers, CDC connectors, or transactional outbox workers subject to HA failover.
- Engineers MUST ensure downstream consumers and CDC connectors verify `pg_replication_slots.synced` on the standby and establish reconnection logic capable of handling LSN rewind or matching the promoted slot state.
- Subscribers MUST implement idempotent processing keyed on the original source transaction ID or unique domain event ID to handle duplicate delivery resulting from standby LSN conservative advancement.

## Bad vs Good Implementations
### Provisioning and Consuming Logical Replication Slot with PG17 Failover Protection

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Creating a logical replication slot without explicitly passing failover: true causes the slot to remain local to the primary. Upon HA failover, the promoted standby lacks the slot entirely, causing replication collapse and silent message dropping.
```typescript
import { Client } from 'pg';

export async function initConsumerSlot(client: Client, slotName: string): Promise<void> {
  // VULNERABLE: Uses legacy slot creation without failover=true.
  // During an HA switchover or promotion, this slot is missing on the new primary,
  // causing CDC stream termination or massive replay from arbitrary restart points.
  await client.query(`
    SELECT slot_name, consistent_point
    FROM pg_create_logical_replication_slot($1, 'pgoutput');
  `, [slotName]);
}

export async function handleStreamMessage(event: { id: string; payload: unknown }, ack: () => Promise<void>): Promise<void> {
  // VULNERABLE: Direct side-effect execution without idempotency checks
  await processExternalSideEffect(event.payload);
  await ack();
}

declare function processExternalSideEffect(payload: unknown): Promise<void>;
```

#### Production Standard (Correct)
> **Standard**: Specifies `failover: true` in `pg_create_logical_replication_slot`, ensuring slot metadata synchronizes to physical standbys. Combines this with transactional idempotency checks on message processing to absorb unavoidable duplicate deliveries caused by conservative LSN synchronization.
```typescript
import { Client } from 'pg';

interface ReplicationSlotConfig {
  slotName: string;
  outputPlugin: string;
}

export async function initConsumerSlot(client: Client, config: ReplicationSlotConfig): Promise<void> {
  // SECURE: Enforces Postgres 17 failover=true parameter.
  // pg_create_logical_replication_slot(slot_name, plugin, temporary, two_phase, failover)
  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(
          $1, 
          $2, 
          false, -- temporary
          false, -- two_phase
          true   -- failover (PG17+)
        );
      END IF;
    END
    $$;
  `, [config.slotName, config.outputPlugin]);
}

export async function handleStreamMessage(
  client: Client,
  event: { eventId: string; lsn: string; payload: unknown },
  ack: (lsn: string) => Promise<void>
): Promise<void> {
  // SECURE: Idempotent processing guard ensuring resilience against rewind post-failover
  await client.query('BEGIN');
  try {
    const res = await client.query(
      `INSERT INTO processed_events (event_id, processed_at)
       VALUES ($1, NOW())
       ON CONFLICT (event_id) DO NOTHING
       RETURNING event_id;`,
      [event.eventId]
    );

    if (res.rowCount && res.rowCount > 0) {
      await processExternalSideEffect(event.payload);
    }

    await client.query('COMMIT');
    await ack(event.lsn);
  } catch (err) {
    await client.query('ROLLBACK');
    throw err;
  }
}

declare function processExternalSideEffect(payload: unknown): Promise<void>;
```

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 Sync Determinism

Postgres 17 Logical Replication Failover Slot Sync Determinism defines an industrial-grade behavioral standard for backend engineering. Enforces synchronous logical replication slot synchronization on standby instances using PostgreSQL 17 failover slot capabilities (`failover = true` and `sync_replication_slots = true`). Guarantees that consumer subscribers and outbox processors avoid missing transactions or suffering unconstrained rewind replay cascades during automated physical HA failover. 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 Causing Silent Message Loss or Catastrophic Replay During Primary 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 Slots Causing Silent Message Loss or Catastrophic Replay During Primary 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 provision logical replication slots intended for failover survival with `failover = true` on the primary instance (`pg_create_logical_replication_slot(slot_name, plugin, false, false, true)`).

Engineers MUST ALWAYS provision logical replication slots intended for failover survival with `failover = true` on the primary instance (`pg_create_logical_replication_slot(slot_name, plugin, false, false, true)`).

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 configure `sync_replication_slots = true` and define `synchronized_standby_slots` in PostgreSQL 17 primary configurations to ensure physical standbys do not lag behind logical consumers before commit.

Engineers MUST ALWAYS configure `sync_replication_slots = true` and define `synchronized_standby_slots` in PostgreSQL 17 primary configurations to ensure physical standbys do not lag behind logical consumers before commit.

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 NOT rely on default, non-failover slots (`failover = false`) for critical message dispatchers, CDC connectors, or transactional outbox workers subject to HA failover.

Engineers MUST NOT rely on default, non-failover slots (`failover = false`) for critical message dispatchers, CDC connectors, or transactional outbox workers subject to HA failover.

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 ensure downstream consumers and CDC connectors verify `pg_replication_slots.synced` on the standby and establish reconnection logic capable of handling LSN rewind or matching the promoted slot state.

Engineers MUST ensure downstream consumers and CDC connectors verify `pg_replication_slots.synced` on the standby and establish reconnection logic capable of handling LSN rewind or matching the promoted slot 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

Subscribers MUST implement idempotent processing keyed on the original source transaction ID or unique domain event ID to handle duplicate delivery resulting from standby LSN conservative advancement.

Subscribers MUST implement idempotent processing keyed on the original source transaction ID or unique domain event ID to handle duplicate delivery resulting from standby LSN conservative advancement.

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

Enforces synchronous logical replication slot synchronization on standby instances using PostgreSQL 17 failover slot capabilities (`failover = true` and `sync_replication_slots = true`). Guarantees that consumer subscribers and outbox processors avoid missing transactions or suffering unconstrained rewind replay cascades during automated physical HA failover. 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 Causing Silent Message Loss or Catastrophic Replay During Primary 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