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

PostgreSQL 17 Failover Slot Synchronization Boundary for Event-Driven CDC Pipelines

Enforces deterministic physical-to-logical replication slot synchronization across Patroni high-availability boundaries in PostgreSQL 17. Guarantees zero data loss and prevents duplicate CDC replay during planned or unplanned primary failovers by mandating synchronized failover slots and strict LSN watermark gating before consumer reconnections.

Prohibited Anti-Pattern: Unsynchronized Logical Slot Orphanage and LSN Regressions During HA Standby Promotion

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: PostgreSQL 17 Failover Slot Synchronization Boundary for Event-Driven CDC Pipelines - Enforces deterministic physical-to-logical replication slot synchronization across Patroni high-availability boundaries in PostgreSQL 17. Guarantees zero data loss and prevents duplicate CDC replay during planned or unplanned primary failovers by mandating synchronized failover slots and strict LSN watermark gating before consumer reconnections.
globs: src/infra/db/**/*.{ts,js,py,sql,yaml}, src/cdc/**/*.{ts,js,py}, deploy/patroni/**/*.{yaml,yml}, k8s/**/*.yaml
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/pg17-failover-slot-sync-boundary"
---

# PostgreSQL 17 Failover Slot Synchronization Boundary for Event-Driven CDC Pipelines

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unsynchronized Logical Slot Orphanage and LSN Regressions During HA Standby Promotion

## System Constraints
You are a Principal Engineer enforcing PostgreSQL 17 Failover Slot Synchronization Boundary. Mandate invariants: In any PostgreSQL 17 HA topology running event-driven change data capture (CDC), logical replication slots MUST be declared with 'failover = true' on the primary and explicitly synchronized via Patroni standby slot synchronization (pg_sync_replication_slots). Applications and CDC consumers MUST verify that the promoted standby's confirmed_flush_lsn is strictly greater than or equal to the consumer's persisted checkpoint before resuming replication to prevent catalog bloat, corrupted WAL advancement, or massive event duplication.

## Strict Guidelines
- Engineers MUST ALWAYS provision logical replication slots with 'failover = true' and specify 'synchronized_standby_slots' on the primary in PostgreSQL 17.
- Engineers MUST NOT allow CDC ingestion consumers to reconnect without validating that target standby confirmed_flush_lsn >= consumer_committed_lsn.
- Services MUST configure Patroni standby nodes with 'sync_replication_slots: true' to continuously mirror failover-enabled logical slots from the primary.
- Code SHOULD enforce idempotency via transactional deduplication or deterministic outbox watermarks even when PostgreSQL 17 zero-data-loss slot failover is active.
- Components NEVER drop or recreate replication slots automatically during connection failures, as this advances the confirmed_flush_lsn and triggers catastrophic data loss.

## Bad vs Good Implementations
### CDC Consumer Connection Initialization and Failover Guardrail

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Creating a slot without `failover = true` in PostgreSQL 17 means it will not be synced to standbys via Patroni. When a failover occurs, the slot disappears, forcing recreation at the current WAL position (causing data loss) or reconnection to an un-synced slot leading to duplicated or missing events.
```typescript
import { Client } from 'pg';

export async function initCdcPipeline(connectionString: string, slotName: string) {
  const client = new Client({ connectionString });
  await client.connect();

  // BAD: Blindly creating or assuming slot exists without failover flag or LSN sync check
  const slotExists = await client.query('SELECT 1 FROM pg_replication_slots WHERE slot_name = $1', [slotName]);
  if (slotExists.rowCount === 0) {
    await client.query(`SELECT pg_create_logical_replication_slot($1, 'pgoutput')`, [slotName]);
  }
  
  // Starts streaming without validating failover state or standby sync watermark
  return client;
}
```

#### Production Standard (Correct)
> **Standard**: Creates logical slots with PostgreSQL 17's failover parameter set to true and validates confirmed_flush_lsn against the committed CDC watermark prior to consuming changes, preventing both silent data loss and out-of-order replay.
```typescript
import { Client } from 'pg';

interface SlotMetadata {
  slot_name: string;
  plugin: string;
  failover: boolean;
  synced: boolean;
  confirmed_flush_lsn: string;
}

export async function initCdcPipeline(
  client: Client,
  slotName: string,
  lastCommittedLsn: string
): Promise<void> {
  const query = `
    SELECT slot_name, plugin, failover, synced, confirmed_flush_lsn::text
    FROM pg_replication_slots
    WHERE slot_name = $1;
  `;
  const result = await client.query<SlotMetadata>(query, [slotName]);

  if (result.rowCount === 0) {
    // PG17: Explicitly declare failover = true for physical-to-logical slot replication
    await client.query(
      `SELECT pg_create_logical_replication_slot($1, 'pgoutput', false, false, true);`,
      [slotName]
    );
    return;
  }

  const slot = result.rows[0];
  if (!slot.failover) {
    throw new Error(`CRITICAL: Slot ${slotName} does not have failover enabled.`);
  }

  // Gating check: Standby MUST have caught up to or exceeded the consumer checkpoint
  const lsnCheck = await client.query<{ is_ready: boolean }>(
    'SELECT pg_lsn($1) <= pg_lsn($2) AS is_ready;',
    [lastCommittedLsn, slot.confirmed_flush_lsn]
  );

  if (!lsnCheck.rows[0]?.is_ready) {
    throw new Error(
      `REPLICATION_BOUNDARY_VIOLATION: Slot confirmed LSN (${slot.confirmed_flush_lsn}) is behind consumer checkpoint (${lastCommittedLsn}). Failover sync lagging.`
    );
  }
}
```

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 Boundary for Event-Driven CDC Pipelines

PostgreSQL 17 Failover Slot Synchronization Boundary for Event-Driven CDC Pipelines defines an industrial-grade behavioral standard for backend engineering. Enforces deterministic physical-to-logical replication slot synchronization across Patroni high-availability boundaries in PostgreSQL 17. Guarantees zero data loss and prevents duplicate CDC replay during planned or unplanned primary failovers by mandating synchronized failover slots and strict LSN watermark gating before consumer reconnections. 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 Slot Orphanage and LSN Regressions During HA Standby 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 Slot Orphanage and LSN Regressions During HA Standby 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' and specify 'synchronized_standby_slots' on the primary in PostgreSQL 17.

Engineers MUST ALWAYS provision logical replication slots with 'failover = true' and specify 'synchronized_standby_slots' on the primary in PostgreSQL 17.

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 allow CDC ingestion consumers to reconnect without validating that target standby confirmed_flush_lsn >= consumer_committed_lsn.

Engineers MUST NOT allow CDC ingestion consumers to reconnect without validating that target standby confirmed_flush_lsn >= consumer_committed_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

Services MUST configure Patroni standby nodes with 'sync_replication_slots

Services MUST configure Patroni standby nodes with 'sync_replication_slots: true' to continuously mirror failover-enabled logical slots from the 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.
4

Code SHOULD enforce idempotency via transactional deduplication or deterministic outbox watermarks even when PostgreSQL 17 zero-data-loss slot failover is active.

Code SHOULD enforce idempotency via transactional deduplication or deterministic outbox watermarks even when PostgreSQL 17 zero-data-loss slot failover is active.

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 drop or recreate replication slots automatically during connection failures, as this advances the confirmed_flush_lsn and triggers catastrophic data loss.

Components NEVER drop or recreate replication slots automatically during connection failures, as this advances the confirmed_flush_lsn and triggers catastrophic data loss.

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 Boundary for Event-Driven CDC Pipelines critical for AI coding assistants?

Enforces deterministic physical-to-logical replication slot synchronization across Patroni high-availability boundaries in PostgreSQL 17. Guarantees zero data loss and prevents duplicate CDC replay during planned or unplanned primary failovers by mandating synchronized failover slots and strict LSN watermark gating before consumer reconnections. 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 Slot Orphanage and LSN Regressions During HA Standby 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