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

Postgres 17 Failover Replication Slots & Idempotent CDC Outbox Continuity

Enforces Postgres 17 failover-enabled logical replication slots and physical standby synchronization barriers for Transactional Outbox CDC pipelines. Prevents silent WAL truncation, event drops, and replay storms during primary failover and standby promotion by guaranteeing slot persistence across timeline switches.

Prohibited Anti-Pattern: Creating un-synchronized legacy logical replication slots without failover flags and running un-hedged CDC tailing vulnerable to standby promotion data loss.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Postgres 17 Failover Replication Slots & Idempotent CDC Outbox Continuity - Enforces Postgres 17 failover-enabled logical replication slots and physical standby synchronization barriers for Transactional Outbox CDC pipelines. Prevents silent WAL truncation, event drops, and replay storms during primary failover and standby promotion by guaranteeing slot persistence across timeline switches.
globs: src/**/*.ts, src/**/*.sql, migrations/**/*.sql, infra/**/*.tf
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/postgres-17-failover-replication-slots-cdc-integrity"
---

# Postgres 17 Failover Replication Slots & Idempotent CDC Outbox Continuity

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Creating un-synchronized legacy logical replication slots without failover flags and running un-hedged CDC tailing vulnerable to standby promotion data loss.

## System Constraints
You are a Principal Database Infrastructure and Backend Architect enforcing Postgres 17 Failover Replication Slots and CDC Outbox integrity. You must guarantee zero event loss and strictly bounded deduplication during primary promotion and timeline changes.

## Strict Guidelines
- Engineers MUST ALWAYS provision logical replication slots in PostgreSQL 17+ with the 'failover' parameter set to true via pg_create_logical_replication_slot(slot_name, plugin, false, false, true).
- Engineers MUST ALWAYS declare logical slot names in 'synchronized_standby_slots' on the primary cluster to ensure physical standbys do not advance past the logical slot LSN.
- Engineers MUST verify that physical standbys enable 'sync_replication_slots = on' and 'hot_standby_feedback = on' to prevent vacuum from cleaning dead tuples required by logical decoding.
- CDC consumers MUST persist confirmed_flush_lsn atomically alongside outbox message commits or downstream broker confirmations, enforcing monotonic LSN checkpointing.
- CDC consumer reconnection logic MUST inspect the target node's 'pg_is_in_recovery()' status and verify slot availability before consuming events following database switchovers.
- Downstream consumers MUST implement deterministic deduplication using an outbox UUID or composite key (aggregate_type, aggregate_id, sequence_number) to absorb replay overlap from pre-flush WAL buffers.
- Engineers MUST NOT rely on ephemeral or local-only logical slots without failover enabled for production CDC pipelines.

## Bad vs Good Implementations
### Failover-Safe Logical Replication Slot Provisioning & Verification

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Legacy pg_create_logical_replication_slot invocations default to failover=false. When a failover occurs, the promoted standby does not synchronize or maintain the slot, resulting in missing replication slots on the new primary, breaking the outbox CDC pipeline and losing unread events.
```typescript
import { Client } from 'pg';

export async function setupOutboxSlot(client: Client, slotName: string): Promise<void> {
  // VULNERABLE: Uses legacy slot creation without failover=true.
  // Upon primary failover, this slot will not exist on the promoted standby,
  // leading to permanent CDC stream halt or catastrophic event loss.
  await client.query(
    `SELECT pg_create_logical_replication_slot($1, 'pgoutput');`,
    [slotName]
  );
}
```

#### Production Standard (Correct)
> **Standard**: Leverages Postgres 17's failover=true capability directly during creation and uses pg_alter_replication_slot as a migration fallback. Checks synchronized_standby_slots to ensure physical standbys retain the WAL needed for zero-loss consumer failover.
```typescript
import { Client } from 'pg';

interface SlotMetadata {
  slotName: string;
  plugin: string;
  failover: boolean;
  synced: boolean;
  confirmedFlushLsn: string | null;
}

export async function setupOutboxSlot(
  client: Client,
  slotName: string,
  plugin: string = 'pgoutput'
): Promise<void> {
  // In Postgres 17, pg_create_logical_replication_slot supports the failover parameter:
  // pg_create_logical_replication_slot(slot_name, plugin, temporary, two_phase, failover)
  const slotCheck = await client.query<SlotMetadata>(
    `SELECT slot_name as "slotName", plugin, failover, synced, confirmed_flush_lsn as "confirmedFlushLsn"
     FROM pg_replication_slots
     WHERE slot_name = $1;`,
    [slotName]
  );

  if (slotCheck.rows.length === 0) {
    await client.query(
      `SELECT pg_create_logical_replication_slot(
         slot_name => $1,
         plugin => $2,
         temporary => false,
         two_phase => false,
         failover => true
       );`,
      [slotName, plugin]
    );
  } else {
    const existing = slotCheck.rows[0];
    if (!existing.failover) {
      // In PG 17, alter replication slot to enable failover if not configured
      await client.query(
        `SELECT pg_alter_replication_slot($1, failover => true);`,
        [slotName]
      );
    }
  }

  // Assert synchronized_standby_slots configuration guard
  const syncCheck = await client.query<{ setting: string }>(
    `SELECT current_setting('synchronized_standby_slots', true) AS setting;`
  );
  const synchronizedSlots = (syncCheck.rows[0]?.setting || '')
    .split(',')
    .map(s => s.trim());

  if (!synchronizedSlots.includes(slotName) && synchronizedSlots[0] !== '*') {
    console.warn(
      `CRITICAL ALERT: Slot ${slotName} is not listed in 'synchronized_standby_slots'. ` +
      `Physical standbys may purge WAL prior to logical replication sync.`
    );
  }
}
```

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 Failover Replication Slots & Idempotent CDC Outbox Continuity

Postgres 17 Failover Replication Slots & Idempotent CDC Outbox Continuity defines an industrial-grade behavioral standard for backend engineering. Enforces Postgres 17 failover-enabled logical replication slots and physical standby synchronization barriers for Transactional Outbox CDC pipelines. Prevents silent WAL truncation, event drops, and replay storms during primary failover and standby promotion by guaranteeing slot persistence across timeline switches. 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 un-synchronized legacy logical replication slots without failover flags and running un-hedged CDC tailing vulnerable to standby promotion data loss. 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 un-synchronized legacy logical replication slots without failover flags and running un-hedged CDC tailing vulnerable to standby promotion data loss.Critical
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+ with the 'failover' parameter set to true via pg_create_logical_replication_slot(slot_name, plugin, false, false, true).

Engineers MUST ALWAYS provision logical replication slots in PostgreSQL 17+ with the 'failover' parameter set to true via 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 declare logical slot names in 'synchronized_standby_slots' on the primary cluster to ensure physical standbys do not advance past the logical slot LSN.

Engineers MUST ALWAYS declare logical slot names in 'synchronized_standby_slots' on the primary cluster to ensure physical standbys do not advance past the logical slot 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.
3

Engineers MUST verify that physical standbys enable 'sync_replication_slots = on' and 'hot_standby_feedback = on' to prevent vacuum from cleaning dead tuples required by logical decoding.

Engineers MUST verify that physical standbys enable 'sync_replication_slots = on' and 'hot_standby_feedback = on' to prevent vacuum from cleaning dead tuples required by logical decoding.

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

CDC consumers MUST persist confirmed_flush_lsn atomically alongside outbox message commits or downstream broker confirmations, enforcing monotonic LSN checkpointing.

CDC consumers MUST persist confirmed_flush_lsn atomically alongside outbox message commits or downstream broker confirmations, enforcing monotonic LSN checkpointing.

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 consumer reconnection logic MUST inspect the target node's 'pg_is_in_recovery()' status and verify slot availability before consuming events following database switchovers.

CDC consumer reconnection logic MUST inspect the target node's 'pg_is_in_recovery()' status and verify slot availability before consuming events following database switchovers.

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

Downstream consumers MUST implement deterministic deduplication using an outbox UUID or composite key (aggregate_type, aggregate_id, sequence_number) to absorb replay overlap from pre-flush WAL buffers.

Downstream consumers MUST implement deterministic deduplication using an outbox UUID or composite key (aggregate_type, aggregate_id, sequence_number) to absorb replay overlap from pre-flush WAL buffers.

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

Engineers MUST NOT rely on ephemeral or local-only logical slots without failover enabled for production CDC pipelines.

Engineers MUST NOT rely on ephemeral or local-only logical slots without failover enabled for production CDC pipelines.

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 Failover Replication Slots & Idempotent CDC Outbox Continuity critical for AI coding assistants?

Enforces Postgres 17 failover-enabled logical replication slots and physical standby synchronization barriers for Transactional Outbox CDC pipelines. Prevents silent WAL truncation, event drops, and replay storms during primary failover and standby promotion by guaranteeing slot persistence across timeline switches. 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 un-synchronized legacy logical replication slots without failover flags and running un-hedged CDC tailing vulnerable to standby promotion data loss.) 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