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

Postgres 17 Failover Slot Synchronization and Replication Barrier Guardrail

Enforces Postgres 17 logical replication slot synchronization across high-availability physical standby nodes via synchronized failover slots and synchronized replication barriers (`sync_replication_slots`). Guarantees zero message loss, eliminates duplicate message replay storms, and prevents downstream subscriber split-brain during standby promotion by blocking replication advancement past unconfirmed physical standby LSN barriers.

Prohibited Anti-Pattern: Creating uncoordinated logical replication slots vulnerable to post-failover data loss or re-streaming duplicate message storms.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Postgres 17 Failover Slot Synchronization and Replication Barrier Guardrail - Enforces Postgres 17 logical replication slot synchronization across high-availability physical standby nodes via synchronized failover slots and synchronized replication barriers (`sync_replication_slots`). Guarantees zero message loss, eliminates duplicate message replay storms, and prevents downstream subscriber split-brain during standby promotion by blocking replication advancement past unconfirmed physical standby LSN barriers.
globs: src/**/*.service.ts, src/**/*.config.ts, src/database/**/*.ts, src/replication/**/*.ts, migrations/**/*.sql, deploy/db/**/*.conf
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/postgres-17-failover-slot-sync-replication-barrier"
---

# Postgres 17 Failover Slot Synchronization and Replication Barrier Guardrail

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Creating uncoordinated logical replication slots vulnerable to post-failover data loss or re-streaming duplicate message storms.

## System Constraints
You are a Principal Database Infrastructure Engineer enforcing Postgres 17 logical failover slot invariants. In distributed CDC pipelines and transactional event publishing architectures, logical slots must remain durable across physical standby promotion. You must guarantee that all logical replication slots are provisioned with `failover = true`, primary instances configure `synchronized_standby_slots`, and standbys run with `sync_replication_slots = on`. Reject any client connection routing logic or migration script that interacts with logical slots without verifying failover synchronization status.

## Strict Guidelines
- Engineers MUST ALWAYS provision logical replication slots with `failover = true` in PostgreSQL 17+ environments.
- Engineers MUST explicitly verify physical standby nodes mirror logical slot progression via `pg_sync_replication_slots()` or the background `sync_replication_slots = on` worker.
- Database administrators MUST list downstream standby application names in `synchronized_standby_slots` on the primary to prevent the primary from advancing its WAL cleanup ahead of physical standbys.
- Replication workers and CDC consumers MUST validate `sync_state` via `pg_replication_slots` before redirecting downstream subscribers during physical failovers.
- Engineers MUST NOT create logical replication slots with default parameters (`failover = false`) for critical event streaming pipelines (e.g., Debezium, Outbox processors).
- Connection pooling and automated failover scripts MUST inspect `pg_replication_slots.failover` and `pg_replication_slots.synced` on the promoted replica before unpausing subscription consumption.

## Bad vs Good Implementations
### Logical Replication Slot Provisioning & Barrier Synchronization Verification

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Omitting the 'failover' parameter creates a legacy logical replication slot that is not synchronized to physical standbys. Upon primary node failure and subsequent standby promotion, the slot disappears, causing subscriber downtime, CDC breakage, or extreme message loss and replay storms.
```typescript
import { Client } from 'pg';

export async function initReplicationSlot(client: Client, slotName: string): Promise<void> {
  // Anti-pattern: Postgres 16-style slot creation without Postgres 17 failover barrier flags.
  // If the primary fails over, this slot does not exist on the standby, causing downstream failure
  // or data loss/resets.
  await client.query(
    `SELECT pg_create_logical_replication_slot($1, 'pgoutput');`,
    [slotName]
  );
}
```

#### Production Standard (Correct)
> **Standard**: Validates server compatibility (PG 17+), initializes the slot using named parameters including `failover => true` and `twophase => true`, and queries `pg_replication_slots` to verify proper barrier configuration.
```typescript
import { Client } from 'pg';

interface ReplicationSlotConfig {
  slotName: string;
  plugin?: string;
  failover?: boolean;
}

export async function initReplicationSlot(
  client: Client,
  config: ReplicationSlotConfig
): Promise<void> {
  const plugin = config.plugin ?? 'pgoutput';
  const failover = config.failover ?? true;

  // Verify Postgres 17+ support
  const versionRes = await client.query('SHOW server_version_num;');
  const serverVersion = parseInt(versionRes.rows[0].server_version_num, 10);

  if (serverVersion < 170000) {
    throw new Error('Postgres 17 or higher is required for failover slot synchronization');
  }

  // Create logical replication slot with Postgres 17 failover = true flag
  await client.query(
    `SELECT pg_create_logical_replication_slot(
      slot_name => $1,
      plugin => $2,
      temporary => false,
      twophase => true,
      failover => $3
    );`,
    [config.slotName, plugin, failover]
  );

  // Verify slot status and failover enablement
  const check = await client.query(
    `SELECT slot_name, failover, synced 
     FROM pg_replication_slots 
     WHERE slot_name = $1;`,
    [config.slotName]
  );

  if (!check.rows[0]?.failover) {
    throw new Error(`Failed to initialize failover-synchronized slot for ${config.slotName}`);
  }
}
```

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 Slot Synchronization and Replication Barrier Guardrail

Postgres 17 Failover Slot Synchronization and Replication Barrier Guardrail defines an industrial-grade behavioral standard for backend engineering. Enforces Postgres 17 logical replication slot synchronization across high-availability physical standby nodes via synchronized failover slots and synchronized replication barriers (`sync_replication_slots`). Guarantees zero message loss, eliminates duplicate message replay storms, and prevents downstream subscriber split-brain during standby promotion by blocking replication advancement past unconfirmed physical standby LSN barriers. 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 uncoordinated logical replication slots vulnerable to post-failover data loss or re-streaming duplicate message storms. 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 uncoordinated logical replication slots vulnerable to post-failover data loss or re-streaming duplicate message storms.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 with `failover = true` in PostgreSQL 17+ environments.

Engineers MUST ALWAYS provision logical replication slots with `failover = true` in PostgreSQL 17+ environments.

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 explicitly verify physical standby nodes mirror logical slot progression via `pg_sync_replication_slots()` or the background `sync_replication_slots = on` worker.

Engineers MUST explicitly verify physical standby nodes mirror logical slot progression via `pg_sync_replication_slots()` or the background `sync_replication_slots = on` worker.

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

Database administrators MUST list downstream standby application names in `synchronized_standby_slots` on the primary to prevent the primary from advancing its WAL cleanup ahead of physical standbys.

Database administrators MUST list downstream standby application names in `synchronized_standby_slots` on the primary to prevent the primary from advancing its WAL cleanup ahead of physical standbys.

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

Replication workers and CDC consumers MUST validate `sync_state` via `pg_replication_slots` before redirecting downstream subscribers during physical failovers.

Replication workers and CDC consumers MUST validate `sync_state` via `pg_replication_slots` before redirecting downstream subscribers during physical failovers.

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

Engineers MUST NOT create logical replication slots with default parameters (`failover = false`) for critical event streaming pipelines (e.g., Debezium, Outbox processors).

Engineers MUST NOT create logical replication slots with default parameters (`failover = false`) for critical event streaming pipelines (e.g., Debezium, Outbox processors).

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

Connection pooling and automated failover scripts MUST inspect `pg_replication_slots.failover` and `pg_replication_slots.synced` on the promoted replica before unpausing subscription consumption.

Connection pooling and automated failover scripts MUST inspect `pg_replication_slots.failover` and `pg_replication_slots.synced` on the promoted replica before unpausing subscription consumption.

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 Slot Synchronization and Replication Barrier Guardrail critical for AI coding assistants?

Enforces Postgres 17 logical replication slot synchronization across high-availability physical standby nodes via synchronized failover slots and synchronized replication barriers (`sync_replication_slots`). Guarantees zero message loss, eliminates duplicate message replay storms, and prevents downstream subscriber split-brain during standby promotion by blocking replication advancement past unconfirmed physical standby LSN barriers. 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 uncoordinated logical replication slots vulnerable to post-failover data loss or re-streaming duplicate message storms.) 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