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

PostgreSQL 17 Failover Slot Synchronization & Logical Outbox Idempotency

Enforces strict failover synchronization invariants for PostgreSQL 17 logical replication slots across HA clusters. Mandates the use of 'failover = true' on primary publication slots, coordinated pg_sync_replication_slots() synchronization on standbys, and consumer-side deterministic LSN/transaction-ID deduplication to prevent message replay storms and outbox corruption following cluster promotion.

Prohibited Anti-Pattern: Unsynchronized Logical Slots and Non-Idempotent Outbox Consumption Trigger Massive Data Duplication on Promotion

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: PostgreSQL 17 Failover Slot Synchronization & Logical Outbox Idempotency - Enforces strict failover synchronization invariants for PostgreSQL 17 logical replication slots across HA clusters. Mandates the use of 'failover = true' on primary publication slots, coordinated pg_sync_replication_slots() synchronization on standbys, and consumer-side deterministic LSN/transaction-ID deduplication to prevent message replay storms and outbox corruption following cluster promotion.
globs: src/infrastructure/database/**/*.ts, src/replication/**/*.ts, src/cdc/**/*.ts, src/outbox/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/postgres17-logical-failover-slot-sync-invariants"
---

# PostgreSQL 17 Failover Slot Synchronization & Logical Outbox Idempotency

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unsynchronized Logical Slots and Non-Idempotent Outbox Consumption Trigger Massive Data Duplication on Promotion

## System Constraints
You are a Principal Database Infrastructure Engineer enforcing PostgreSQL 17 logical replication failover slot synchronization invariants. Ensure all logical replication slots are provisioned with failover enablement, synchronized to physical standbys via synchronized_standby_slots or active synchronization daemons, and paired with strictly idempotent CDC/Outbox consumers.

## Strict Guidelines
- Engineers MUST ALWAYS provision logical replication slots with `failover = true` in PostgreSQL 17 when high-availability physical standbys are present (`SELECT pg_create_logical_replication_slot('slot_name', 'pgoutput', false, false, true)`).
- Engineers MUST ensure that the physical standby cluster registers target logical slot names in `synchronized_standby_slots` on the primary to prevent physical replication from advancing past logical slot restart LSNs.
- Engineers MUST NOT advance logical replication slot confirmation (`pg_replication_origin_advance` or pg_logical slot ACK) before persisting consumer-side monotonic LSN watermarks in an ACID transaction.
- Consumer services MUST maintain deterministic deduplication tables keyed by `(origin_xid, origin_lsn)` to guarantee idempotency during promotion reconciliation when restart LSN rewinds.
- CDC services NEVER assume seamless zero-gap failover; clients MUST gracefully handle `ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE` during promotion and reconnect only after verifying `pg_is_in_recovery() = false` and slot presence on the promoted primary.

## Bad vs Good Implementations
### PostgreSQL 17 Failover-Enabled Slot Creation and Standby Synchronization Verification

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Creating the logical replication slot without `failover = true` (parameter 5 in PG17) prevents the standby from replicating the slot state. Upon failover, the slot does not exist on the promoted node. Additionally, outbox consumption lacks transactional LSN tracking, causing duplicated execution on rewind.
```typescript
import { Client } from 'pg';

export async function initLogicalReplicationSlot(client: Client, slotName: string): Promise<void> {
  // Anti-pattern: Missing PG17 failover parameter; slot will NOT sync to standby
  // When primary dies, promoted replica loses slot state completely
  await client.query(
    `SELECT pg_create_logical_replication_slot($1, 'pgoutput', false, false);`,
    [slotName]
  );
}

export async function processOutboxMessage(client: Client, message: { id: string; payload: unknown }): Promise<void> {
  // Anti-pattern: No idempotent deduplication based on transaction ID or LSN
  await client.query(
    `INSERT INTO processed_events (event_id, payload) VALUES ($1, $2);`,
    [message.id, JSON.stringify(message.payload)]
  );
}
```

#### Production Standard (Correct)
> **Standard**: Configures PostgreSQL 17 logical slot with failover persistence enabled (`failover = true`). Implements strict atomic CDC deduplication using commit LSN and transaction ID to safely absorb restart-LSN replay loops following failover promotion.
```typescript
import { PoolClient } from 'pg';

interface ReplicationCommitRecord {
  slotName: string;
  commitLsn: string;
  transactionId: string;
  eventId: string;
  payload: Record<string, unknown>;
}

export async function ensurePg17FailoverSlot(client: PoolClient, slotName: string): Promise<void> {
  // PG17: parameter 5 is 'failover = true', ensuring slot metadata syncs 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(
          $1,           -- slot_name
          'pgoutput',   -- plugin
          false,        -- temporary
          false,        -- two_phase
          true          -- failover (PostgreSQL 17+)
        );
      END IF;
    END
    $$;
  `, [slotName]);
}

export async function consumeOutboxTransactionallyIdempotent(
  client: PoolClient,
  record: ReplicationCommitRecord
): Promise<boolean> {
  await client.query('BEGIN;');
  try {
    // Invariant: Deduplicate using PG origin XID and LSN to absorb failover restart-LSN rewinds
    const dedupeResult = await client.query(
      `INSERT INTO cdc_processed_watermarks (slot_name, commit_lsn, transaction_id, processed_at)
       VALUES ($1, $2::pg_lsn, $3, NOW())
       ON CONFLICT (slot_name, transaction_id) DO NOTHING
       RETURNING transaction_id;`,
      [record.slotName, record.commitLsn, record.transactionId]
    );

    if (dedupeResult.rowCount === 0) {
      // Already processed before failover; drop replay safely
      await client.query('COMMIT;');
      return false;
    }

    await client.query(
      `INSERT INTO business_events (event_id, payload) VALUES ($1, $2)
       ON CONFLICT (event_id) DO UPDATE SET payload = EXCLUDED.payload;`,
      [record.eventId, JSON.stringify(record.payload)]
    );

    await client.query('COMMIT;');
    return true;
  } catch (error) {
    await client.query('ROLLBACK;');
    throw error;
  }
}
```

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 Failover Slot Synchronization & Logical Outbox Idempotency

PostgreSQL 17 Failover Slot Synchronization & Logical Outbox Idempotency defines an industrial-grade behavioral standard for backend engineering. Enforces strict failover synchronization invariants for PostgreSQL 17 logical replication slots across HA clusters. Mandates the use of 'failover = true' on primary publication slots, coordinated pg_sync_replication_slots() synchronization on standbys, and consumer-side deterministic LSN/transaction-ID deduplication to prevent message replay storms and outbox corruption following cluster 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: Unsynchronized Logical Slots and Non-Idempotent Outbox Consumption Trigger Massive Data Duplication on Promotion 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 and Non-Idempotent Outbox Consumption Trigger Massive Data Duplication on PromotionCritical
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 with `failover = true` in PostgreSQL 17 when high-availability physical standbys are present (`SELECT pg_create_logical_replication_slot('slot_name', 'pgoutput', false, false, true)`).

Engineers MUST ALWAYS provision logical replication slots with `failover = true` in PostgreSQL 17 when high-availability physical standbys are present (`SELECT pg_create_logical_replication_slot('slot_name', 'pgoutput', 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 ensure that the physical standby cluster registers target logical slot names in `synchronized_standby_slots` on the primary to prevent physical replication from advancing past logical slot restart LSNs.

Engineers MUST ensure that the physical standby cluster registers target logical slot names in `synchronized_standby_slots` on the primary to prevent physical replication from advancing past logical slot restart LSNs.

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 advance logical replication slot confirmation (`pg_replication_origin_advance` or pg_logical slot ACK) before persisting consumer-side monotonic LSN watermarks in an ACID transaction.

Engineers MUST NOT advance logical replication slot confirmation (`pg_replication_origin_advance` or pg_logical slot ACK) before persisting consumer-side monotonic LSN watermarks in an ACID transaction.

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

Consumer services MUST maintain deterministic deduplication tables keyed by `(origin_xid, origin_lsn)` to guarantee idempotency during promotion reconciliation when restart LSN rewinds.

Consumer services MUST maintain deterministic deduplication tables keyed by `(origin_xid, origin_lsn)` to guarantee idempotency during promotion reconciliation when restart LSN rewinds.

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

CDC services NEVER assume seamless zero-gap failover

CDC services NEVER assume seamless zero-gap failover; clients MUST gracefully handle `ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE` during promotion and reconnect only after verifying `pg_is_in_recovery() = false` and slot presence on the promoted 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.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is PostgreSQL 17 Failover Slot Synchronization & Logical Outbox Idempotency critical for AI coding assistants?

Enforces strict failover synchronization invariants for PostgreSQL 17 logical replication slots across HA clusters. Mandates the use of 'failover = true' on primary publication slots, coordinated pg_sync_replication_slots() synchronization on standbys, and consumer-side deterministic LSN/transaction-ID deduplication to prevent message replay storms and outbox corruption following cluster 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 (Unsynchronized Logical Slots and Non-Idempotent Outbox Consumption Trigger Massive Data Duplication on Promotion) 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