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

Postgres 17 Logical Replication Slot Failover Synchronization Boundary

Enforces failover-enabled logical slots and physical-to-logical coordination via sync_replication_slots and synchronized_standby_slots in PostgreSQL 17 HA topologies. Guarantees downstream consumers experience deterministic resumption without WAL gap corruption or silent event loss during Patroni failover events.

Prohibited Anti-Pattern: Desynchronized Logical Replication Slots Causing Data Loss and Stream Gaps on Standby Failover

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Postgres 17 Logical Replication Slot Failover Synchronization Boundary - Enforces failover-enabled logical slots and physical-to-logical coordination via sync_replication_slots and synchronized_standby_slots in PostgreSQL 17 HA topologies. Guarantees downstream consumers experience deterministic resumption without WAL gap corruption or silent event loss during Patroni failover events.
globs: src/**/*.ts, src/database/**/*.ts, migrations/**/*.sql, infra/**/*.tf, config/**/*.yaml
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/postgres-17-logical-slot-failover-boundary"
---

# Postgres 17 Logical Replication Slot Failover Synchronization Boundary

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Desynchronized Logical Replication Slots Causing Data Loss and Stream Gaps on Standby Failover

## System Constraints
You are a Principal Database Reliability Architect enforcing Postgres 17 Logical Replication Failover-Slot Sync Boundary standards. In PostgreSQL 17, failover support for logical replication slots is native via `failover => true` during slot creation, combined with `sync_replication_slots = on` on standbys and `synchronized_standby_slots` on the primary. You must reject any legacy or uncoordinated logical replication configuration, ensure strict validation of slot metadata, and enforce safe consumer failover reconnect guards.

## Strict Guidelines
- Engineers MUST ALWAYS create logical replication slots with `failover => true` using Postgres 17 native slot parameters.
- Primary Patroni nodes MUST configure `synchronized_standby_slots` to reference the physical standby slots before advancing confirmed WAL past standby positions.
- Standby Patroni nodes MUST enable `sync_replication_slots = on` and maintain hot_standby feedback to continuously replicate slot state.
- CDC services and downstream consumers MUST verify `failover = true` in `pg_replication_slots` before commencing change ingestion.
- Downstream consumers MUST NEVER reconnect after a Patroni primary election without asserting that the promoted standby's confirmed_flush_lsn is equal to or ahead of the last committed consumer offset.
- Services MUST NOT execute ad-hoc drop/recreate operations on synchronized slots while `sync_replication_slots` daemon synchronization is active.

## Bad vs Good Implementations
### Postgres 17 Failover-Safe Slot Creation and Invariant Health Check

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Omits the Postgres 17 `failover` parameter. The slot will not be tracked by standby nodes, causing downstream subscribers to stall or drop events when Patroni initiates an automatic primary failover.
```typescript
import { Client } from 'pg';

export async function initLogicalReplicationSlot(client: Client, slotName: string): Promise<void> {
  // ANTI-PATTERN: Creates legacy logical slot without failover parameter.
  // During a Patroni failover, this slot does not exist on the promoted standby,
  // causing CDC subscribers to crash or suffer unrecoverable WAL segment loss.
  await client.query(
    `SELECT pg_create_logical_replication_slot($1, 'pgoutput');`,
    [slotName]
  );
}
```

#### Production Standard (Correct)
> **Standard**: Validates engine version >= 170000, checks that primary enforces `synchronized_standby_slots` for HA standbys, and ensures the logical replication slot is initialized with `failover => true`.
```typescript
import { Client } from 'pg';

interface ReplicationSlotConfig {
  slotName: string;
  plugin?: string;
  expectedStandbySlots: string[];
}

export async function initLogicalReplicationSlot(
  client: Client,
  config: ReplicationSlotConfig
): Promise<void> {
  const { slotName, plugin = 'pgoutput', expectedStandbySlots } = config;

  // 1. Verify Postgres 17+ server version
  const versionRes = await client.query<{ server_version_num: string }>(
    'SHOW server_version_num;'
  );
  const versionNum = parseInt(versionRes.rows[0].server_version_num, 10);
  if (versionNum < 170000) {
    throw new Error(`Postgres 17+ required for failover slots. Detected: ${versionNum}`);
  }

  // 2. Validate primary synchronized_standby_slots configuration
  const syncSlotsRes = await client.query<{ synchronized_standby_slots: string }>(
    'SHOW synchronized_standby_slots;'
  );
  const activeStandbySlots = syncSlotsRes.rows[0].synchronized_standby_slots
    .split(',')
    .map((s) => s.trim());

  const missingSlots = expectedStandbySlots.filter((s) => !activeStandbySlots.includes(s));
  if (missingSlots.length > 0) {
    throw new Error(
      `Primary missing required synchronized_standby_slots: ${missingSlots.join(', ')}`
    );
  }

  // 3. Create or verify slot with failover enabled (PG17 native syntax)
  const slotCheck = await client.query<{ failover: boolean }>(
    'SELECT failover FROM pg_replication_slots WHERE slot_name = $1;',
    [slotName]
  );

  if (slotCheck.rowCount === 0) {
    await client.query(
      'SELECT pg_create_logical_replication_slot($1, $2, false, false, true);',
      [slotName, plugin]
    );
  } else if (!slotCheck.rows[0].failover) {
    throw new Error(
      `Slot ${slotName} exists but failover is false. Invariant violation for HA topology.`
    );
  }
}
```

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 Slot Failover Synchronization Boundary

Postgres 17 Logical Replication Slot Failover Synchronization Boundary defines an industrial-grade behavioral standard for backend engineering. Enforces failover-enabled logical slots and physical-to-logical coordination via sync_replication_slots and synchronized_standby_slots in PostgreSQL 17 HA topologies. Guarantees downstream consumers experience deterministic resumption without WAL gap corruption or silent event loss during Patroni failover events. 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: Desynchronized Logical Replication Slots Causing Data Loss and Stream Gaps on Standby 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 DriftDesynchronized Logical Replication Slots Causing Data Loss and Stream Gaps on Standby 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 create logical replication slots with `failover => true` using Postgres 17 native slot parameters.

Engineers MUST ALWAYS create logical replication slots with `failover => true` using Postgres 17 native slot parameters.

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

Primary Patroni nodes MUST configure `synchronized_standby_slots` to reference the physical standby slots before advancing confirmed WAL past standby positions.

Primary Patroni nodes MUST configure `synchronized_standby_slots` to reference the physical standby slots before advancing confirmed WAL past standby positions.

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

Standby Patroni nodes MUST enable `sync_replication_slots = on` and maintain hot_standby feedback to continuously replicate slot state.

Standby Patroni nodes MUST enable `sync_replication_slots = on` and maintain hot_standby feedback to continuously replicate 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.
4

CDC services and downstream consumers MUST verify `failover = true` in `pg_replication_slots` before commencing change ingestion.

CDC services and downstream consumers MUST verify `failover = true` in `pg_replication_slots` before commencing change ingestion.

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

Downstream consumers MUST NEVER reconnect after a Patroni primary election without asserting that the promoted standby's confirmed_flush_lsn is equal to or ahead of the last committed consumer offset.

Downstream consumers MUST NEVER reconnect after a Patroni primary election without asserting that the promoted standby's confirmed_flush_lsn is equal to or ahead of the last committed consumer offset.

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 NOT execute ad-hoc drop/recreate operations on synchronized slots while `sync_replication_slots` daemon synchronization is active.

Services MUST NOT execute ad-hoc drop/recreate operations on synchronized slots while `sync_replication_slots` daemon synchronization 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.
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 Slot Failover Synchronization Boundary critical for AI coding assistants?

Enforces failover-enabled logical slots and physical-to-logical coordination via sync_replication_slots and synchronized_standby_slots in PostgreSQL 17 HA topologies. Guarantees downstream consumers experience deterministic resumption without WAL gap corruption or silent event loss during Patroni failover events. 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 (Desynchronized Logical Replication Slots Causing Data Loss and Stream Gaps on Standby 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